From 83abd40456d879927ed429646c92f6af288bd67b Mon Sep 17 00:00:00 2001 From: chai2010 Date: Sat, 15 Dec 2018 00:29:04 +0800 Subject: [PATCH] =?UTF-8?q?examples:=20=E7=A7=BB=E9=99=A4=E7=AC=AC?= =?UTF-8?q?=E4=B8=89=E6=96=B9=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/README.md | 10 - .../docker/docker/pkg/pubsub/publisher.go | 121 - .../docker/pkg/pubsub/publisher_test.go | 142 - .../github.com/golang/protobuf/.gitignore | 17 - .../github.com/golang/protobuf/.travis.yml | 30 - examples/github.com/golang/protobuf/AUTHORS | 3 - .../github.com/golang/protobuf/CONTRIBUTORS | 3 - examples/github.com/golang/protobuf/LICENSE | 31 - examples/github.com/golang/protobuf/Makefile | 48 - examples/github.com/golang/protobuf/README.md | 283 - .../golang/protobuf/conformance/Makefile | 49 - .../protobuf/conformance/conformance.go | 154 - .../protobuf/conformance/conformance.sh | 4 - .../protobuf/conformance/failure_list_go.txt | 61 - .../conformance_proto/conformance.pb.go | 1816 ----- .../conformance_proto/conformance.proto | 273 - .../golang/protobuf/conformance/test.sh | 26 - .../golang/protobuf/descriptor/descriptor.go | 93 - .../protobuf/descriptor/descriptor_test.go | 32 - .../golang/protobuf/jsonpb/jsonpb.go | 1241 ---- .../golang/protobuf/jsonpb/jsonpb_test.go | 1150 --- .../jsonpb_test_proto/more_test_objects.pb.go | 368 - .../jsonpb_test_proto/more_test_objects.proto | 69 - .../jsonpb_test_proto/test_objects.pb.go | 1278 ---- .../jsonpb_test_proto/test_objects.proto | 171 - .../golang/protobuf/proto/all_test.go | 2410 ------- .../golang/protobuf/proto/any_test.go | 300 - .../github.com/golang/protobuf/proto/clone.go | 253 - .../golang/protobuf/proto/clone_test.go | 390 - .../golang/protobuf/proto/decode.go | 428 -- .../golang/protobuf/proto/decode_test.go | 255 - .../golang/protobuf/proto/discard.go | 350 - .../golang/protobuf/proto/discard_test.go | 170 - .../golang/protobuf/proto/encode.go | 221 - .../golang/protobuf/proto/encode_test.go | 85 - .../github.com/golang/protobuf/proto/equal.go | 300 - .../golang/protobuf/proto/equal_test.go | 244 - .../golang/protobuf/proto/extensions.go | 543 -- .../golang/protobuf/proto/extensions_test.go | 688 -- .../github.com/golang/protobuf/proto/lib.go | 921 --- .../golang/protobuf/proto/map_test.go | 70 - .../golang/protobuf/proto/message_set.go | 314 - .../golang/protobuf/proto/message_set_test.go | 77 - .../golang/protobuf/proto/pointer_reflect.go | 357 - .../golang/protobuf/proto/pointer_unsafe.go | 308 - .../golang/protobuf/proto/properties.go | 544 -- .../protobuf/proto/proto3_proto/proto3.pb.go | 461 -- .../protobuf/proto/proto3_proto/proto3.proto | 89 - .../golang/protobuf/proto/proto3_test.go | 151 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 191 - .../golang/protobuf/proto/table_marshal.go | 2681 ------- .../golang/protobuf/proto/table_merge.go | 654 -- .../golang/protobuf/proto/table_unmarshal.go | 1967 ----- .../protobuf/proto/test_proto/test.pb.go | 5118 ------------- .../protobuf/proto/test_proto/test.proto | 562 -- .../github.com/golang/protobuf/proto/text.go | 843 --- .../golang/protobuf/proto/text_parser.go | 880 --- .../golang/protobuf/proto/text_parser_test.go | 706 -- .../golang/protobuf/proto/text_test.go | 518 -- .../protoc-gen-go/descriptor/descriptor.pb.go | 2812 -------- .../protoc-gen-go/descriptor/descriptor.proto | 872 --- .../golang/protobuf/protoc-gen-go/doc.go | 51 - .../protoc-gen-go/generator/generator.go | 2928 -------- .../generator/internal/remap/remap.go | 117 - .../generator/internal/remap/remap_test.go | 82 - .../protoc-gen-go/generator/name_test.go | 115 - .../protobuf/protoc-gen-go/golden_test.go | 422 -- .../protobuf/protoc-gen-go/grpc/grpc.go | 483 -- .../protobuf/protoc-gen-go/link_grpc.go | 34 - .../golang/protobuf/protoc-gen-go/main.go | 98 - .../protoc-gen-go/plugin/plugin.pb.go | 369 - .../protoc-gen-go/plugin/plugin.pb.golden | 83 - .../protoc-gen-go/plugin/plugin.proto | 167 - .../testdata/deprecated/deprecated.pb.go | 232 - .../testdata/deprecated/deprecated.proto | 69 - .../extension_base/extension_base.pb.go | 139 - .../extension_base/extension_base.proto | 48 - .../extension_extra/extension_extra.pb.go | 78 - .../extension_extra/extension_extra.proto | 40 - .../protoc-gen-go/testdata/extension_test.go | 206 - .../extension_user/extension_user.pb.go | 401 -- .../extension_user/extension_user.proto | 102 - .../protoc-gen-go/testdata/grpc/grpc.pb.go | 444 -- .../protoc-gen-go/testdata/grpc/grpc.proto | 61 - .../testdata/import_public/a.pb.go | 110 - .../testdata/import_public/a.proto | 45 - .../testdata/import_public/b.pb.go | 87 - .../testdata/import_public/b.proto | 43 - .../testdata/import_public/sub/a.pb.go | 100 - .../testdata/import_public/sub/a.proto | 47 - .../testdata/import_public/sub/b.pb.go | 67 - .../testdata/import_public/sub/b.proto | 39 - .../testdata/import_public_test.go | 66 - .../testdata/imports/fmt/m.pb.go | 66 - .../testdata/imports/fmt/m.proto | 35 - .../testdata/imports/test_a_1/m1.pb.go | 130 - .../testdata/imports/test_a_1/m1.proto | 44 - .../testdata/imports/test_a_1/m2.pb.go | 67 - .../testdata/imports/test_a_1/m2.proto | 35 - .../testdata/imports/test_a_2/m3.pb.go | 67 - .../testdata/imports/test_a_2/m3.proto | 35 - .../testdata/imports/test_a_2/m4.pb.go | 67 - .../testdata/imports/test_a_2/m4.proto | 35 - .../testdata/imports/test_b_1/m1.pb.go | 67 - .../testdata/imports/test_b_1/m1.proto | 35 - .../testdata/imports/test_b_1/m2.pb.go | 67 - .../testdata/imports/test_b_1/m2.proto | 35 - .../testdata/imports/test_import_a1m1.pb.go | 80 - .../testdata/imports/test_import_a1m1.proto | 42 - .../testdata/imports/test_import_a1m2.pb.go | 80 - .../testdata/imports/test_import_a1m2.proto | 42 - .../testdata/imports/test_import_all.pb.go | 138 - .../testdata/imports/test_import_all.proto | 58 - .../protoc-gen-go/testdata/main_test.go | 48 - .../protoc-gen-go/testdata/multi/multi1.pb.go | 96 - .../protoc-gen-go/testdata/multi/multi1.proto | 46 - .../protoc-gen-go/testdata/multi/multi2.pb.go | 128 - .../protoc-gen-go/testdata/multi/multi2.proto | 48 - .../protoc-gen-go/testdata/multi/multi3.pb.go | 115 - .../protoc-gen-go/testdata/multi/multi3.proto | 45 - .../protoc-gen-go/testdata/my_test/test.pb.go | 1174 --- .../protoc-gen-go/testdata/my_test/test.proto | 158 - .../testdata/proto3/proto3.pb.go | 196 - .../testdata/proto3/proto3.proto | 55 - .../github.com/golang/protobuf/ptypes/any.go | 139 - .../golang/protobuf/ptypes/any/any.pb.go | 191 - .../golang/protobuf/ptypes/any/any.proto | 149 - .../golang/protobuf/ptypes/any_test.go | 113 - .../github.com/golang/protobuf/ptypes/doc.go | 35 - .../golang/protobuf/ptypes/duration.go | 102 - .../protobuf/ptypes/duration/duration.pb.go | 159 - .../protobuf/ptypes/duration/duration.proto | 117 - .../golang/protobuf/ptypes/duration_test.go | 121 - .../golang/protobuf/ptypes/empty/empty.pb.go | 79 - .../golang/protobuf/ptypes/empty/empty.proto | 52 - .../protobuf/ptypes/struct/struct.pb.go | 440 -- .../protobuf/ptypes/struct/struct.proto | 96 - .../golang/protobuf/ptypes/timestamp.go | 134 - .../protobuf/ptypes/timestamp/timestamp.pb.go | 175 - .../protobuf/ptypes/timestamp/timestamp.proto | 133 - .../golang/protobuf/ptypes/timestamp_test.go | 153 - .../protobuf/ptypes/wrappers/wrappers.pb.go | 443 -- .../protobuf/ptypes/wrappers/wrappers.proto | 118 - .../github.com/golang/protobuf/regenerate.sh | 53 - .../go-grpc-middleware/.gitignore | 202 - .../go-grpc-middleware/.travis.yml | 22 - .../go-grpc-middleware/CONTRIBUTING.md | 20 - .../grpc-ecosystem/go-grpc-middleware/DOC.md | 166 - .../go-grpc-middleware/Gopkg.lock | 123 - .../go-grpc-middleware/Gopkg.toml | 35 - .../grpc-ecosystem/go-grpc-middleware/LICENSE | 201 - .../go-grpc-middleware/README.md | 86 - .../go-grpc-middleware/chain.go | 183 - .../go-grpc-middleware/chain_test.go | 172 - .../grpc-ecosystem/go-grpc-middleware/doc.go | 69 - .../go-grpc-middleware/makefile | 22 - .../go-grpc-middleware/slack.png | Bin 5088 -> 0 bytes .../go-grpc-middleware/wrappers.go | 29 - .../go-grpc-middleware/wrappers_test.go | 52 - .../grpc-ecosystem/grpc-gateway/.gitignore | 9 - .../grpc-ecosystem/grpc-gateway/.travis.yml | 81 - .../grpc-gateway/.travis/bazel-build.sh | 10 - .../grpc-gateway/.travis/bazel-test.sh | 12 - .../grpc-gateway/.travis/install-bazel.sh | 20 - .../grpc-gateway/.travis/install-protoc.sh | 19 - .../.travis/install-swagger-codegen.sh | 9 - .../grpc-ecosystem/grpc-gateway/BUILD | 23 - .../grpc-ecosystem/grpc-gateway/CHANGELOG.md | 590 -- .../grpc-gateway/CONTRIBUTING.md | 20 - .../grpc-gateway/ISSUE_TEMPLATE.md | 41 - .../grpc-ecosystem/grpc-gateway/LICENSE.txt | 27 - .../grpc-ecosystem/grpc-gateway/Makefile | 206 - .../grpc-ecosystem/grpc-gateway/README.md | 252 - .../grpc-ecosystem/grpc-gateway/WORKSPACE | 53 - .../grpc-gateway/bin/.gitignore | 3 - .../grpc-ecosystem/grpc-gateway/bin/coverage | 17 - .../grpc-gateway/codegenerator/BUILD.bazel | 26 - .../grpc-gateway/codegenerator/doc.go | 4 - .../grpc-gateway/codegenerator/parse_req.go | 23 - .../codegenerator/parse_req_test.go | 69 - .../grpc-gateway/docs/.gitignore | 1 - .../grpc-ecosystem/grpc-gateway/docs/Gemfile | 9 - .../grpc-gateway/docs/Gemfile.lock | 256 - .../grpc-gateway/docs/_config.yaml | 19 - .../grpc-gateway/docs/_docs/background.md | 11 - .../docs/_docs/customizingyourgateway.md | 94 - .../grpc-gateway/docs/_docs/cygwin.md | 83 - .../grpc-gateway/docs/_docs/examples.md | 17 - .../grpc-gateway/docs/_docs/faq.md | 32 - .../grpc-gateway/docs/_docs/features.md | 30 - .../docs/_docs/grpcapiconfiguration.md | 149 - .../grpc-gateway/docs/_docs/usage.md | 194 - .../grpc-gateway/docs/_layouts/default.html | 92 - .../grpc-ecosystem/grpc-gateway/docs/index.md | 27 - .../grpc-ecosystem/grpc-gateway/docs/run.sh | 28 - .../grpc-gateway/examples/README.md | 40 - .../grpc-gateway/examples/browser/.gitignore | 3 - .../grpc-gateway/examples/browser/README.md | 31 - .../a_bit_of_everything_service.spec.js | 185 - .../examples/browser/bin/.gitignore | 2 - .../grpc-gateway/examples/browser/bower.json | 21 - .../examples/browser/echo_service.spec.js | 43 - .../grpc-gateway/examples/browser/gulpfile.js | 81 - .../grpc-gateway/examples/browser/index.html | 22 - .../examples/browser/package.json | 23 - .../examples/clients/abe/.gitignore | 1 - .../clients/abe/.swagger-codegen-ignore | 1 - .../examples/clients/abe/BUILD.bazel | 25 - .../clients/abe/a_bit_of_everything_nested.go | 22 - .../abe/a_bit_of_everything_service_api.go | 938 --- .../examples/clients/abe/api_client.go | 164 - .../examples/clients/abe/api_response.go | 44 - .../abe/camel_case_service_name_api.go | 110 - .../examples/clients/abe/configuration.go | 67 - .../examples/clients/abe/echo_rpc_api.go | 265 - .../examples/clients/abe/echo_service_api.go | 265 - .../abe/examplepb_a_bit_of_everything.go | 74 - .../examples/clients/abe/examplepb_body.go | 16 - .../clients/abe/examplepb_numeric_enum.go | 15 - .../examples/clients/abe/nested_deep_enum.go | 15 - .../examples/clients/abe/protobuf_empty.go | 15 - .../clients/abe/sub_string_message.go | 16 - .../examples/clients/echo/.gitignore | 1 - .../clients/echo/.swagger-codegen-ignore | 1 - .../examples/clients/echo/BUILD.bazel | 17 - .../examples/clients/echo/api_client.go | 164 - .../examples/clients/echo/api_response.go | 44 - .../examples/clients/echo/configuration.go | 67 - .../examples/clients/echo/echo_service_api.go | 541 -- .../clients/echo/examplepb_embedded.go | 19 - .../clients/echo/examplepb_simple_message.go | 30 - .../clients/unannotatedecho/.gitignore | 1 - .../unannotatedecho/.swagger-codegen-ignore | 1 - .../clients/unannotatedecho/BUILD.bazel | 16 - .../clients/unannotatedecho/api_client.go | 164 - .../clients/unannotatedecho/api_response.go | 44 - .../clients/unannotatedecho/configuration.go | 67 - .../examplepb_unannotated_simple_message.go | 22 - .../unannotated_echo_service_api.go | 290 - .../cmd/example-gateway-server/BUILD.bazel | 18 - .../cmd/example-gateway-server/main.go | 37 - .../cmd/example-grpc-server/BUILD.bazel | 19 - .../examples/cmd/example-grpc-server/main.go | 28 - .../grpc-gateway/examples/gateway/BUILD.bazel | 20 - .../grpc-gateway/examples/gateway/doc.go | 2 - .../grpc-gateway/examples/gateway/gateway.go | 57 - .../grpc-gateway/examples/gateway/handlers.go | 61 - .../grpc-gateway/examples/gateway/main.go | 77 - .../examples/integration/BUILD.bazel | 27 - .../examples/integration/client_test.go | 196 - .../examples/integration/integration_test.go | 982 --- .../examples/integration/main_test.go | 98 - .../examples/integration/proto_error_test.go | 207 - .../examples/proto/examplepb/BUILD.bazel | 64 - .../proto/examplepb/a_bit_of_everything.pb.go | 1330 ---- .../examplepb/a_bit_of_everything.pb.gw.go | 1116 --- .../proto/examplepb/a_bit_of_everything.proto | 316 - .../a_bit_of_everything.swagger.json | 933 --- .../proto/examplepb/echo_service.pb.go | 600 -- .../proto/examplepb/echo_service.pb.gw.go | 575 -- .../proto/examplepb/echo_service.proto | 72 - .../proto/examplepb/echo_service.swagger.json | 503 -- .../proto/examplepb/flow_combination.pb.go | 840 --- .../proto/examplepb/flow_combination.pb.gw.go | 1889 ----- .../proto/examplepb/flow_combination.proto | 168 - .../examples/proto/examplepb/stream.pb.go | 286 - .../examples/proto/examplepb/stream.pb.gw.go | 285 - .../examples/proto/examplepb/stream.proto | 29 - .../examplepb/unannotated_echo_service.pb.go | 270 - .../unannotated_echo_service.pb.gw.go | 317 - .../examplepb/unannotated_echo_service.proto | 37 - .../unannotated_echo_service.swagger.json | 170 - .../examplepb/unannotated_echo_service.yaml | 15 - .../examples/proto/examplepb/wrappers.pb.go | 209 - .../proto/examplepb/wrappers.pb.gw.go | 120 - .../examples/proto/examplepb/wrappers.proto | 24 - .../proto/examplepb/wrappers.swagger.json | 75 - .../examples/proto/sub/BUILD.bazel | 21 - .../examples/proto/sub/message.pb.go | 77 - .../examples/proto/sub/message.proto | 7 - .../examples/proto/sub2/BUILD.bazel | 21 - .../examples/proto/sub2/message.pb.go | 78 - .../examples/proto/sub2/message.proto | 7 - .../grpc-gateway/examples/server/BUILD.bazel | 30 - .../examples/server/a_bit_of_everything.go | 272 - .../grpc-gateway/examples/server/echo.go | 41 - .../examples/server/flow_combination.go | 72 - .../grpc-gateway/examples/server/main.go | 38 - .../examples/server/unannotatedecho.go | 40 - .../protoc-gen-grpc-gateway/BUILD.bazel | 41 - .../descriptor/BUILD.bazel | 44 - .../descriptor/grpc_api_configuration.go | 71 - .../descriptor/grpc_api_configuration_test.go | 164 - .../descriptor/grpc_api_service.go | 31 - .../descriptor/registry.go | 375 - .../descriptor/registry_test.go | 588 -- .../descriptor/services.go | 286 - .../descriptor/services_test.go | 1210 ---- .../descriptor/types.go | 375 - .../descriptor/types_test.go | 206 - .../generator/BUILD.bazel | 13 - .../generator/generator.go | 13 - .../gengateway/BUILD.bazel | 38 - .../protoc-gen-grpc-gateway/gengateway/doc.go | 2 - .../gengateway/generator.go | 114 - .../gengateway/generator_test.go | 153 - .../gengateway/template.go | 409 -- .../gengateway/template_test.go | 404 -- .../httprule/BUILD.bazel | 32 - .../httprule/compile.go | 117 - .../httprule/compile_test.go | 122 - .../protoc-gen-grpc-gateway/httprule/parse.go | 351 - .../httprule/parse_test.go | 313 - .../protoc-gen-grpc-gateway/httprule/types.go | 60 - .../httprule/types_test.go | 91 - .../protoc-gen-grpc-gateway/main.go | 115 - .../protoc-gen-swagger/BUILD.bazel | 30 - .../grpc-gateway/protoc-gen-swagger/defs.bzl | 112 - .../protoc-gen-swagger/genswagger/BUILD.bazel | 37 - .../protoc-gen-swagger/genswagger/doc.go | 2 - .../genswagger/generator.go | 132 - .../protoc-gen-swagger/genswagger/template.go | 1189 --- .../genswagger/template_test.go | 889 --- .../protoc-gen-swagger/genswagger/types.go | 226 - .../grpc-gateway/protoc-gen-swagger/main.go | 153 - .../protoc-gen-swagger/main_test.go | 137 - .../protoc-gen-swagger/options/BUILD.bazel | 33 - .../options/annotations.pb.go | 91 - .../options/annotations.proto | 37 - .../options/openapiv2.pb.go | 1376 ---- .../options/openapiv2.proto | 338 - .../grpc-gateway/repositories.bzl | 49 - .../grpc-gateway/runtime/BUILD.bazel | 82 - .../grpc-gateway/runtime/context.go | 187 - .../grpc-gateway/runtime/context_test.go | 192 - .../grpc-gateway/runtime/convert.go | 87 - .../grpc-gateway/runtime/doc.go | 5 - .../grpc-gateway/runtime/errors.go | 142 - .../grpc-gateway/runtime/errors_test.go | 57 - .../grpc-gateway/runtime/handler.go | 195 - .../grpc-gateway/runtime/handler_test.go | 228 - .../grpc-gateway/runtime/internal/BUILD.bazel | 23 - .../runtime/internal/stream_chunk.pb.go | 119 - .../runtime/internal/stream_chunk.proto | 15 - .../grpc-gateway/runtime/marshal_json.go | 45 - .../grpc-gateway/runtime/marshal_json_test.go | 260 - .../grpc-gateway/runtime/marshal_jsonpb.go | 203 - .../runtime/marshal_jsonpb_test.go | 616 -- .../grpc-gateway/runtime/marshal_proto.go | 62 - .../runtime/marshal_proto_test.go | 91 - .../grpc-gateway/runtime/marshaler.go | 48 - .../runtime/marshaler_registry.go | 91 - .../runtime/marshaler_registry_test.go | 107 - .../grpc-gateway/runtime/mux.go | 260 - .../grpc-gateway/runtime/mux_test.go | 213 - .../grpc-gateway/runtime/pattern.go | 227 - .../grpc-gateway/runtime/pattern_test.go | 590 -- .../grpc-gateway/runtime/proto2_convert.go | 80 - .../grpc-gateway/runtime/proto_errors.go | 61 - .../grpc-gateway/runtime/query.go | 357 - .../grpc-gateway/runtime/query_test.go | 794 --- .../third_party/googleapis/LICENSE | 201 - .../googleapis/README.grpc-gateway | 22 - .../googleapis/google/api/annotations.proto | 31 - .../googleapis/google/api/http.proto | 291 - .../googleapis/google/rpc/code.proto | 186 - .../googleapis/google/rpc/error_details.proto | 200 - .../googleapis/google/rpc/status.proto | 92 - .../grpc-gateway/utilities/BUILD.bazel | 20 - .../grpc-gateway/utilities/doc.go | 2 - .../grpc-gateway/utilities/pattern.go | 22 - .../grpc-gateway/utilities/trie.go | 177 - .../grpc-gateway/utilities/trie_test.go | 372 - .../mwitkow/go-proto-validators/.gitignore | 89 - .../mwitkow/go-proto-validators/.travis.yml | 18 - .../mwitkow/go-proto-validators/LICENSE.txt | 201 - .../mwitkow/go-proto-validators/Makefile | 45 - .../mwitkow/go-proto-validators/README.md | 132 - .../go-proto-validators/examples/.gitignore | 1 - .../go-proto-validators/examples/nested.pb.go | 83 - .../go-proto-validators/examples/nested.proto | 15 - .../examples/nested.validator.pb.go | 54 - .../mwitkow/go-proto-validators/helper.go | 39 - .../go-proto-validators/install_protoc.sh | 22 - .../go-proto-validators/plugin/plugin.go | 591 -- .../protoc-gen-govalidators/main.go | 67 - .../go-proto-validators/test/.gitignore | 2 - .../test/gogo/validator_test.go | 488 -- .../test/golang/validator_test.go | 512 -- .../test/validator_proto2.proto | 78 - .../test/validator_proto3.proto | 72 - .../test/validator_proto3_map.proto | 26 - .../test/validator_proto3_oneof.proto | 28 - .../go-proto-validators/validator.pb.go | 238 - .../go-proto-validators/validator.proto | 66 - examples/golang.org/x/net/context/context.go | 56 - .../golang.org/x/net/context/context_test.go | 583 -- .../x/net/context/ctxhttp/ctxhttp.go | 74 - .../x/net/context/ctxhttp/ctxhttp_17_test.go | 29 - .../x/net/context/ctxhttp/ctxhttp_pre17.go | 147 - .../net/context/ctxhttp/ctxhttp_pre17_test.go | 79 - .../x/net/context/ctxhttp/ctxhttp_test.go | 105 - examples/golang.org/x/net/context/go17.go | 72 - examples/golang.org/x/net/context/go19.go | 20 - examples/golang.org/x/net/context/pre_go17.go | 300 - examples/golang.org/x/net/context/pre_go19.go | 109 - .../x/net/context/withtimeout_test.go | 31 - examples/golang.org/x/net/http2/.gitignore | 2 - examples/golang.org/x/net/http2/Dockerfile | 51 - examples/golang.org/x/net/http2/Makefile | 3 - examples/golang.org/x/net/http2/README | 20 - examples/golang.org/x/net/http2/ciphers.go | 641 -- .../golang.org/x/net/http2/ciphers_test.go | 309 - .../x/net/http2/client_conn_pool.go | 282 - .../x/net/http2/configure_transport.go | 82 - examples/golang.org/x/net/http2/databuffer.go | 146 - .../golang.org/x/net/http2/databuffer_test.go | 157 - examples/golang.org/x/net/http2/errors.go | 133 - .../golang.org/x/net/http2/errors_test.go | 24 - examples/golang.org/x/net/http2/flow.go | 50 - examples/golang.org/x/net/http2/flow_test.go | 87 - examples/golang.org/x/net/http2/frame.go | 1579 ---- examples/golang.org/x/net/http2/frame_test.go | 1191 ---- examples/golang.org/x/net/http2/go111.go | 26 - examples/golang.org/x/net/http2/go16.go | 16 - examples/golang.org/x/net/http2/go17.go | 121 - examples/golang.org/x/net/http2/go17_not18.go | 36 - examples/golang.org/x/net/http2/go18.go | 56 - examples/golang.org/x/net/http2/go18_test.go | 79 - examples/golang.org/x/net/http2/go19.go | 16 - examples/golang.org/x/net/http2/go19_test.go | 59 - examples/golang.org/x/net/http2/gotrack.go | 170 - .../golang.org/x/net/http2/gotrack_test.go | 33 - .../golang.org/x/net/http2/h2demo/.gitignore | 6 - .../golang.org/x/net/http2/h2demo/Dockerfile | 11 - .../x/net/http2/h2demo/Dockerfile.0 | 134 - .../golang.org/x/net/http2/h2demo/Makefile | 55 - examples/golang.org/x/net/http2/h2demo/README | 16 - .../x/net/http2/h2demo/deployment-prod.yaml | 28 - .../golang.org/x/net/http2/h2demo/h2demo.go | 543 -- .../golang.org/x/net/http2/h2demo/launch.go | 302 - .../golang.org/x/net/http2/h2demo/rootCA.key | 27 - .../golang.org/x/net/http2/h2demo/rootCA.pem | 26 - .../golang.org/x/net/http2/h2demo/rootCA.srl | 1 - .../golang.org/x/net/http2/h2demo/server.crt | 20 - .../golang.org/x/net/http2/h2demo/server.key | 27 - .../x/net/http2/h2demo/service.yaml | 17 - .../golang.org/x/net/http2/h2demo/tmpl.go | 1991 ------ examples/golang.org/x/net/http2/h2i/README.md | 97 - examples/golang.org/x/net/http2/h2i/h2i.go | 522 -- examples/golang.org/x/net/http2/headermap.go | 78 - .../golang.org/x/net/http2/hpack/encode.go | 240 - .../x/net/http2/hpack/encode_test.go | 386 - .../golang.org/x/net/http2/hpack/hpack.go | 496 -- .../x/net/http2/hpack/hpack_test.go | 741 -- .../golang.org/x/net/http2/hpack/huffman.go | 212 - .../golang.org/x/net/http2/hpack/tables.go | 479 -- .../x/net/http2/hpack/tables_test.go | 214 - examples/golang.org/x/net/http2/http2.go | 391 - examples/golang.org/x/net/http2/http2_test.go | 227 - examples/golang.org/x/net/http2/not_go111.go | 17 - examples/golang.org/x/net/http2/not_go16.go | 21 - examples/golang.org/x/net/http2/not_go17.go | 95 - examples/golang.org/x/net/http2/not_go18.go | 29 - examples/golang.org/x/net/http2/not_go19.go | 16 - examples/golang.org/x/net/http2/pipe.go | 163 - examples/golang.org/x/net/http2/pipe_test.go | 130 - examples/golang.org/x/net/http2/server.go | 2891 -------- .../x/net/http2/server_push_test.go | 521 -- .../golang.org/x/net/http2/server_test.go | 3888 ---------- .../testdata/draft-ietf-httpbis-http2.xml | 5021 ------------- examples/golang.org/x/net/http2/transport.go | 2453 ------- .../golang.org/x/net/http2/transport_test.go | 4185 ----------- examples/golang.org/x/net/http2/write.go | 365 - examples/golang.org/x/net/http2/writesched.go | 242 - .../x/net/http2/writesched_priority.go | 452 -- .../x/net/http2/writesched_priority_test.go | 541 -- .../x/net/http2/writesched_random.go | 72 - .../x/net/http2/writesched_random_test.go | 44 - .../golang.org/x/net/http2/writesched_test.go | 125 - .../golang.org/x/net/http2/z_spec_test.go | 356 - .../golang.org/x/net/internal/iana/const.go | 223 - .../golang.org/x/net/internal/iana/gen.go | 383 - .../x/net/internal/nettest/helper_bsd.go | 53 - .../x/net/internal/nettest/helper_nobsd.go | 15 - .../x/net/internal/nettest/helper_posix.go | 31 - .../x/net/internal/nettest/helper_stub.go | 32 - .../x/net/internal/nettest/helper_unix.go | 29 - .../x/net/internal/nettest/helper_windows.go | 42 - .../x/net/internal/nettest/interface.go | 94 - .../x/net/internal/nettest/rlimit.go | 11 - .../x/net/internal/nettest/stack.go | 152 - .../x/net/internal/socket/cmsghdr.go | 11 - .../x/net/internal/socket/cmsghdr_bsd.go | 13 - .../internal/socket/cmsghdr_linux_32bit.go | 14 - .../internal/socket/cmsghdr_linux_64bit.go | 14 - .../internal/socket/cmsghdr_solaris_64bit.go | 14 - .../x/net/internal/socket/cmsghdr_stub.go | 17 - .../x/net/internal/socket/defs_darwin.go | 44 - .../x/net/internal/socket/defs_dragonfly.go | 44 - .../x/net/internal/socket/defs_freebsd.go | 44 - .../x/net/internal/socket/defs_linux.go | 49 - .../x/net/internal/socket/defs_netbsd.go | 47 - .../x/net/internal/socket/defs_openbsd.go | 44 - .../x/net/internal/socket/defs_solaris.go | 44 - .../x/net/internal/socket/error_unix.go | 31 - .../x/net/internal/socket/error_windows.go | 26 - .../x/net/internal/socket/iovec_32bit.go | 19 - .../x/net/internal/socket/iovec_64bit.go | 19 - .../internal/socket/iovec_solaris_64bit.go | 19 - .../x/net/internal/socket/iovec_stub.go | 11 - .../x/net/internal/socket/mmsghdr_stub.go | 21 - .../x/net/internal/socket/mmsghdr_unix.go | 42 - .../x/net/internal/socket/msghdr_bsd.go | 39 - .../x/net/internal/socket/msghdr_bsdvar.go | 16 - .../x/net/internal/socket/msghdr_linux.go | 36 - .../net/internal/socket/msghdr_linux_32bit.go | 24 - .../net/internal/socket/msghdr_linux_64bit.go | 24 - .../x/net/internal/socket/msghdr_openbsd.go | 14 - .../internal/socket/msghdr_solaris_64bit.go | 36 - .../x/net/internal/socket/msghdr_stub.go | 14 - .../x/net/internal/socket/rawconn.go | 66 - .../x/net/internal/socket/rawconn_mmsg.go | 74 - .../x/net/internal/socket/rawconn_msg.go | 77 - .../x/net/internal/socket/rawconn_nommsg.go | 18 - .../x/net/internal/socket/rawconn_nomsg.go | 18 - .../x/net/internal/socket/rawconn_stub.go | 25 - .../x/net/internal/socket/reflect.go | 62 - .../x/net/internal/socket/socket.go | 285 - .../net/internal/socket/socket_go1_9_test.go | 259 - .../x/net/internal/socket/socket_test.go | 46 - .../golang.org/x/net/internal/socket/sys.go | 33 - .../x/net/internal/socket/sys_bsd.go | 17 - .../x/net/internal/socket/sys_bsdvar.go | 14 - .../x/net/internal/socket/sys_darwin.go | 7 - .../x/net/internal/socket/sys_dragonfly.go | 7 - .../x/net/internal/socket/sys_linux.go | 27 - .../x/net/internal/socket/sys_linux_386.go | 55 - .../x/net/internal/socket/sys_linux_386.s | 11 - .../x/net/internal/socket/sys_linux_amd64.go | 10 - .../x/net/internal/socket/sys_linux_arm.go | 10 - .../x/net/internal/socket/sys_linux_arm64.go | 10 - .../x/net/internal/socket/sys_linux_mips.go | 10 - .../x/net/internal/socket/sys_linux_mips64.go | 10 - .../net/internal/socket/sys_linux_mips64le.go | 10 - .../x/net/internal/socket/sys_linux_mipsle.go | 10 - .../x/net/internal/socket/sys_linux_ppc64.go | 10 - .../net/internal/socket/sys_linux_ppc64le.go | 10 - .../x/net/internal/socket/sys_linux_s390x.go | 55 - .../x/net/internal/socket/sys_linux_s390x.s | 11 - .../x/net/internal/socket/sys_netbsd.go | 25 - .../x/net/internal/socket/sys_posix.go | 168 - .../x/net/internal/socket/sys_solaris.go | 71 - .../x/net/internal/socket/sys_solaris_amd64.s | 11 - .../x/net/internal/socket/sys_stub.go | 64 - .../x/net/internal/socket/sys_unix.go | 33 - .../x/net/internal/socket/sys_windows.go | 70 - .../x/net/internal/socket/zsys_darwin_386.go | 59 - .../net/internal/socket/zsys_darwin_amd64.go | 61 - .../x/net/internal/socket/zsys_darwin_arm.go | 59 - .../net/internal/socket/zsys_darwin_arm64.go | 61 - .../internal/socket/zsys_dragonfly_amd64.go | 61 - .../x/net/internal/socket/zsys_freebsd_386.go | 59 - .../net/internal/socket/zsys_freebsd_amd64.go | 61 - .../x/net/internal/socket/zsys_freebsd_arm.go | 59 - .../x/net/internal/socket/zsys_linux_386.go | 63 - .../x/net/internal/socket/zsys_linux_amd64.go | 66 - .../x/net/internal/socket/zsys_linux_arm.go | 63 - .../x/net/internal/socket/zsys_linux_arm64.go | 66 - .../x/net/internal/socket/zsys_linux_mips.go | 63 - .../net/internal/socket/zsys_linux_mips64.go | 66 - .../internal/socket/zsys_linux_mips64le.go | 66 - .../net/internal/socket/zsys_linux_mipsle.go | 63 - .../x/net/internal/socket/zsys_linux_ppc64.go | 66 - .../net/internal/socket/zsys_linux_ppc64le.go | 66 - .../x/net/internal/socket/zsys_linux_s390x.go | 66 - .../x/net/internal/socket/zsys_netbsd_386.go | 65 - .../net/internal/socket/zsys_netbsd_amd64.go | 68 - .../x/net/internal/socket/zsys_netbsd_arm.go | 65 - .../x/net/internal/socket/zsys_openbsd_386.go | 59 - .../net/internal/socket/zsys_openbsd_amd64.go | 61 - .../x/net/internal/socket/zsys_openbsd_arm.go | 59 - .../net/internal/socket/zsys_solaris_amd64.go | 60 - .../golang.org/x/net/internal/socks/client.go | 168 - .../x/net/internal/socks/dial_test.go | 170 - .../golang.org/x/net/internal/socks/socks.go | 316 - .../x/net/internal/sockstest/server.go | 241 - .../x/net/internal/sockstest/server_test.go | 103 - .../x/net/internal/timeseries/timeseries.go | 525 -- .../internal/timeseries/timeseries_test.go | 170 - examples/golang.org/x/net/trace/events.go | 532 -- examples/golang.org/x/net/trace/histogram.go | 365 - .../golang.org/x/net/trace/histogram_test.go | 325 - examples/golang.org/x/net/trace/trace.go | 1103 --- examples/golang.org/x/net/trace/trace_go16.go | 21 - examples/golang.org/x/net/trace/trace_go17.go | 21 - examples/golang.org/x/net/trace/trace_test.go | 178 - .../api/annotations/annotations.pb.go | 54 - .../googleapis/api/annotations/http.pb.go | 666 -- .../genproto/googleapis/rpc/code/code.pb.go | 246 - .../rpc/errdetails/error_details.pb.go | 422 -- .../googleapis/rpc/status/status.pb.go | 143 - .../grpc/.github/ISSUE_TEMPLATE | 14 - examples/google.golang.org/grpc/.travis.yml | 24 - examples/google.golang.org/grpc/AUTHORS | 1 - .../google.golang.org/grpc/CONTRIBUTING.md | 36 - .../grpc/Documentation/compression.md | 80 - .../grpc/Documentation/concurrency.md | 33 - .../grpc/Documentation/encoding.md | 146 - .../grpc/Documentation/gomock-example.md | 182 - .../grpc/Documentation/grpc-auth-support.md | 78 - .../grpc/Documentation/grpc-metadata.md | 227 - .../grpc/Documentation/log_levels.md | 49 - .../grpc/Documentation/rpc-errors.md | 68 - .../server-reflection-tutorial.md | 152 - .../grpc/Documentation/stickiness.md | 46 - .../grpc/Documentation/versioning.md | 34 - examples/google.golang.org/grpc/LICENSE | 202 - examples/google.golang.org/grpc/Makefile | 48 - examples/google.golang.org/grpc/README.md | 45 - examples/google.golang.org/grpc/backoff.go | 38 - examples/google.golang.org/grpc/balancer.go | 416 -- .../grpc/balancer/balancer.go | 270 - .../grpc/balancer/base/balancer.go | 208 - .../grpc/balancer/base/base.go | 52 - .../grpclb/grpc_lb_v1/load_balancer.pb.go | 832 --- .../grpc/balancer/grpclb/grpclb.go | 368 - .../grpc/balancer/grpclb/grpclb_picker.go | 170 - .../balancer/grpclb/grpclb_remote_balancer.go | 294 - .../grpc/balancer/grpclb/grpclb_test.go | 970 --- .../grpc/balancer/grpclb/grpclb_util.go | 214 - .../grpc/balancer/grpclb/grpclb_util_test.go | 219 - .../grpc/balancer/grpclb/regenerate.sh | 33 - .../grpc/balancer/roundrobin/roundrobin.go | 79 - .../balancer/roundrobin/roundrobin_test.go | 477 -- .../grpc/balancer_conn_wrappers.go | 300 - .../grpc/balancer_switching_test.go | 469 -- .../google.golang.org/grpc/balancer_test.go | 804 --- .../grpc/balancer_v1_wrapper.go | 328 - .../grpc/benchmark/benchmain/main.go | 546 -- .../grpc/benchmark/benchmark.go | 369 - .../grpc/benchmark/benchmark16_test.go | 112 - .../grpc/benchmark/benchmark17_test.go | 85 - .../grpc/benchmark/benchresult/main.go | 133 - .../grpc/benchmark/client/main.go | 195 - .../grpc/benchmark/grpc_testing/control.pb.go | 1568 ---- .../grpc/benchmark/grpc_testing/control.proto | 186 - .../benchmark/grpc_testing/messages.pb.go | 731 -- .../benchmark/grpc_testing/messages.proto | 157 - .../benchmark/grpc_testing/payloads.pb.go | 344 - .../benchmark/grpc_testing/payloads.proto | 40 - .../benchmark/grpc_testing/services.pb.go | 448 -- .../benchmark/grpc_testing/services.proto | 56 - .../grpc/benchmark/grpc_testing/stats.pb.go | 302 - .../grpc/benchmark/grpc_testing/stats.proto | 55 - .../grpc/benchmark/latency/latency.go | 316 - .../grpc/benchmark/latency/latency_test.go | 353 - .../benchmark/primitives/code_string_test.go | 135 - .../grpc/benchmark/primitives/context_test.go | 120 - .../benchmark/primitives/primitives_test.go | 403 -- .../grpc/benchmark/run_bench.sh | 187 - .../grpc/benchmark/server/main.go | 90 - .../grpc/benchmark/stats/histogram.go | 222 - .../grpc/benchmark/stats/stats.go | 302 - .../grpc/benchmark/stats/util.go | 208 - .../grpc/benchmark/worker/benchmark_client.go | 391 - .../grpc/benchmark/worker/benchmark_server.go | 188 - .../grpc/benchmark/worker/main.go | 230 - .../grpc/benchmark/worker/util.go | 35 - examples/google.golang.org/grpc/call.go | 93 - examples/google.golang.org/grpc/call_test.go | 293 - .../channelz/grpc_channelz_v1/channelz.pb.go | 3257 --------- .../grpc/channelz/service/regenerate.sh | 33 - .../grpc/channelz/service/service.go | 266 - .../grpc/channelz/service/service_test.go | 477 -- examples/google.golang.org/grpc/clientconn.go | 1602 ----- .../google.golang.org/grpc/clientconn_test.go | 678 -- examples/google.golang.org/grpc/codec.go | 50 - examples/google.golang.org/grpc/codec_test.go | 32 - examples/google.golang.org/grpc/codegen.sh | 17 - .../grpc/codes/code_string.go | 62 - .../google.golang.org/grpc/codes/codes.go | 197 - .../grpc/codes/codes_test.go | 84 - .../grpc/connectivity/connectivity.go | 72 - .../grpc/credentials/alts/alts.go | 329 - .../grpc/credentials/alts/alts_test.go | 290 - .../alts/core/authinfo/authinfo.go | 87 - .../alts/core/authinfo/authinfo_test.go | 134 - .../grpc/credentials/alts/core/common.go | 70 - .../credentials/alts/core/conn/aeadrekey.go | 131 - .../alts/core/conn/aeadrekey_test.go | 263 - .../credentials/alts/core/conn/aes128gcm.go | 105 - .../alts/core/conn/aes128gcm_test.go | 223 - .../alts/core/conn/aes128gcmrekey.go | 116 - .../alts/core/conn/aes128gcmrekey_test.go | 117 - .../grpc/credentials/alts/core/conn/common.go | 70 - .../credentials/alts/core/conn/counter.go | 106 - .../alts/core/conn/counter_test.go | 141 - .../grpc/credentials/alts/core/conn/record.go | 271 - .../credentials/alts/core/conn/record_test.go | 274 - .../alts/core/handshaker/handshaker.go | 365 - .../alts/core/handshaker/handshaker_test.go | 261 - .../alts/core/handshaker/service/service.go | 56 - .../core/handshaker/service/service_test.go | 69 - .../core/proto/grpc_gcp/altscontext.pb.go | 137 - .../alts/core/proto/grpc_gcp/handshaker.pb.go | 1178 --- .../grpc_gcp/transport_security_common.pb.go | 178 - .../grpc/credentials/alts/core/regenerate.sh | 35 - .../alts/core/testutil/testutil.go | 125 - .../grpc/credentials/alts/utils.go | 136 - .../grpc/credentials/alts/utils_test.go | 111 - .../grpc/credentials/credentials.go | 220 - .../grpc/credentials/credentials_test.go | 206 - .../grpc/credentials/credentials_util_go17.go | 60 - .../grpc/credentials/credentials_util_go18.go | 38 - .../credentials/credentials_util_pre_go17.go | 57 - .../grpc/credentials/oauth/oauth.go | 173 - examples/google.golang.org/grpc/doc.go | 24 - .../grpc/encoding/encoding.go | 118 - .../grpc/encoding/gzip/gzip.go | 117 - .../grpc/encoding/proto/proto.go | 110 - .../encoding/proto/proto_benchmark_test.go | 100 - .../grpc/encoding/proto/proto_test.go | 129 - examples/google.golang.org/grpc/envconfig.go | 37 - .../google.golang.org/grpc/examples/README.md | 64 - .../grpc/examples/gotutorial.md | 431 -- .../helloworld/greeter_client/main.go | 57 - .../helloworld/greeter_server/main.go | 57 - .../helloworld/helloworld/helloworld.pb.go | 198 - .../helloworld/helloworld/helloworld.proto | 37 - .../helloworld/mock_helloworld/hw_mock.go | 48 - .../mock_helloworld/hw_mock_test.go | 70 - .../grpc/examples/oauth/client/main.go | 72 - .../grpc/examples/oauth/server/main.go | 108 - .../grpc/examples/route_guide/README.md | 35 - .../examples/route_guide/client/client.go | 192 - .../route_guide/mock_routeguide/rg_mock.go | 200 - .../mock_routeguide/rg_mock_test.go | 83 - .../route_guide/routeguide/route_guide.pb.go | 640 -- .../route_guide/routeguide/route_guide.proto | 110 - .../examples/route_guide/server/server.go | 238 - .../route_guide/testdata/route_guide_db.json | 601 -- .../grpc/examples/rpc_errors/client/main.go | 62 - .../grpc/examples/rpc_errors/server/main.go | 80 - examples/google.golang.org/grpc/go16.go | 70 - examples/google.golang.org/grpc/go17.go | 71 - .../grpclb/grpc_lb_v1/messages/messages.pb.go | 718 -- .../grpclb/grpc_lb_v1/messages/messages.proto | 133 - .../grpclb/grpc_lb_v1/service/service.pb.go | 150 - .../grpclb/grpc_lb_v1/service/service.proto | 26 - .../google.golang.org/grpc/grpclb/noimport.go | 27 - .../grpc/grpclog/glogger/glogger.go | 86 - .../google.golang.org/grpc/grpclog/grpclog.go | 126 - .../google.golang.org/grpc/grpclog/logger.go | 85 - .../grpc/grpclog/loggerv2.go | 195 - .../grpc/grpclog/loggerv2_test.go | 62 - .../grpc/health/grpc_health_v1/health.pb.go | 227 - .../google.golang.org/grpc/health/health.go | 72 - .../grpc/health/regenerate.sh | 33 - .../google.golang.org/grpc/interceptor.go | 77 - .../grpc/internal/backoff/backoff.go | 78 - .../grpc/internal/channelz/funcs.go | 573 -- .../grpc/internal/channelz/types.go | 418 -- .../grpc/internal/grpcrand/grpcrand.go | 56 - .../grpc/internal/internal.go | 36 - .../grpc/internal/leakcheck/leakcheck.go | 118 - .../grpc/internal/leakcheck/leakcheck_test.go | 76 - .../grpc/interop/alts/client/client.go | 69 - .../grpc/interop/alts/server/server.go | 53 - .../grpc/interop/client/client.go | 204 - .../grpc/interop/grpc_testing/test.pb.go | 1087 --- .../grpc/interop/grpc_testing/test.proto | 174 - .../interop/http2/negative_http2_client.go | 159 - .../grpc/interop/server/server.go | 78 - .../grpc/interop/test_utils.go | 745 -- .../grpc/keepalive/keepalive.go | 65 - .../grpc/metadata/metadata.go | 210 - .../grpc/metadata/metadata_test.go | 251 - .../grpc/naming/dns_resolver.go | 290 - .../grpc/naming/dns_resolver_test.go | 315 - .../google.golang.org/grpc/naming/go17.go | 34 - .../grpc/naming/go17_test.go | 42 - .../google.golang.org/grpc/naming/go18.go | 28 - .../grpc/naming/go18_test.go | 41 - .../google.golang.org/grpc/naming/naming.go | 69 - examples/google.golang.org/grpc/peer/peer.go | 51 - .../google.golang.org/grpc/picker_wrapper.go | 336 - .../grpc/picker_wrapper_test.go | 160 - examples/google.golang.org/grpc/pickfirst.go | 108 - .../google.golang.org/grpc/pickfirst_test.go | 360 - examples/google.golang.org/grpc/proxy.go | 130 - examples/google.golang.org/grpc/proxy_test.go | 182 - .../grpc/reflection/README.md | 18 - .../grpc_reflection_v1alpha/reflection.pb.go | 925 --- .../grpc_reflection_v1alpha/reflection.proto | 136 - .../grpc/reflection/grpc_testing/proto2.pb.go | 82 - .../grpc/reflection/grpc_testing/proto2.proto | 22 - .../reflection/grpc_testing/proto2_ext.pb.go | 109 - .../reflection/grpc_testing/proto2_ext.proto | 30 - .../reflection/grpc_testing/proto2_ext2.pb.go | 98 - .../reflection/grpc_testing/proto2_ext2.proto | 28 - .../grpc/reflection/grpc_testing/test.pb.go | 319 - .../grpc/reflection/grpc_testing/test.proto | 35 - .../reflection/grpc_testingv3/testv3.pb.go | 457 -- .../reflection/grpc_testingv3/testv3.proto | 35 - .../grpc/reflection/serverreflection.go | 454 -- .../grpc/reflection/serverreflection_test.go | 526 -- .../grpc/resolver/dns/dns_resolver.go | 381 - .../grpc/resolver/dns/dns_resolver_test.go | 936 --- .../grpc/resolver/dns/go17.go | 35 - .../grpc/resolver/dns/go17_test.go | 50 - .../grpc/resolver/dns/go18.go | 29 - .../grpc/resolver/dns/go18_test.go | 49 - .../grpc/resolver/manual/manual.go | 91 - .../grpc/resolver/passthrough/passthrough.go | 57 - .../grpc/resolver/resolver.go | 154 - .../grpc/resolver_conn_wrapper.go | 158 - .../grpc/resolver_conn_wrapper_test.go | 113 - examples/google.golang.org/grpc/rpc_util.go | 741 -- .../google.golang.org/grpc/rpc_util_test.go | 288 - examples/google.golang.org/grpc/server.go | 1486 ---- .../google.golang.org/grpc/server_test.go | 136 - .../google.golang.org/grpc/service_config.go | 233 - .../grpc/service_config_test.go | 386 - .../grpc/stats/grpc_testing/test.pb.go | 403 -- .../grpc/stats/grpc_testing/test.proto | 43 - .../google.golang.org/grpc/stats/handlers.go | 64 - .../google.golang.org/grpc/stats/stats.go | 296 - .../grpc/stats/stats_test.go | 1257 ---- .../google.golang.org/grpc/status/go16.go | 42 - .../google.golang.org/grpc/status/go17.go | 44 - .../grpc/status/go17_test.go | 44 - .../google.golang.org/grpc/status/status.go | 189 - .../grpc/status/status_test.go | 348 - .../grpc/stickiness_linkedmap.go | 97 - .../grpc/stickiness_linkedmap_test.go | 186 - .../google.golang.org/grpc/stickiness_test.go | 288 - examples/google.golang.org/grpc/stream.go | 779 -- .../grpc/stress/client/main.go | 337 - .../grpc/stress/grpc_testing/metrics.pb.go | 429 -- .../grpc/stress/grpc_testing/metrics.proto | 49 - .../grpc/stress/metrics_client/main.go | 82 - examples/google.golang.org/grpc/tap/tap.go | 51 - .../grpc/test/bufconn/bufconn.go | 244 - .../grpc/test/bufconn/bufconn_test.go | 199 - .../grpc/test/channelz_test.go | 1199 ---- .../grpc/test/codec_perf/perf.pb.go | 75 - .../grpc/test/codec_perf/perf.proto | 25 - .../grpc/test/end2end_test.go | 6342 ----------------- .../grpc/test/gracefulstop_test.go | 212 - .../grpc/test/grpc_testing/test.pb.go | 949 --- .../grpc/test/grpc_testing/test.proto | 154 - examples/google.golang.org/grpc/test/race.go | 24 - .../grpc/test/rawConnWrapper.go | 345 - .../grpc/test/servertester.go | 280 - .../google.golang.org/grpc/testdata/ca.pem | 15 - .../grpc/testdata/server1.key | 16 - .../grpc/testdata/server1.pem | 16 - .../grpc/testdata/testdata.go | 63 - examples/google.golang.org/grpc/trace.go | 113 - .../grpc/transport/bdp_estimator.go | 140 - .../grpc/transport/controlbuf.go | 796 --- .../grpc/transport/flowcontrol.go | 242 - .../google.golang.org/grpc/transport/go16.go | 51 - .../google.golang.org/grpc/transport/go17.go | 52 - .../grpc/transport/handler_server.go | 451 -- .../grpc/transport/handler_server_test.go | 482 -- .../grpc/transport/http2_client.go | 1298 ---- .../grpc/transport/http2_server.go | 1142 --- .../grpc/transport/http_util.go | 592 -- .../grpc/transport/http_util_test.go | 237 - .../google.golang.org/grpc/transport/log.go | 50 - .../grpc/transport/transport.go | 708 -- .../grpc/transport/transport_test.go | 2312 ------ examples/google.golang.org/grpc/version.go | 22 - examples/google.golang.org/grpc/vet.sh | 94 - 877 files changed, 212211 deletions(-) delete mode 100644 examples/github.com/docker/docker/pkg/pubsub/publisher.go delete mode 100644 examples/github.com/docker/docker/pkg/pubsub/publisher_test.go delete mode 100755 examples/github.com/golang/protobuf/.gitignore delete mode 100755 examples/github.com/golang/protobuf/.travis.yml delete mode 100755 examples/github.com/golang/protobuf/AUTHORS delete mode 100755 examples/github.com/golang/protobuf/CONTRIBUTORS delete mode 100755 examples/github.com/golang/protobuf/LICENSE delete mode 100755 examples/github.com/golang/protobuf/Makefile delete mode 100755 examples/github.com/golang/protobuf/README.md delete mode 100755 examples/github.com/golang/protobuf/conformance/Makefile delete mode 100755 examples/github.com/golang/protobuf/conformance/conformance.go delete mode 100755 examples/github.com/golang/protobuf/conformance/conformance.sh delete mode 100755 examples/github.com/golang/protobuf/conformance/failure_list_go.txt delete mode 100755 examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go delete mode 100755 examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto delete mode 100755 examples/github.com/golang/protobuf/conformance/test.sh delete mode 100755 examples/github.com/golang/protobuf/descriptor/descriptor.go delete mode 100755 examples/github.com/golang/protobuf/descriptor/descriptor_test.go delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb.go delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb_test.go delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go delete mode 100755 examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto delete mode 100755 examples/github.com/golang/protobuf/proto/all_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/any_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/clone.go delete mode 100755 examples/github.com/golang/protobuf/proto/clone_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/decode.go delete mode 100755 examples/github.com/golang/protobuf/proto/decode_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/discard.go delete mode 100755 examples/github.com/golang/protobuf/proto/discard_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/encode.go delete mode 100755 examples/github.com/golang/protobuf/proto/encode_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/equal.go delete mode 100755 examples/github.com/golang/protobuf/proto/equal_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/extensions.go delete mode 100755 examples/github.com/golang/protobuf/proto/extensions_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/lib.go delete mode 100755 examples/github.com/golang/protobuf/proto/map_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/message_set.go delete mode 100755 examples/github.com/golang/protobuf/proto/message_set_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/pointer_reflect.go delete mode 100755 examples/github.com/golang/protobuf/proto/pointer_unsafe.go delete mode 100755 examples/github.com/golang/protobuf/proto/properties.go delete mode 100755 examples/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go delete mode 100755 examples/github.com/golang/protobuf/proto/proto3_proto/proto3.proto delete mode 100755 examples/github.com/golang/protobuf/proto/proto3_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/size2_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/size_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/table_marshal.go delete mode 100755 examples/github.com/golang/protobuf/proto/table_merge.go delete mode 100755 examples/github.com/golang/protobuf/proto/table_unmarshal.go delete mode 100755 examples/github.com/golang/protobuf/proto/test_proto/test.pb.go delete mode 100755 examples/github.com/golang/protobuf/proto/test_proto/test.proto delete mode 100755 examples/github.com/golang/protobuf/proto/text.go delete mode 100755 examples/github.com/golang/protobuf/proto/text_parser.go delete mode 100755 examples/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100755 examples/github.com/golang/protobuf/proto/text_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/doc.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/generator/generator.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/golden_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/link_grpc.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/main.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go delete mode 100755 examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/any.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/any/any.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/any/any.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/any_test.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/doc.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/duration.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/duration/duration.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/duration/duration.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/duration_test.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/empty/empty.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/empty/empty.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/struct/struct.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/struct/struct.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/timestamp.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto delete mode 100755 examples/github.com/golang/protobuf/ptypes/timestamp_test.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go delete mode 100755 examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto delete mode 100755 examples/github.com/golang/protobuf/regenerate.sh delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/.travis.yml delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/DOC.md delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.lock delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.toml delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/README.md delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/chain.go delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/chain_test.go delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/makefile delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/slack.png delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go delete mode 100755 examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis.yml delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-build.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-test.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-bazel.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-protoc.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-swagger-codegen.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/BUILD delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/ISSUE_TEMPLATE.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/Makefile delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/README.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/WORKSPACE delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/bin/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/bin/coverage delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile.lock delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_config.yaml delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/background.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/customizingyourgateway.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/cygwin.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/examples.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/faq.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/features.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/grpcapiconfiguration.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/usage.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/_layouts/default.html delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/index.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/docs/run.sh delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/README.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/README.md delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/a_bit_of_everything_service.spec.js delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bin/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bower.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/echo_service.spec.js delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/gulpfile.js delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/index.html delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/package.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.swagger-codegen-ignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_nested.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_service_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_client.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_response.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/camel_case_service_name_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/configuration.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_rpc_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_service_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_a_bit_of_everything.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_body.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_numeric_enum.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/nested_deep_enum.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/protobuf_empty.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/sub_string_message.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.swagger-codegen-ignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_client.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_response.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/configuration.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/echo_service_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_embedded.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_simple_message.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.gitignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.swagger-codegen-ignore delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_client.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_response.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/configuration.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/examplepb_unannotated_simple_message.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/unannotated_echo_service_api.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/gateway.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/handlers.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/client_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/integration_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/main_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/proto_error_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.swagger.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.swagger.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.swagger.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.yaml delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.gw.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.swagger.json delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/a_bit_of_everything.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/echo.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/flow_combination.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/unannotatedecho.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/repositories.bzl delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.pb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/README.grpc-gateway delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/annotations.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/http.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/code.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/error_details.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/status.proto delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go delete mode 100755 examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/.gitignore delete mode 100755 examples/github.com/mwitkow/go-proto-validators/.travis.yml delete mode 100755 examples/github.com/mwitkow/go-proto-validators/LICENSE.txt delete mode 100755 examples/github.com/mwitkow/go-proto-validators/Makefile delete mode 100755 examples/github.com/mwitkow/go-proto-validators/README.md delete mode 100755 examples/github.com/mwitkow/go-proto-validators/examples/.gitignore delete mode 100755 examples/github.com/mwitkow/go-proto-validators/examples/nested.pb.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/examples/nested.proto delete mode 100755 examples/github.com/mwitkow/go-proto-validators/examples/nested.validator.pb.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/helper.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/install_protoc.sh delete mode 100755 examples/github.com/mwitkow/go-proto-validators/plugin/plugin.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/protoc-gen-govalidators/main.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/.gitignore delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/gogo/validator_test.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/golang/validator_test.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/validator_proto2.proto delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/validator_proto3.proto delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_map.proto delete mode 100755 examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_oneof.proto delete mode 100755 examples/github.com/mwitkow/go-proto-validators/validator.pb.go delete mode 100755 examples/github.com/mwitkow/go-proto-validators/validator.proto delete mode 100755 examples/golang.org/x/net/context/context.go delete mode 100755 examples/golang.org/x/net/context/context_test.go delete mode 100755 examples/golang.org/x/net/context/ctxhttp/ctxhttp.go delete mode 100755 examples/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go delete mode 100755 examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go delete mode 100755 examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go delete mode 100755 examples/golang.org/x/net/context/ctxhttp/ctxhttp_test.go delete mode 100755 examples/golang.org/x/net/context/go17.go delete mode 100755 examples/golang.org/x/net/context/go19.go delete mode 100755 examples/golang.org/x/net/context/pre_go17.go delete mode 100755 examples/golang.org/x/net/context/pre_go19.go delete mode 100755 examples/golang.org/x/net/context/withtimeout_test.go delete mode 100755 examples/golang.org/x/net/http2/.gitignore delete mode 100644 examples/golang.org/x/net/http2/Dockerfile delete mode 100644 examples/golang.org/x/net/http2/Makefile delete mode 100644 examples/golang.org/x/net/http2/README delete mode 100644 examples/golang.org/x/net/http2/ciphers.go delete mode 100644 examples/golang.org/x/net/http2/ciphers_test.go delete mode 100644 examples/golang.org/x/net/http2/client_conn_pool.go delete mode 100644 examples/golang.org/x/net/http2/configure_transport.go delete mode 100644 examples/golang.org/x/net/http2/databuffer.go delete mode 100644 examples/golang.org/x/net/http2/databuffer_test.go delete mode 100644 examples/golang.org/x/net/http2/errors.go delete mode 100644 examples/golang.org/x/net/http2/errors_test.go delete mode 100644 examples/golang.org/x/net/http2/flow.go delete mode 100644 examples/golang.org/x/net/http2/flow_test.go delete mode 100644 examples/golang.org/x/net/http2/frame.go delete mode 100644 examples/golang.org/x/net/http2/frame_test.go delete mode 100644 examples/golang.org/x/net/http2/go111.go delete mode 100644 examples/golang.org/x/net/http2/go16.go delete mode 100644 examples/golang.org/x/net/http2/go17.go delete mode 100644 examples/golang.org/x/net/http2/go17_not18.go delete mode 100644 examples/golang.org/x/net/http2/go18.go delete mode 100644 examples/golang.org/x/net/http2/go18_test.go delete mode 100644 examples/golang.org/x/net/http2/go19.go delete mode 100644 examples/golang.org/x/net/http2/go19_test.go delete mode 100644 examples/golang.org/x/net/http2/gotrack.go delete mode 100644 examples/golang.org/x/net/http2/gotrack_test.go delete mode 100644 examples/golang.org/x/net/http2/h2demo/.gitignore delete mode 100644 examples/golang.org/x/net/http2/h2demo/Dockerfile delete mode 100644 examples/golang.org/x/net/http2/h2demo/Dockerfile.0 delete mode 100644 examples/golang.org/x/net/http2/h2demo/Makefile delete mode 100644 examples/golang.org/x/net/http2/h2demo/README delete mode 100644 examples/golang.org/x/net/http2/h2demo/deployment-prod.yaml delete mode 100644 examples/golang.org/x/net/http2/h2demo/h2demo.go delete mode 100644 examples/golang.org/x/net/http2/h2demo/launch.go delete mode 100644 examples/golang.org/x/net/http2/h2demo/rootCA.key delete mode 100644 examples/golang.org/x/net/http2/h2demo/rootCA.pem delete mode 100644 examples/golang.org/x/net/http2/h2demo/rootCA.srl delete mode 100644 examples/golang.org/x/net/http2/h2demo/server.crt delete mode 100644 examples/golang.org/x/net/http2/h2demo/server.key delete mode 100644 examples/golang.org/x/net/http2/h2demo/service.yaml delete mode 100644 examples/golang.org/x/net/http2/h2demo/tmpl.go delete mode 100644 examples/golang.org/x/net/http2/h2i/README.md delete mode 100644 examples/golang.org/x/net/http2/h2i/h2i.go delete mode 100644 examples/golang.org/x/net/http2/headermap.go delete mode 100644 examples/golang.org/x/net/http2/hpack/encode.go delete mode 100644 examples/golang.org/x/net/http2/hpack/encode_test.go delete mode 100644 examples/golang.org/x/net/http2/hpack/hpack.go delete mode 100644 examples/golang.org/x/net/http2/hpack/hpack_test.go delete mode 100644 examples/golang.org/x/net/http2/hpack/huffman.go delete mode 100644 examples/golang.org/x/net/http2/hpack/tables.go delete mode 100644 examples/golang.org/x/net/http2/hpack/tables_test.go delete mode 100644 examples/golang.org/x/net/http2/http2.go delete mode 100644 examples/golang.org/x/net/http2/http2_test.go delete mode 100644 examples/golang.org/x/net/http2/not_go111.go delete mode 100644 examples/golang.org/x/net/http2/not_go16.go delete mode 100644 examples/golang.org/x/net/http2/not_go17.go delete mode 100644 examples/golang.org/x/net/http2/not_go18.go delete mode 100644 examples/golang.org/x/net/http2/not_go19.go delete mode 100644 examples/golang.org/x/net/http2/pipe.go delete mode 100644 examples/golang.org/x/net/http2/pipe_test.go delete mode 100644 examples/golang.org/x/net/http2/server.go delete mode 100644 examples/golang.org/x/net/http2/server_push_test.go delete mode 100644 examples/golang.org/x/net/http2/server_test.go delete mode 100644 examples/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml delete mode 100644 examples/golang.org/x/net/http2/transport.go delete mode 100644 examples/golang.org/x/net/http2/transport_test.go delete mode 100644 examples/golang.org/x/net/http2/write.go delete mode 100644 examples/golang.org/x/net/http2/writesched.go delete mode 100644 examples/golang.org/x/net/http2/writesched_priority.go delete mode 100644 examples/golang.org/x/net/http2/writesched_priority_test.go delete mode 100644 examples/golang.org/x/net/http2/writesched_random.go delete mode 100644 examples/golang.org/x/net/http2/writesched_random_test.go delete mode 100644 examples/golang.org/x/net/http2/writesched_test.go delete mode 100644 examples/golang.org/x/net/http2/z_spec_test.go delete mode 100644 examples/golang.org/x/net/internal/iana/const.go delete mode 100644 examples/golang.org/x/net/internal/iana/gen.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_bsd.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_nobsd.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_posix.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_stub.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_unix.go delete mode 100644 examples/golang.org/x/net/internal/nettest/helper_windows.go delete mode 100644 examples/golang.org/x/net/internal/nettest/interface.go delete mode 100644 examples/golang.org/x/net/internal/nettest/rlimit.go delete mode 100644 examples/golang.org/x/net/internal/nettest/stack.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr_bsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr_linux_32bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr_linux_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr_solaris_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/cmsghdr_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_darwin.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_dragonfly.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_freebsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_linux.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_netbsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_openbsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/defs_solaris.go delete mode 100644 examples/golang.org/x/net/internal/socket/error_unix.go delete mode 100644 examples/golang.org/x/net/internal/socket/error_windows.go delete mode 100644 examples/golang.org/x/net/internal/socket/iovec_32bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/iovec_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/iovec_solaris_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/iovec_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/mmsghdr_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/mmsghdr_unix.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_bsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_bsdvar.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_linux.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_linux_32bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_linux_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_openbsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_solaris_64bit.go delete mode 100644 examples/golang.org/x/net/internal/socket/msghdr_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn_mmsg.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn_msg.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn_nommsg.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn_nomsg.go delete mode 100644 examples/golang.org/x/net/internal/socket/rawconn_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/reflect.go delete mode 100644 examples/golang.org/x/net/internal/socket/socket.go delete mode 100644 examples/golang.org/x/net/internal/socket/socket_go1_9_test.go delete mode 100644 examples/golang.org/x/net/internal/socket/socket_test.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_bsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_bsdvar.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_darwin.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_dragonfly.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_386.s delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_arm64.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_mips.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_mips64.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_mips64le.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_mipsle.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_ppc64.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_ppc64le.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_s390x.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_linux_s390x.s delete mode 100644 examples/golang.org/x/net/internal/socket/sys_netbsd.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_posix.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_solaris.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_solaris_amd64.s delete mode 100644 examples/golang.org/x/net/internal/socket/sys_stub.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_unix.go delete mode 100644 examples/golang.org/x/net/internal/socket/sys_windows.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_darwin_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_darwin_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_darwin_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_darwin_arm64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_dragonfly_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_freebsd_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_freebsd_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_freebsd_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_arm64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_mips.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_mips64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_mips64le.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_mipsle.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_ppc64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_ppc64le.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_linux_s390x.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_netbsd_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_netbsd_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_netbsd_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_openbsd_386.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_openbsd_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_openbsd_arm.go delete mode 100644 examples/golang.org/x/net/internal/socket/zsys_solaris_amd64.go delete mode 100644 examples/golang.org/x/net/internal/socks/client.go delete mode 100644 examples/golang.org/x/net/internal/socks/dial_test.go delete mode 100644 examples/golang.org/x/net/internal/socks/socks.go delete mode 100644 examples/golang.org/x/net/internal/sockstest/server.go delete mode 100644 examples/golang.org/x/net/internal/sockstest/server_test.go delete mode 100644 examples/golang.org/x/net/internal/timeseries/timeseries.go delete mode 100644 examples/golang.org/x/net/internal/timeseries/timeseries_test.go delete mode 100644 examples/golang.org/x/net/trace/events.go delete mode 100644 examples/golang.org/x/net/trace/histogram.go delete mode 100644 examples/golang.org/x/net/trace/histogram_test.go delete mode 100644 examples/golang.org/x/net/trace/trace.go delete mode 100644 examples/golang.org/x/net/trace/trace_go16.go delete mode 100644 examples/golang.org/x/net/trace/trace_go17.go delete mode 100644 examples/golang.org/x/net/trace/trace_test.go delete mode 100644 examples/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go delete mode 100644 examples/google.golang.org/genproto/googleapis/api/annotations/http.pb.go delete mode 100644 examples/google.golang.org/genproto/googleapis/rpc/code/code.pb.go delete mode 100644 examples/google.golang.org/genproto/googleapis/rpc/errdetails/error_details.pb.go delete mode 100644 examples/google.golang.org/genproto/googleapis/rpc/status/status.pb.go delete mode 100755 examples/google.golang.org/grpc/.github/ISSUE_TEMPLATE delete mode 100755 examples/google.golang.org/grpc/.travis.yml delete mode 100755 examples/google.golang.org/grpc/AUTHORS delete mode 100755 examples/google.golang.org/grpc/CONTRIBUTING.md delete mode 100755 examples/google.golang.org/grpc/Documentation/compression.md delete mode 100755 examples/google.golang.org/grpc/Documentation/concurrency.md delete mode 100755 examples/google.golang.org/grpc/Documentation/encoding.md delete mode 100755 examples/google.golang.org/grpc/Documentation/gomock-example.md delete mode 100755 examples/google.golang.org/grpc/Documentation/grpc-auth-support.md delete mode 100755 examples/google.golang.org/grpc/Documentation/grpc-metadata.md delete mode 100755 examples/google.golang.org/grpc/Documentation/log_levels.md delete mode 100755 examples/google.golang.org/grpc/Documentation/rpc-errors.md delete mode 100755 examples/google.golang.org/grpc/Documentation/server-reflection-tutorial.md delete mode 100755 examples/google.golang.org/grpc/Documentation/stickiness.md delete mode 100755 examples/google.golang.org/grpc/Documentation/versioning.md delete mode 100755 examples/google.golang.org/grpc/LICENSE delete mode 100755 examples/google.golang.org/grpc/Makefile delete mode 100755 examples/google.golang.org/grpc/README.md delete mode 100755 examples/google.golang.org/grpc/backoff.go delete mode 100755 examples/google.golang.org/grpc/balancer.go delete mode 100755 examples/google.golang.org/grpc/balancer/balancer.go delete mode 100755 examples/google.golang.org/grpc/balancer/base/balancer.go delete mode 100755 examples/google.golang.org/grpc/balancer/base/base.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb_picker.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb_test.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb_util.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/grpclb_util_test.go delete mode 100755 examples/google.golang.org/grpc/balancer/grpclb/regenerate.sh delete mode 100755 examples/google.golang.org/grpc/balancer/roundrobin/roundrobin.go delete mode 100755 examples/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go delete mode 100755 examples/google.golang.org/grpc/balancer_conn_wrappers.go delete mode 100755 examples/google.golang.org/grpc/balancer_switching_test.go delete mode 100755 examples/google.golang.org/grpc/balancer_test.go delete mode 100755 examples/google.golang.org/grpc/balancer_v1_wrapper.go delete mode 100755 examples/google.golang.org/grpc/benchmark/benchmain/main.go delete mode 100755 examples/google.golang.org/grpc/benchmark/benchmark.go delete mode 100755 examples/google.golang.org/grpc/benchmark/benchmark16_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/benchmark17_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/benchresult/main.go delete mode 100755 examples/google.golang.org/grpc/benchmark/client/main.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/control.proto delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/messages.proto delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/services.proto delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go delete mode 100755 examples/google.golang.org/grpc/benchmark/grpc_testing/stats.proto delete mode 100755 examples/google.golang.org/grpc/benchmark/latency/latency.go delete mode 100755 examples/google.golang.org/grpc/benchmark/latency/latency_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/primitives/code_string_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/primitives/context_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/primitives/primitives_test.go delete mode 100755 examples/google.golang.org/grpc/benchmark/run_bench.sh delete mode 100755 examples/google.golang.org/grpc/benchmark/server/main.go delete mode 100755 examples/google.golang.org/grpc/benchmark/stats/histogram.go delete mode 100755 examples/google.golang.org/grpc/benchmark/stats/stats.go delete mode 100755 examples/google.golang.org/grpc/benchmark/stats/util.go delete mode 100755 examples/google.golang.org/grpc/benchmark/worker/benchmark_client.go delete mode 100755 examples/google.golang.org/grpc/benchmark/worker/benchmark_server.go delete mode 100755 examples/google.golang.org/grpc/benchmark/worker/main.go delete mode 100755 examples/google.golang.org/grpc/benchmark/worker/util.go delete mode 100755 examples/google.golang.org/grpc/call.go delete mode 100755 examples/google.golang.org/grpc/call_test.go delete mode 100755 examples/google.golang.org/grpc/channelz/grpc_channelz_v1/channelz.pb.go delete mode 100755 examples/google.golang.org/grpc/channelz/service/regenerate.sh delete mode 100755 examples/google.golang.org/grpc/channelz/service/service.go delete mode 100755 examples/google.golang.org/grpc/channelz/service/service_test.go delete mode 100755 examples/google.golang.org/grpc/clientconn.go delete mode 100755 examples/google.golang.org/grpc/clientconn_test.go delete mode 100755 examples/google.golang.org/grpc/codec.go delete mode 100755 examples/google.golang.org/grpc/codec_test.go delete mode 100755 examples/google.golang.org/grpc/codegen.sh delete mode 100755 examples/google.golang.org/grpc/codes/code_string.go delete mode 100755 examples/google.golang.org/grpc/codes/codes.go delete mode 100755 examples/google.golang.org/grpc/codes/codes_test.go delete mode 100755 examples/google.golang.org/grpc/connectivity/connectivity.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/alts.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/alts_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/common.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/common.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/counter.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/counter_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/record.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/conn/record_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/altscontext.pb.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/handshaker.pb.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/transport_security_common.pb.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/regenerate.sh delete mode 100755 examples/google.golang.org/grpc/credentials/alts/core/testutil/testutil.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/utils.go delete mode 100755 examples/google.golang.org/grpc/credentials/alts/utils_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/credentials.go delete mode 100755 examples/google.golang.org/grpc/credentials/credentials_test.go delete mode 100755 examples/google.golang.org/grpc/credentials/credentials_util_go17.go delete mode 100755 examples/google.golang.org/grpc/credentials/credentials_util_go18.go delete mode 100755 examples/google.golang.org/grpc/credentials/credentials_util_pre_go17.go delete mode 100755 examples/google.golang.org/grpc/credentials/oauth/oauth.go delete mode 100755 examples/google.golang.org/grpc/doc.go delete mode 100755 examples/google.golang.org/grpc/encoding/encoding.go delete mode 100755 examples/google.golang.org/grpc/encoding/gzip/gzip.go delete mode 100755 examples/google.golang.org/grpc/encoding/proto/proto.go delete mode 100755 examples/google.golang.org/grpc/encoding/proto/proto_benchmark_test.go delete mode 100755 examples/google.golang.org/grpc/encoding/proto/proto_test.go delete mode 100755 examples/google.golang.org/grpc/envconfig.go delete mode 100755 examples/google.golang.org/grpc/examples/README.md delete mode 100755 examples/google.golang.org/grpc/examples/gotutorial.md delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/greeter_client/main.go delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/greeter_server/main.go delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go delete mode 100755 examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go delete mode 100755 examples/google.golang.org/grpc/examples/oauth/client/main.go delete mode 100755 examples/google.golang.org/grpc/examples/oauth/server/main.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/README.md delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/client/client.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/server/server.go delete mode 100755 examples/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json delete mode 100755 examples/google.golang.org/grpc/examples/rpc_errors/client/main.go delete mode 100755 examples/google.golang.org/grpc/examples/rpc_errors/server/main.go delete mode 100755 examples/google.golang.org/grpc/go16.go delete mode 100755 examples/google.golang.org/grpc/go17.go delete mode 100755 examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go delete mode 100755 examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto delete mode 100755 examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go delete mode 100755 examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto delete mode 100755 examples/google.golang.org/grpc/grpclb/noimport.go delete mode 100755 examples/google.golang.org/grpc/grpclog/glogger/glogger.go delete mode 100755 examples/google.golang.org/grpc/grpclog/grpclog.go delete mode 100755 examples/google.golang.org/grpc/grpclog/logger.go delete mode 100755 examples/google.golang.org/grpc/grpclog/loggerv2.go delete mode 100755 examples/google.golang.org/grpc/grpclog/loggerv2_test.go delete mode 100755 examples/google.golang.org/grpc/health/grpc_health_v1/health.pb.go delete mode 100755 examples/google.golang.org/grpc/health/health.go delete mode 100755 examples/google.golang.org/grpc/health/regenerate.sh delete mode 100755 examples/google.golang.org/grpc/interceptor.go delete mode 100755 examples/google.golang.org/grpc/internal/backoff/backoff.go delete mode 100755 examples/google.golang.org/grpc/internal/channelz/funcs.go delete mode 100755 examples/google.golang.org/grpc/internal/channelz/types.go delete mode 100755 examples/google.golang.org/grpc/internal/grpcrand/grpcrand.go delete mode 100755 examples/google.golang.org/grpc/internal/internal.go delete mode 100755 examples/google.golang.org/grpc/internal/leakcheck/leakcheck.go delete mode 100755 examples/google.golang.org/grpc/internal/leakcheck/leakcheck_test.go delete mode 100755 examples/google.golang.org/grpc/interop/alts/client/client.go delete mode 100755 examples/google.golang.org/grpc/interop/alts/server/server.go delete mode 100755 examples/google.golang.org/grpc/interop/client/client.go delete mode 100755 examples/google.golang.org/grpc/interop/grpc_testing/test.pb.go delete mode 100755 examples/google.golang.org/grpc/interop/grpc_testing/test.proto delete mode 100755 examples/google.golang.org/grpc/interop/http2/negative_http2_client.go delete mode 100755 examples/google.golang.org/grpc/interop/server/server.go delete mode 100755 examples/google.golang.org/grpc/interop/test_utils.go delete mode 100755 examples/google.golang.org/grpc/keepalive/keepalive.go delete mode 100755 examples/google.golang.org/grpc/metadata/metadata.go delete mode 100755 examples/google.golang.org/grpc/metadata/metadata_test.go delete mode 100755 examples/google.golang.org/grpc/naming/dns_resolver.go delete mode 100755 examples/google.golang.org/grpc/naming/dns_resolver_test.go delete mode 100755 examples/google.golang.org/grpc/naming/go17.go delete mode 100755 examples/google.golang.org/grpc/naming/go17_test.go delete mode 100755 examples/google.golang.org/grpc/naming/go18.go delete mode 100755 examples/google.golang.org/grpc/naming/go18_test.go delete mode 100755 examples/google.golang.org/grpc/naming/naming.go delete mode 100755 examples/google.golang.org/grpc/peer/peer.go delete mode 100755 examples/google.golang.org/grpc/picker_wrapper.go delete mode 100755 examples/google.golang.org/grpc/picker_wrapper_test.go delete mode 100755 examples/google.golang.org/grpc/pickfirst.go delete mode 100755 examples/google.golang.org/grpc/pickfirst_test.go delete mode 100755 examples/google.golang.org/grpc/proxy.go delete mode 100755 examples/google.golang.org/grpc/proxy_test.go delete mode 100755 examples/google.golang.org/grpc/reflection/README.md delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2.proto delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/test.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testing/test.proto delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go delete mode 100755 examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto delete mode 100755 examples/google.golang.org/grpc/reflection/serverreflection.go delete mode 100755 examples/google.golang.org/grpc/reflection/serverreflection_test.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/dns_resolver.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/dns_resolver_test.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/go17.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/go17_test.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/go18.go delete mode 100755 examples/google.golang.org/grpc/resolver/dns/go18_test.go delete mode 100755 examples/google.golang.org/grpc/resolver/manual/manual.go delete mode 100755 examples/google.golang.org/grpc/resolver/passthrough/passthrough.go delete mode 100755 examples/google.golang.org/grpc/resolver/resolver.go delete mode 100755 examples/google.golang.org/grpc/resolver_conn_wrapper.go delete mode 100755 examples/google.golang.org/grpc/resolver_conn_wrapper_test.go delete mode 100755 examples/google.golang.org/grpc/rpc_util.go delete mode 100755 examples/google.golang.org/grpc/rpc_util_test.go delete mode 100755 examples/google.golang.org/grpc/server.go delete mode 100755 examples/google.golang.org/grpc/server_test.go delete mode 100755 examples/google.golang.org/grpc/service_config.go delete mode 100755 examples/google.golang.org/grpc/service_config_test.go delete mode 100755 examples/google.golang.org/grpc/stats/grpc_testing/test.pb.go delete mode 100755 examples/google.golang.org/grpc/stats/grpc_testing/test.proto delete mode 100755 examples/google.golang.org/grpc/stats/handlers.go delete mode 100755 examples/google.golang.org/grpc/stats/stats.go delete mode 100755 examples/google.golang.org/grpc/stats/stats_test.go delete mode 100755 examples/google.golang.org/grpc/status/go16.go delete mode 100755 examples/google.golang.org/grpc/status/go17.go delete mode 100755 examples/google.golang.org/grpc/status/go17_test.go delete mode 100755 examples/google.golang.org/grpc/status/status.go delete mode 100755 examples/google.golang.org/grpc/status/status_test.go delete mode 100755 examples/google.golang.org/grpc/stickiness_linkedmap.go delete mode 100755 examples/google.golang.org/grpc/stickiness_linkedmap_test.go delete mode 100755 examples/google.golang.org/grpc/stickiness_test.go delete mode 100755 examples/google.golang.org/grpc/stream.go delete mode 100755 examples/google.golang.org/grpc/stress/client/main.go delete mode 100755 examples/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go delete mode 100755 examples/google.golang.org/grpc/stress/grpc_testing/metrics.proto delete mode 100755 examples/google.golang.org/grpc/stress/metrics_client/main.go delete mode 100755 examples/google.golang.org/grpc/tap/tap.go delete mode 100755 examples/google.golang.org/grpc/test/bufconn/bufconn.go delete mode 100755 examples/google.golang.org/grpc/test/bufconn/bufconn_test.go delete mode 100755 examples/google.golang.org/grpc/test/channelz_test.go delete mode 100755 examples/google.golang.org/grpc/test/codec_perf/perf.pb.go delete mode 100755 examples/google.golang.org/grpc/test/codec_perf/perf.proto delete mode 100755 examples/google.golang.org/grpc/test/end2end_test.go delete mode 100755 examples/google.golang.org/grpc/test/gracefulstop_test.go delete mode 100755 examples/google.golang.org/grpc/test/grpc_testing/test.pb.go delete mode 100755 examples/google.golang.org/grpc/test/grpc_testing/test.proto delete mode 100755 examples/google.golang.org/grpc/test/race.go delete mode 100755 examples/google.golang.org/grpc/test/rawConnWrapper.go delete mode 100755 examples/google.golang.org/grpc/test/servertester.go delete mode 100755 examples/google.golang.org/grpc/testdata/ca.pem delete mode 100755 examples/google.golang.org/grpc/testdata/server1.key delete mode 100755 examples/google.golang.org/grpc/testdata/server1.pem delete mode 100755 examples/google.golang.org/grpc/testdata/testdata.go delete mode 100755 examples/google.golang.org/grpc/trace.go delete mode 100755 examples/google.golang.org/grpc/transport/bdp_estimator.go delete mode 100755 examples/google.golang.org/grpc/transport/controlbuf.go delete mode 100755 examples/google.golang.org/grpc/transport/flowcontrol.go delete mode 100755 examples/google.golang.org/grpc/transport/go16.go delete mode 100755 examples/google.golang.org/grpc/transport/go17.go delete mode 100755 examples/google.golang.org/grpc/transport/handler_server.go delete mode 100755 examples/google.golang.org/grpc/transport/handler_server_test.go delete mode 100755 examples/google.golang.org/grpc/transport/http2_client.go delete mode 100755 examples/google.golang.org/grpc/transport/http2_server.go delete mode 100755 examples/google.golang.org/grpc/transport/http_util.go delete mode 100755 examples/google.golang.org/grpc/transport/http_util_test.go delete mode 100755 examples/google.golang.org/grpc/transport/log.go delete mode 100755 examples/google.golang.org/grpc/transport/transport.go delete mode 100755 examples/google.golang.org/grpc/transport/transport_test.go delete mode 100755 examples/google.golang.org/grpc/version.go delete mode 100755 examples/google.golang.org/grpc/vet.sh diff --git a/examples/README.md b/examples/README.md index 4f44091..8df2d41 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,13 +1,3 @@ ## 代码列表 TODO - -## 第三方库 - -- [golang.org/x/net/{context|http2|trace}](https://github.com/golang/net): [32a936](https://github.com/golang/net/tree/32a936f46389aa10549d60bd7833e54b01685d09) -- [Protobuf](https://github.com/golang/protobuf): [v1.1.0](https://github.com/golang/protobuf/releases/tag/v1.1.0) -- [gRPC](https://github.com/grpc/grpc-go): [v1.13.0](https://github.com/grpc/grpc-go/releases/tag/v1.13.0) -- [grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway): [v1.4.1](https://github.com/grpc-ecosystem/grpc-gateway/releases/tag/v1.4.1) -- [grpc-middleware](https://github.com/grpc-ecosystem/go-grpc-middleware): [v1.0.0](https://github.com/grpc-ecosystem/go-grpc-middleware/releases/tag/v1.0.0) -- [pubsub](https://godoc.org/github.com/docker/docker/pkg/pubsub): [v17.03.2-ce](https://github.com/moby/moby/releases/tag/v17.03.2-ce) -- [go-proto-validators](https://github.com/mwitkow/go-proto-validators): [0950a7](https://github.com/mwitkow/go-proto-validators/tree/0950a79900071e9f3f5979b78078c599376422fd) diff --git a/examples/github.com/docker/docker/pkg/pubsub/publisher.go b/examples/github.com/docker/docker/pkg/pubsub/publisher.go deleted file mode 100644 index 76033ed..0000000 --- a/examples/github.com/docker/docker/pkg/pubsub/publisher.go +++ /dev/null @@ -1,121 +0,0 @@ -package pubsub // import "github.com/docker/docker/pkg/pubsub" - -import ( - "sync" - "time" -) - -var wgPool = sync.Pool{New: func() interface{} { return new(sync.WaitGroup) }} - -// NewPublisher creates a new pub/sub publisher to broadcast messages. -// The duration is used as the send timeout as to not block the publisher publishing -// messages to other clients if one client is slow or unresponsive. -// The buffer is used when creating new channels for subscribers. -func NewPublisher(publishTimeout time.Duration, buffer int) *Publisher { - return &Publisher{ - buffer: buffer, - timeout: publishTimeout, - subscribers: make(map[subscriber]topicFunc), - } -} - -type subscriber chan interface{} -type topicFunc func(v interface{}) bool - -// Publisher is basic pub/sub structure. Allows to send events and subscribe -// to them. Can be safely used from multiple goroutines. -type Publisher struct { - m sync.RWMutex - buffer int - timeout time.Duration - subscribers map[subscriber]topicFunc -} - -// Len returns the number of subscribers for the publisher -func (p *Publisher) Len() int { - p.m.RLock() - i := len(p.subscribers) - p.m.RUnlock() - return i -} - -// Subscribe adds a new subscriber to the publisher returning the channel. -func (p *Publisher) Subscribe() chan interface{} { - return p.SubscribeTopic(nil) -} - -// SubscribeTopic adds a new subscriber that filters messages sent by a topic. -func (p *Publisher) SubscribeTopic(topic topicFunc) chan interface{} { - ch := make(chan interface{}, p.buffer) - p.m.Lock() - p.subscribers[ch] = topic - p.m.Unlock() - return ch -} - -// SubscribeTopicWithBuffer adds a new subscriber that filters messages sent by a topic. -// The returned channel has a buffer of the specified size. -func (p *Publisher) SubscribeTopicWithBuffer(topic topicFunc, buffer int) chan interface{} { - ch := make(chan interface{}, buffer) - p.m.Lock() - p.subscribers[ch] = topic - p.m.Unlock() - return ch -} - -// Evict removes the specified subscriber from receiving any more messages. -func (p *Publisher) Evict(sub chan interface{}) { - p.m.Lock() - delete(p.subscribers, sub) - close(sub) - p.m.Unlock() -} - -// Publish sends the data in v to all subscribers currently registered with the publisher. -func (p *Publisher) Publish(v interface{}) { - p.m.RLock() - if len(p.subscribers) == 0 { - p.m.RUnlock() - return - } - - wg := wgPool.Get().(*sync.WaitGroup) - for sub, topic := range p.subscribers { - wg.Add(1) - go p.sendTopic(sub, topic, v, wg) - } - wg.Wait() - wgPool.Put(wg) - p.m.RUnlock() -} - -// Close closes the channels to all subscribers registered with the publisher. -func (p *Publisher) Close() { - p.m.Lock() - for sub := range p.subscribers { - delete(p.subscribers, sub) - close(sub) - } - p.m.Unlock() -} - -func (p *Publisher) sendTopic(sub subscriber, topic topicFunc, v interface{}, wg *sync.WaitGroup) { - defer wg.Done() - if topic != nil && !topic(v) { - return - } - - // send under a select as to not block if the receiver is unavailable - if p.timeout > 0 { - select { - case sub <- v: - case <-time.After(p.timeout): - } - return - } - - select { - case sub <- v: - default: - } -} diff --git a/examples/github.com/docker/docker/pkg/pubsub/publisher_test.go b/examples/github.com/docker/docker/pkg/pubsub/publisher_test.go deleted file mode 100644 index 98e1582..0000000 --- a/examples/github.com/docker/docker/pkg/pubsub/publisher_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package pubsub // import "github.com/docker/docker/pkg/pubsub" - -import ( - "fmt" - "testing" - "time" -) - -func TestSendToOneSub(t *testing.T) { - p := NewPublisher(100*time.Millisecond, 10) - c := p.Subscribe() - - p.Publish("hi") - - msg := <-c - if msg.(string) != "hi" { - t.Fatalf("expected message hi but received %v", msg) - } -} - -func TestSendToMultipleSubs(t *testing.T) { - p := NewPublisher(100*time.Millisecond, 10) - var subs []chan interface{} - subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) - - p.Publish("hi") - - for _, c := range subs { - msg := <-c - if msg.(string) != "hi" { - t.Fatalf("expected message hi but received %v", msg) - } - } -} - -func TestEvictOneSub(t *testing.T) { - p := NewPublisher(100*time.Millisecond, 10) - s1 := p.Subscribe() - s2 := p.Subscribe() - - p.Evict(s1) - p.Publish("hi") - if _, ok := <-s1; ok { - t.Fatal("expected s1 to not receive the published message") - } - - msg := <-s2 - if msg.(string) != "hi" { - t.Fatalf("expected message hi but received %v", msg) - } -} - -func TestClosePublisher(t *testing.T) { - p := NewPublisher(100*time.Millisecond, 10) - var subs []chan interface{} - subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) - p.Close() - - for _, c := range subs { - if _, ok := <-c; ok { - t.Fatal("expected all subscriber channels to be closed") - } - } -} - -const sampleText = "test" - -type testSubscriber struct { - dataCh chan interface{} - ch chan error -} - -func (s *testSubscriber) Wait() error { - return <-s.ch -} - -func newTestSubscriber(p *Publisher) *testSubscriber { - ts := &testSubscriber{ - dataCh: p.Subscribe(), - ch: make(chan error), - } - go func() { - for data := range ts.dataCh { - s, ok := data.(string) - if !ok { - ts.ch <- fmt.Errorf("Unexpected type %T", data) - break - } - if s != sampleText { - ts.ch <- fmt.Errorf("Unexpected text %s", s) - break - } - } - close(ts.ch) - }() - return ts -} - -// for testing with -race -func TestPubSubRace(t *testing.T) { - p := NewPublisher(0, 1024) - var subs []*testSubscriber - for j := 0; j < 50; j++ { - subs = append(subs, newTestSubscriber(p)) - } - for j := 0; j < 1000; j++ { - p.Publish(sampleText) - } - time.AfterFunc(1*time.Second, func() { - for _, s := range subs { - p.Evict(s.dataCh) - } - }) - for _, s := range subs { - s.Wait() - } -} - -func BenchmarkPubSub(b *testing.B) { - for i := 0; i < b.N; i++ { - b.StopTimer() - p := NewPublisher(0, 1024) - var subs []*testSubscriber - for j := 0; j < 50; j++ { - subs = append(subs, newTestSubscriber(p)) - } - b.StartTimer() - for j := 0; j < 1000; j++ { - p.Publish(sampleText) - } - time.AfterFunc(1*time.Second, func() { - for _, s := range subs { - p.Evict(s.dataCh) - } - }) - for _, s := range subs { - if err := s.Wait(); err != nil { - b.Fatal(err) - } - } - } -} diff --git a/examples/github.com/golang/protobuf/.gitignore b/examples/github.com/golang/protobuf/.gitignore deleted file mode 100755 index c7dd405..0000000 --- a/examples/github.com/golang/protobuf/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -.DS_Store -*.[568ao] -*.ao -*.so -*.pyc -._* -.nfs.* -[568a].out -*~ -*.orig -core -_obj -_test -_testmain.go - -# Conformance test output and transient files. -conformance/failing_tests.txt diff --git a/examples/github.com/golang/protobuf/.travis.yml b/examples/github.com/golang/protobuf/.travis.yml deleted file mode 100755 index 455fa66..0000000 --- a/examples/github.com/golang/protobuf/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -sudo: false -language: go -go: -- 1.6.x -- 1.10.x -- 1.x - -install: - - go get -v -d -t github.com/golang/protobuf/... - - curl -L https://github.com/google/protobuf/releases/download/v3.5.1/protoc-3.5.1-linux-x86_64.zip -o /tmp/protoc.zip - - unzip /tmp/protoc.zip -d "$HOME"/protoc - - mkdir -p "$HOME"/src && ln -s "$HOME"/protoc "$HOME"/src/protobuf - -env: - - PATH=$HOME/protoc/bin:$PATH - -script: - - make all - - make regenerate - # TODO(tamird): When https://github.com/travis-ci/gimme/pull/130 is - # released, make this look for "1.x". - - if [[ "$TRAVIS_GO_VERSION" == 1.10* ]]; then - if [[ "$(git status --porcelain 2>&1)" != "" ]]; then - git status >&2; - git diff -a >&2; - exit 1; - fi; - echo "git status is clean."; - fi; - - make test diff --git a/examples/github.com/golang/protobuf/AUTHORS b/examples/github.com/golang/protobuf/AUTHORS deleted file mode 100755 index 15167cd..0000000 --- a/examples/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/examples/github.com/golang/protobuf/CONTRIBUTORS b/examples/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100755 index 1c4577e..0000000 --- a/examples/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/examples/github.com/golang/protobuf/LICENSE b/examples/github.com/golang/protobuf/LICENSE deleted file mode 100755 index 1b1b192..0000000 --- a/examples/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,31 +0,0 @@ -Go support for Protocol Buffers - Google's data interchange format - -Copyright 2010 The Go Authors. All rights reserved. -https://github.com/golang/protobuf - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/examples/github.com/golang/protobuf/Makefile b/examples/github.com/golang/protobuf/Makefile deleted file mode 100755 index 2bc2621..0000000 --- a/examples/github.com/golang/protobuf/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -all: install - -install: - go install ./proto ./jsonpb ./ptypes ./protoc-gen-go - -test: - go test ./... ./protoc-gen-go/testdata - make -C conformance test - -clean: - go clean ./... - -nuke: - go clean -i ./... - -regenerate: - ./regenerate.sh diff --git a/examples/github.com/golang/protobuf/README.md b/examples/github.com/golang/protobuf/README.md deleted file mode 100755 index 01b29da..0000000 --- a/examples/github.com/golang/protobuf/README.md +++ /dev/null @@ -1,283 +0,0 @@ -# Go support for Protocol Buffers - -[![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf) -[![GoDoc](https://godoc.org/github.com/golang/protobuf?status.svg)](https://godoc.org/github.com/golang/protobuf) - -Google's data interchange format. -Copyright 2010 The Go Authors. -https://github.com/golang/protobuf - -This package and the code it generates requires at least Go 1.6. - -This software implements Go bindings for protocol buffers. For -information about protocol buffers themselves, see - https://developers.google.com/protocol-buffers/ - -## Installation ## - -To use this software, you must: -- Install the standard C++ implementation of protocol buffers from - https://developers.google.com/protocol-buffers/ -- Of course, install the Go compiler and tools from - https://golang.org/ - See - https://golang.org/doc/install - for details or, if you are using gccgo, follow the instructions at - https://golang.org/doc/install/gccgo -- Grab the code from the repository and install the proto package. - The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. - The compiler plugin, protoc-gen-go, will be installed in $GOBIN, - defaulting to $GOPATH/bin. It must be in your $PATH for the protocol - compiler, protoc, to find it. - -This software has two parts: a 'protocol compiler plugin' that -generates Go source files that, once compiled, can access and manage -protocol buffers; and a library that implements run-time support for -encoding (marshaling), decoding (unmarshaling), and accessing protocol -buffers. - -There is support for gRPC in Go using protocol buffers. -See the note at the bottom of this file for details. - -There are no insertion points in the plugin. - - -## Using protocol buffers with Go ## - -Once the software is installed, there are two steps to using it. -First you must compile the protocol buffer definitions and then import -them, with the support library, into your program. - -To compile the protocol buffer definition, run protoc with the --go_out -parameter set to the directory you want to output the Go code to. - - protoc --go_out=. *.proto - -The generated files will be suffixed .pb.go. See the Test code below -for an example using such a file. - -## Packages and input paths ## - -The protocol buffer language has a concept of "packages" which does not -correspond well to the Go notion of packages. In generated Go code, -each source `.proto` file is associated with a single Go package. The -name and import path for this package is specified with the `go_package` -proto option: - - option go_package = "github.com/golang/protobuf/ptypes/any"; - -The protocol buffer compiler will attempt to derive a package name and -import path if a `go_package` option is not present, but it is -best to always specify one explicitly. - -There is a one-to-one relationship between source `.proto` files and -generated `.pb.go` files, but any number of `.pb.go` files may be -contained in the same Go package. - -The output name of a generated file is produced by replacing the -`.proto` suffix with `.pb.go` (e.g., `foo.proto` produces `foo.pb.go`). -However, the output directory is selected in one of two ways. Let -us say we have `inputs/x.proto` with a `go_package` option of -`github.com/golang/protobuf/p`. The corresponding output file may -be: - -- Relative to the import path: - - protoc --go_out=. inputs/x.proto - # writes ./github.com/golang/protobuf/p/x.pb.go - - (This can work well with `--go_out=$GOPATH`.) - -- Relative to the input file: - - protoc --go_out=paths=source_relative:. inputs/x.proto - # generate ./inputs/x.pb.go - -## Generated code ## - -The package comment for the proto library contains text describing -the interface provided in Go for protocol buffers. Here is an edited -version. - -The proto package converts data structures to and from the -wire format of protocol buffers. It works in concert with the -Go source code generated for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - Helpers for getting values are superseded by the - GetFoo methods and their use is deprecated. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed with the enum's type name. Enum types have - a String method, and a Enum method to assist in message construction. - - Nested groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -Consider file test.proto, containing - -```proto - syntax = "proto2"; - package example; - - enum FOO { X = 17; }; - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - } -``` - -To create and play with a Test object from the example package, - -```go - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - "path/to/example" - ) - - func main() { - test := &example.Test { - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &example.Test_OptionalGroup { - RequiredField: proto.String("good bye"), - }, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &example.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // etc. - } -``` - -## Parameters ## - -To pass extra parameters to the plugin, use a comma-separated -parameter list separated from the output directory by a colon: - - protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - -- `paths=(import | source_relative)` - specifies how the paths of - generated files are structured. See the "Packages and imports paths" - section above. The default is `import`. -- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to - load. The only plugin in this repo is `grpc`. -- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is - associated with Go package quux/shme. This is subject to the - import_prefix parameter. - -The following parameters are deprecated and should not be used: - -- `import_prefix=xxx` - a prefix that is added onto the beginning of - all imports. -- `import_path=foo/bar` - used as the package if no input files - declare `go_package`. If it contains slashes, everything up to the - rightmost slash is ignored. - -## gRPC Support ## - -If a proto file specifies RPC services, protoc-gen-go can be instructed to -generate code compatible with gRPC (http://www.grpc.io/). To do this, pass -the `plugins` parameter to protoc-gen-go; the usual way is to insert it into -the --go_out argument to protoc: - - protoc --go_out=plugins=grpc:. *.proto - -## Compatibility ## - -The library and the generated code are expected to be stable over time. -However, we reserve the right to make breaking changes without notice for the -following reasons: - -- Security. A security issue in the specification or implementation may come to - light whose resolution requires breaking compatibility. We reserve the right - to address such security issues. -- Unspecified behavior. There are some aspects of the Protocol Buffers - specification that are undefined. Programs that depend on such unspecified - behavior may break in future releases. -- Specification errors or changes. If it becomes necessary to address an - inconsistency, incompleteness, or change in the Protocol Buffers - specification, resolving the issue could affect the meaning or legality of - existing programs. We reserve the right to address such issues, including - updating the implementations. -- Bugs. If the library has a bug that violates the specification, a program - that depends on the buggy behavior may break if the bug is fixed. We reserve - the right to fix such bugs. -- Adding methods or fields to generated structs. These may conflict with field - names that already exist in a schema, causing applications to break. When the - code generator encounters a field in the schema that would collide with a - generated field or method name, the code generator will append an underscore - to the generated field or method name. -- Adding, removing, or changing methods or fields in generated structs that - start with `XXX`. These parts of the generated code are exported out of - necessity, but should not be considered part of the public API. -- Adding, removing, or changing unexported symbols in generated code. - -Any breaking changes outside of these will be announced 6 months in advance to -protobuf@googlegroups.com. - -You should, whenever possible, use generated code created by the `protoc-gen-go` -tool built at the same commit as the `proto` package. The `proto` package -declares package-level constants in the form `ProtoPackageIsVersionX`. -Application code and generated code may depend on one of these constants to -ensure that compilation will fail if the available version of the proto library -is too old. Whenever we make a change to the generated code that requires newer -library support, in the same commit we will increment the version number of the -generated code and declare a new package-level constant whose name incorporates -the latest version number. Removing a compatibility constant is considered a -breaking change and would be subject to the announcement policy stated above. - -The `protoc-gen-go/generator` package exposes a plugin interface, -which is used by the gRPC code generation. This interface is not -supported and is subject to incompatible changes without notice. diff --git a/examples/github.com/golang/protobuf/conformance/Makefile b/examples/github.com/golang/protobuf/conformance/Makefile deleted file mode 100755 index b99e4ed..0000000 --- a/examples/github.com/golang/protobuf/conformance/Makefile +++ /dev/null @@ -1,49 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2016 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -PROTOBUF_ROOT=$(HOME)/src/protobuf - -all: - @echo To run the tests in this directory, acquire the main protobuf - @echo distribution from: - @echo - @echo ' https://github.com/google/protobuf' - @echo - @echo Build the test runner with: - @echo - @echo ' cd conformance && make conformance-test-runner' - @echo - @echo And run the tests in this directory with: - @echo - @echo ' make test PROTOBUF_ROOT=' - -test: - ./test.sh $(PROTOBUF_ROOT) diff --git a/examples/github.com/golang/protobuf/conformance/conformance.go b/examples/github.com/golang/protobuf/conformance/conformance.go deleted file mode 100755 index 3029312..0000000 --- a/examples/github.com/golang/protobuf/conformance/conformance.go +++ /dev/null @@ -1,154 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// conformance implements the conformance test subprocess protocol as -// documented in conformance.proto. -package main - -import ( - "encoding/binary" - "fmt" - "io" - "os" - - pb "github.com/golang/protobuf/conformance/internal/conformance_proto" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" -) - -func main() { - var sizeBuf [4]byte - inbuf := make([]byte, 0, 4096) - outbuf := proto.NewBuffer(nil) - for { - if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF { - break - } else if err != nil { - fmt.Fprintln(os.Stderr, "go conformance: read request:", err) - os.Exit(1) - } - size := binary.LittleEndian.Uint32(sizeBuf[:]) - if int(size) > cap(inbuf) { - inbuf = make([]byte, size) - } - inbuf = inbuf[:size] - if _, err := io.ReadFull(os.Stdin, inbuf); err != nil { - fmt.Fprintln(os.Stderr, "go conformance: read request:", err) - os.Exit(1) - } - - req := new(pb.ConformanceRequest) - if err := proto.Unmarshal(inbuf, req); err != nil { - fmt.Fprintln(os.Stderr, "go conformance: parse request:", err) - os.Exit(1) - } - res := handle(req) - - if err := outbuf.Marshal(res); err != nil { - fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err) - os.Exit(1) - } - binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes()))) - if _, err := os.Stdout.Write(sizeBuf[:]); err != nil { - fmt.Fprintln(os.Stderr, "go conformance: write response:", err) - os.Exit(1) - } - if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil { - fmt.Fprintln(os.Stderr, "go conformance: write response:", err) - os.Exit(1) - } - outbuf.Reset() - } -} - -var jsonMarshaler = jsonpb.Marshaler{ - OrigName: true, -} - -func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse { - var err error - var msg pb.TestAllTypes - switch p := req.Payload.(type) { - case *pb.ConformanceRequest_ProtobufPayload: - err = proto.Unmarshal(p.ProtobufPayload, &msg) - case *pb.ConformanceRequest_JsonPayload: - err = jsonpb.UnmarshalString(p.JsonPayload, &msg) - default: - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_RuntimeError{ - RuntimeError: "unknown request payload type", - }, - } - } - if err != nil { - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_ParseError{ - ParseError: err.Error(), - }, - } - } - switch req.RequestedOutputFormat { - case pb.WireFormat_PROTOBUF: - p, err := proto.Marshal(&msg) - if err != nil { - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_SerializeError{ - SerializeError: err.Error(), - }, - } - } - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_ProtobufPayload{ - ProtobufPayload: p, - }, - } - case pb.WireFormat_JSON: - p, err := jsonMarshaler.MarshalToString(&msg) - if err != nil { - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_SerializeError{ - SerializeError: err.Error(), - }, - } - } - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_JsonPayload{ - JsonPayload: p, - }, - } - default: - return &pb.ConformanceResponse{ - Result: &pb.ConformanceResponse_RuntimeError{ - RuntimeError: "unknown output format", - }, - } - } -} diff --git a/examples/github.com/golang/protobuf/conformance/conformance.sh b/examples/github.com/golang/protobuf/conformance/conformance.sh deleted file mode 100755 index 8532f57..0000000 --- a/examples/github.com/golang/protobuf/conformance/conformance.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -cd $(dirname $0) -exec go run conformance.go $* diff --git a/examples/github.com/golang/protobuf/conformance/failure_list_go.txt b/examples/github.com/golang/protobuf/conformance/failure_list_go.txt deleted file mode 100755 index d372808..0000000 --- a/examples/github.com/golang/protobuf/conformance/failure_list_go.txt +++ /dev/null @@ -1,61 +0,0 @@ -# This is the list of conformance tests that are known ot fail right now. -# TODO: These should be fixed. - -DurationProtoInputTooLarge.JsonOutput -DurationProtoInputTooSmall.JsonOutput -FieldMaskNumbersDontRoundTrip.JsonOutput -FieldMaskPathsDontRoundTrip.JsonOutput -FieldMaskTooManyUnderscore.JsonOutput -JsonInput.AnyWithFieldMask.JsonOutput -JsonInput.AnyWithFieldMask.ProtobufOutput -JsonInput.DoubleFieldQuotedValue.JsonOutput -JsonInput.DoubleFieldQuotedValue.ProtobufOutput -JsonInput.DurationHas3FractionalDigits.Validator -JsonInput.DurationHas6FractionalDigits.Validator -JsonInput.DurationHas9FractionalDigits.Validator -JsonInput.DurationHasZeroFractionalDigit.Validator -JsonInput.DurationMaxValue.JsonOutput -JsonInput.DurationMaxValue.ProtobufOutput -JsonInput.DurationMinValue.JsonOutput -JsonInput.DurationMinValue.ProtobufOutput -JsonInput.EnumFieldUnknownValue.Validator -JsonInput.FieldMask.JsonOutput -JsonInput.FieldMask.ProtobufOutput -JsonInput.FieldNameInLowerCamelCase.Validator -JsonInput.FieldNameWithMixedCases.JsonOutput -JsonInput.FieldNameWithMixedCases.ProtobufOutput -JsonInput.FieldNameWithMixedCases.Validator -JsonInput.FieldNameWithNumbers.Validator -JsonInput.FloatFieldQuotedValue.JsonOutput -JsonInput.FloatFieldQuotedValue.ProtobufOutput -JsonInput.Int32FieldExponentialFormat.JsonOutput -JsonInput.Int32FieldExponentialFormat.ProtobufOutput -JsonInput.Int32FieldFloatTrailingZero.JsonOutput -JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput -JsonInput.Int32FieldMaxFloatValue.JsonOutput -JsonInput.Int32FieldMaxFloatValue.ProtobufOutput -JsonInput.Int32FieldMinFloatValue.JsonOutput -JsonInput.Int32FieldMinFloatValue.ProtobufOutput -JsonInput.Int32FieldStringValue.JsonOutput -JsonInput.Int32FieldStringValue.ProtobufOutput -JsonInput.Int32FieldStringValueEscaped.JsonOutput -JsonInput.Int32FieldStringValueEscaped.ProtobufOutput -JsonInput.Int64FieldBeString.Validator -JsonInput.MapFieldValueIsNull -JsonInput.OneofFieldDuplicate -JsonInput.RepeatedFieldMessageElementIsNull -JsonInput.RepeatedFieldPrimitiveElementIsNull -JsonInput.StringFieldSurrogateInWrongOrder -JsonInput.StringFieldUnpairedHighSurrogate -JsonInput.StringFieldUnpairedLowSurrogate -JsonInput.TimestampHas3FractionalDigits.Validator -JsonInput.TimestampHas6FractionalDigits.Validator -JsonInput.TimestampHas9FractionalDigits.Validator -JsonInput.TimestampHasZeroFractionalDigit.Validator -JsonInput.TimestampJsonInputTooSmall -JsonInput.TimestampZeroNormalized.Validator -JsonInput.Uint32FieldMaxFloatValue.JsonOutput -JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput -JsonInput.Uint64FieldBeString.Validator -TimestampProtoInputTooLarge.JsonOutput -TimestampProtoInputTooSmall.JsonOutput diff --git a/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go b/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go deleted file mode 100755 index 82d4541..0000000 --- a/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.pb.go +++ /dev/null @@ -1,1816 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: conformance.proto - -package conformance - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" -import duration "github.com/golang/protobuf/ptypes/duration" -import _struct "github.com/golang/protobuf/ptypes/struct" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" -import wrappers "github.com/golang/protobuf/ptypes/wrappers" -import field_mask "google.golang.org/genproto/protobuf/field_mask" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type WireFormat int32 - -const ( - WireFormat_UNSPECIFIED WireFormat = 0 - WireFormat_PROTOBUF WireFormat = 1 - WireFormat_JSON WireFormat = 2 -) - -var WireFormat_name = map[int32]string{ - 0: "UNSPECIFIED", - 1: "PROTOBUF", - 2: "JSON", -} -var WireFormat_value = map[string]int32{ - "UNSPECIFIED": 0, - "PROTOBUF": 1, - "JSON": 2, -} - -func (x WireFormat) String() string { - return proto.EnumName(WireFormat_name, int32(x)) -} -func (WireFormat) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{0} -} - -type ForeignEnum int32 - -const ( - ForeignEnum_FOREIGN_FOO ForeignEnum = 0 - ForeignEnum_FOREIGN_BAR ForeignEnum = 1 - ForeignEnum_FOREIGN_BAZ ForeignEnum = 2 -) - -var ForeignEnum_name = map[int32]string{ - 0: "FOREIGN_FOO", - 1: "FOREIGN_BAR", - 2: "FOREIGN_BAZ", -} -var ForeignEnum_value = map[string]int32{ - "FOREIGN_FOO": 0, - "FOREIGN_BAR": 1, - "FOREIGN_BAZ": 2, -} - -func (x ForeignEnum) String() string { - return proto.EnumName(ForeignEnum_name, int32(x)) -} -func (ForeignEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{1} -} - -type TestAllTypes_NestedEnum int32 - -const ( - TestAllTypes_FOO TestAllTypes_NestedEnum = 0 - TestAllTypes_BAR TestAllTypes_NestedEnum = 1 - TestAllTypes_BAZ TestAllTypes_NestedEnum = 2 - TestAllTypes_NEG TestAllTypes_NestedEnum = -1 -) - -var TestAllTypes_NestedEnum_name = map[int32]string{ - 0: "FOO", - 1: "BAR", - 2: "BAZ", - -1: "NEG", -} -var TestAllTypes_NestedEnum_value = map[string]int32{ - "FOO": 0, - "BAR": 1, - "BAZ": 2, - "NEG": -1, -} - -func (x TestAllTypes_NestedEnum) String() string { - return proto.EnumName(TestAllTypes_NestedEnum_name, int32(x)) -} -func (TestAllTypes_NestedEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{2, 0} -} - -// Represents a single test case's input. The testee should: -// -// 1. parse this proto (which should always succeed) -// 2. parse the protobuf or JSON payload in "payload" (which may fail) -// 3. if the parse succeeded, serialize the message in the requested format. -type ConformanceRequest struct { - // The payload (whether protobuf of JSON) is always for a TestAllTypes proto - // (see below). - // - // Types that are valid to be assigned to Payload: - // *ConformanceRequest_ProtobufPayload - // *ConformanceRequest_JsonPayload - Payload isConformanceRequest_Payload `protobuf_oneof:"payload"` - // Which format should the testee serialize its message to? - RequestedOutputFormat WireFormat `protobuf:"varint,3,opt,name=requested_output_format,json=requestedOutputFormat,enum=conformance.WireFormat" json:"requested_output_format,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ConformanceRequest) Reset() { *m = ConformanceRequest{} } -func (m *ConformanceRequest) String() string { return proto.CompactTextString(m) } -func (*ConformanceRequest) ProtoMessage() {} -func (*ConformanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{0} -} -func (m *ConformanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ConformanceRequest.Unmarshal(m, b) -} -func (m *ConformanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ConformanceRequest.Marshal(b, m, deterministic) -} -func (dst *ConformanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConformanceRequest.Merge(dst, src) -} -func (m *ConformanceRequest) XXX_Size() int { - return xxx_messageInfo_ConformanceRequest.Size(m) -} -func (m *ConformanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ConformanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ConformanceRequest proto.InternalMessageInfo - -type isConformanceRequest_Payload interface { - isConformanceRequest_Payload() -} - -type ConformanceRequest_ProtobufPayload struct { - ProtobufPayload []byte `protobuf:"bytes,1,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` -} -type ConformanceRequest_JsonPayload struct { - JsonPayload string `protobuf:"bytes,2,opt,name=json_payload,json=jsonPayload,oneof"` -} - -func (*ConformanceRequest_ProtobufPayload) isConformanceRequest_Payload() {} -func (*ConformanceRequest_JsonPayload) isConformanceRequest_Payload() {} - -func (m *ConformanceRequest) GetPayload() isConformanceRequest_Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *ConformanceRequest) GetProtobufPayload() []byte { - if x, ok := m.GetPayload().(*ConformanceRequest_ProtobufPayload); ok { - return x.ProtobufPayload - } - return nil -} - -func (m *ConformanceRequest) GetJsonPayload() string { - if x, ok := m.GetPayload().(*ConformanceRequest_JsonPayload); ok { - return x.JsonPayload - } - return "" -} - -func (m *ConformanceRequest) GetRequestedOutputFormat() WireFormat { - if m != nil { - return m.RequestedOutputFormat - } - return WireFormat_UNSPECIFIED -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ConformanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ConformanceRequest_OneofMarshaler, _ConformanceRequest_OneofUnmarshaler, _ConformanceRequest_OneofSizer, []interface{}{ - (*ConformanceRequest_ProtobufPayload)(nil), - (*ConformanceRequest_JsonPayload)(nil), - } -} - -func _ConformanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ConformanceRequest) - // payload - switch x := m.Payload.(type) { - case *ConformanceRequest_ProtobufPayload: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeRawBytes(x.ProtobufPayload) - case *ConformanceRequest_JsonPayload: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.JsonPayload) - case nil: - default: - return fmt.Errorf("ConformanceRequest.Payload has unexpected type %T", x) - } - return nil -} - -func _ConformanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ConformanceRequest) - switch tag { - case 1: // payload.protobuf_payload - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Payload = &ConformanceRequest_ProtobufPayload{x} - return true, err - case 2: // payload.json_payload - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Payload = &ConformanceRequest_JsonPayload{x} - return true, err - default: - return false, nil - } -} - -func _ConformanceRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ConformanceRequest) - // payload - switch x := m.Payload.(type) { - case *ConformanceRequest_ProtobufPayload: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) - n += len(x.ProtobufPayload) - case *ConformanceRequest_JsonPayload: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.JsonPayload))) - n += len(x.JsonPayload) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Represents a single test case's output. -type ConformanceResponse struct { - // Types that are valid to be assigned to Result: - // *ConformanceResponse_ParseError - // *ConformanceResponse_SerializeError - // *ConformanceResponse_RuntimeError - // *ConformanceResponse_ProtobufPayload - // *ConformanceResponse_JsonPayload - // *ConformanceResponse_Skipped - Result isConformanceResponse_Result `protobuf_oneof:"result"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ConformanceResponse) Reset() { *m = ConformanceResponse{} } -func (m *ConformanceResponse) String() string { return proto.CompactTextString(m) } -func (*ConformanceResponse) ProtoMessage() {} -func (*ConformanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{1} -} -func (m *ConformanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ConformanceResponse.Unmarshal(m, b) -} -func (m *ConformanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ConformanceResponse.Marshal(b, m, deterministic) -} -func (dst *ConformanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConformanceResponse.Merge(dst, src) -} -func (m *ConformanceResponse) XXX_Size() int { - return xxx_messageInfo_ConformanceResponse.Size(m) -} -func (m *ConformanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ConformanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ConformanceResponse proto.InternalMessageInfo - -type isConformanceResponse_Result interface { - isConformanceResponse_Result() -} - -type ConformanceResponse_ParseError struct { - ParseError string `protobuf:"bytes,1,opt,name=parse_error,json=parseError,oneof"` -} -type ConformanceResponse_SerializeError struct { - SerializeError string `protobuf:"bytes,6,opt,name=serialize_error,json=serializeError,oneof"` -} -type ConformanceResponse_RuntimeError struct { - RuntimeError string `protobuf:"bytes,2,opt,name=runtime_error,json=runtimeError,oneof"` -} -type ConformanceResponse_ProtobufPayload struct { - ProtobufPayload []byte `protobuf:"bytes,3,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` -} -type ConformanceResponse_JsonPayload struct { - JsonPayload string `protobuf:"bytes,4,opt,name=json_payload,json=jsonPayload,oneof"` -} -type ConformanceResponse_Skipped struct { - Skipped string `protobuf:"bytes,5,opt,name=skipped,oneof"` -} - -func (*ConformanceResponse_ParseError) isConformanceResponse_Result() {} -func (*ConformanceResponse_SerializeError) isConformanceResponse_Result() {} -func (*ConformanceResponse_RuntimeError) isConformanceResponse_Result() {} -func (*ConformanceResponse_ProtobufPayload) isConformanceResponse_Result() {} -func (*ConformanceResponse_JsonPayload) isConformanceResponse_Result() {} -func (*ConformanceResponse_Skipped) isConformanceResponse_Result() {} - -func (m *ConformanceResponse) GetResult() isConformanceResponse_Result { - if m != nil { - return m.Result - } - return nil -} - -func (m *ConformanceResponse) GetParseError() string { - if x, ok := m.GetResult().(*ConformanceResponse_ParseError); ok { - return x.ParseError - } - return "" -} - -func (m *ConformanceResponse) GetSerializeError() string { - if x, ok := m.GetResult().(*ConformanceResponse_SerializeError); ok { - return x.SerializeError - } - return "" -} - -func (m *ConformanceResponse) GetRuntimeError() string { - if x, ok := m.GetResult().(*ConformanceResponse_RuntimeError); ok { - return x.RuntimeError - } - return "" -} - -func (m *ConformanceResponse) GetProtobufPayload() []byte { - if x, ok := m.GetResult().(*ConformanceResponse_ProtobufPayload); ok { - return x.ProtobufPayload - } - return nil -} - -func (m *ConformanceResponse) GetJsonPayload() string { - if x, ok := m.GetResult().(*ConformanceResponse_JsonPayload); ok { - return x.JsonPayload - } - return "" -} - -func (m *ConformanceResponse) GetSkipped() string { - if x, ok := m.GetResult().(*ConformanceResponse_Skipped); ok { - return x.Skipped - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ConformanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ConformanceResponse_OneofMarshaler, _ConformanceResponse_OneofUnmarshaler, _ConformanceResponse_OneofSizer, []interface{}{ - (*ConformanceResponse_ParseError)(nil), - (*ConformanceResponse_SerializeError)(nil), - (*ConformanceResponse_RuntimeError)(nil), - (*ConformanceResponse_ProtobufPayload)(nil), - (*ConformanceResponse_JsonPayload)(nil), - (*ConformanceResponse_Skipped)(nil), - } -} - -func _ConformanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ConformanceResponse) - // result - switch x := m.Result.(type) { - case *ConformanceResponse_ParseError: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ParseError) - case *ConformanceResponse_SerializeError: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.SerializeError) - case *ConformanceResponse_RuntimeError: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.RuntimeError) - case *ConformanceResponse_ProtobufPayload: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeRawBytes(x.ProtobufPayload) - case *ConformanceResponse_JsonPayload: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.JsonPayload) - case *ConformanceResponse_Skipped: - b.EncodeVarint(5<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Skipped) - case nil: - default: - return fmt.Errorf("ConformanceResponse.Result has unexpected type %T", x) - } - return nil -} - -func _ConformanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ConformanceResponse) - switch tag { - case 1: // result.parse_error - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Result = &ConformanceResponse_ParseError{x} - return true, err - case 6: // result.serialize_error - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Result = &ConformanceResponse_SerializeError{x} - return true, err - case 2: // result.runtime_error - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Result = &ConformanceResponse_RuntimeError{x} - return true, err - case 3: // result.protobuf_payload - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Result = &ConformanceResponse_ProtobufPayload{x} - return true, err - case 4: // result.json_payload - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Result = &ConformanceResponse_JsonPayload{x} - return true, err - case 5: // result.skipped - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Result = &ConformanceResponse_Skipped{x} - return true, err - default: - return false, nil - } -} - -func _ConformanceResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ConformanceResponse) - // result - switch x := m.Result.(type) { - case *ConformanceResponse_ParseError: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ParseError))) - n += len(x.ParseError) - case *ConformanceResponse_SerializeError: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.SerializeError))) - n += len(x.SerializeError) - case *ConformanceResponse_RuntimeError: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.RuntimeError))) - n += len(x.RuntimeError) - case *ConformanceResponse_ProtobufPayload: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) - n += len(x.ProtobufPayload) - case *ConformanceResponse_JsonPayload: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.JsonPayload))) - n += len(x.JsonPayload) - case *ConformanceResponse_Skipped: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Skipped))) - n += len(x.Skipped) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// This proto includes every type of field in both singular and repeated -// forms. -type TestAllTypes struct { - // Singular - OptionalInt32 int32 `protobuf:"varint,1,opt,name=optional_int32,json=optionalInt32" json:"optional_int32,omitempty"` - OptionalInt64 int64 `protobuf:"varint,2,opt,name=optional_int64,json=optionalInt64" json:"optional_int64,omitempty"` - OptionalUint32 uint32 `protobuf:"varint,3,opt,name=optional_uint32,json=optionalUint32" json:"optional_uint32,omitempty"` - OptionalUint64 uint64 `protobuf:"varint,4,opt,name=optional_uint64,json=optionalUint64" json:"optional_uint64,omitempty"` - OptionalSint32 int32 `protobuf:"zigzag32,5,opt,name=optional_sint32,json=optionalSint32" json:"optional_sint32,omitempty"` - OptionalSint64 int64 `protobuf:"zigzag64,6,opt,name=optional_sint64,json=optionalSint64" json:"optional_sint64,omitempty"` - OptionalFixed32 uint32 `protobuf:"fixed32,7,opt,name=optional_fixed32,json=optionalFixed32" json:"optional_fixed32,omitempty"` - OptionalFixed64 uint64 `protobuf:"fixed64,8,opt,name=optional_fixed64,json=optionalFixed64" json:"optional_fixed64,omitempty"` - OptionalSfixed32 int32 `protobuf:"fixed32,9,opt,name=optional_sfixed32,json=optionalSfixed32" json:"optional_sfixed32,omitempty"` - OptionalSfixed64 int64 `protobuf:"fixed64,10,opt,name=optional_sfixed64,json=optionalSfixed64" json:"optional_sfixed64,omitempty"` - OptionalFloat float32 `protobuf:"fixed32,11,opt,name=optional_float,json=optionalFloat" json:"optional_float,omitempty"` - OptionalDouble float64 `protobuf:"fixed64,12,opt,name=optional_double,json=optionalDouble" json:"optional_double,omitempty"` - OptionalBool bool `protobuf:"varint,13,opt,name=optional_bool,json=optionalBool" json:"optional_bool,omitempty"` - OptionalString string `protobuf:"bytes,14,opt,name=optional_string,json=optionalString" json:"optional_string,omitempty"` - OptionalBytes []byte `protobuf:"bytes,15,opt,name=optional_bytes,json=optionalBytes,proto3" json:"optional_bytes,omitempty"` - OptionalNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,18,opt,name=optional_nested_message,json=optionalNestedMessage" json:"optional_nested_message,omitempty"` - OptionalForeignMessage *ForeignMessage `protobuf:"bytes,19,opt,name=optional_foreign_message,json=optionalForeignMessage" json:"optional_foreign_message,omitempty"` - OptionalNestedEnum TestAllTypes_NestedEnum `protobuf:"varint,21,opt,name=optional_nested_enum,json=optionalNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"optional_nested_enum,omitempty"` - OptionalForeignEnum ForeignEnum `protobuf:"varint,22,opt,name=optional_foreign_enum,json=optionalForeignEnum,enum=conformance.ForeignEnum" json:"optional_foreign_enum,omitempty"` - OptionalStringPiece string `protobuf:"bytes,24,opt,name=optional_string_piece,json=optionalStringPiece" json:"optional_string_piece,omitempty"` - OptionalCord string `protobuf:"bytes,25,opt,name=optional_cord,json=optionalCord" json:"optional_cord,omitempty"` - RecursiveMessage *TestAllTypes `protobuf:"bytes,27,opt,name=recursive_message,json=recursiveMessage" json:"recursive_message,omitempty"` - // Repeated - RepeatedInt32 []int32 `protobuf:"varint,31,rep,packed,name=repeated_int32,json=repeatedInt32" json:"repeated_int32,omitempty"` - RepeatedInt64 []int64 `protobuf:"varint,32,rep,packed,name=repeated_int64,json=repeatedInt64" json:"repeated_int64,omitempty"` - RepeatedUint32 []uint32 `protobuf:"varint,33,rep,packed,name=repeated_uint32,json=repeatedUint32" json:"repeated_uint32,omitempty"` - RepeatedUint64 []uint64 `protobuf:"varint,34,rep,packed,name=repeated_uint64,json=repeatedUint64" json:"repeated_uint64,omitempty"` - RepeatedSint32 []int32 `protobuf:"zigzag32,35,rep,packed,name=repeated_sint32,json=repeatedSint32" json:"repeated_sint32,omitempty"` - RepeatedSint64 []int64 `protobuf:"zigzag64,36,rep,packed,name=repeated_sint64,json=repeatedSint64" json:"repeated_sint64,omitempty"` - RepeatedFixed32 []uint32 `protobuf:"fixed32,37,rep,packed,name=repeated_fixed32,json=repeatedFixed32" json:"repeated_fixed32,omitempty"` - RepeatedFixed64 []uint64 `protobuf:"fixed64,38,rep,packed,name=repeated_fixed64,json=repeatedFixed64" json:"repeated_fixed64,omitempty"` - RepeatedSfixed32 []int32 `protobuf:"fixed32,39,rep,packed,name=repeated_sfixed32,json=repeatedSfixed32" json:"repeated_sfixed32,omitempty"` - RepeatedSfixed64 []int64 `protobuf:"fixed64,40,rep,packed,name=repeated_sfixed64,json=repeatedSfixed64" json:"repeated_sfixed64,omitempty"` - RepeatedFloat []float32 `protobuf:"fixed32,41,rep,packed,name=repeated_float,json=repeatedFloat" json:"repeated_float,omitempty"` - RepeatedDouble []float64 `protobuf:"fixed64,42,rep,packed,name=repeated_double,json=repeatedDouble" json:"repeated_double,omitempty"` - RepeatedBool []bool `protobuf:"varint,43,rep,packed,name=repeated_bool,json=repeatedBool" json:"repeated_bool,omitempty"` - RepeatedString []string `protobuf:"bytes,44,rep,name=repeated_string,json=repeatedString" json:"repeated_string,omitempty"` - RepeatedBytes [][]byte `protobuf:"bytes,45,rep,name=repeated_bytes,json=repeatedBytes,proto3" json:"repeated_bytes,omitempty"` - RepeatedNestedMessage []*TestAllTypes_NestedMessage `protobuf:"bytes,48,rep,name=repeated_nested_message,json=repeatedNestedMessage" json:"repeated_nested_message,omitempty"` - RepeatedForeignMessage []*ForeignMessage `protobuf:"bytes,49,rep,name=repeated_foreign_message,json=repeatedForeignMessage" json:"repeated_foreign_message,omitempty"` - RepeatedNestedEnum []TestAllTypes_NestedEnum `protobuf:"varint,51,rep,packed,name=repeated_nested_enum,json=repeatedNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"repeated_nested_enum,omitempty"` - RepeatedForeignEnum []ForeignEnum `protobuf:"varint,52,rep,packed,name=repeated_foreign_enum,json=repeatedForeignEnum,enum=conformance.ForeignEnum" json:"repeated_foreign_enum,omitempty"` - RepeatedStringPiece []string `protobuf:"bytes,54,rep,name=repeated_string_piece,json=repeatedStringPiece" json:"repeated_string_piece,omitempty"` - RepeatedCord []string `protobuf:"bytes,55,rep,name=repeated_cord,json=repeatedCord" json:"repeated_cord,omitempty"` - // Map - MapInt32Int32 map[int32]int32 `protobuf:"bytes,56,rep,name=map_int32_int32,json=mapInt32Int32" json:"map_int32_int32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - MapInt64Int64 map[int64]int64 `protobuf:"bytes,57,rep,name=map_int64_int64,json=mapInt64Int64" json:"map_int64_int64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - MapUint32Uint32 map[uint32]uint32 `protobuf:"bytes,58,rep,name=map_uint32_uint32,json=mapUint32Uint32" json:"map_uint32_uint32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - MapUint64Uint64 map[uint64]uint64 `protobuf:"bytes,59,rep,name=map_uint64_uint64,json=mapUint64Uint64" json:"map_uint64_uint64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - MapSint32Sint32 map[int32]int32 `protobuf:"bytes,60,rep,name=map_sint32_sint32,json=mapSint32Sint32" json:"map_sint32_sint32,omitempty" protobuf_key:"zigzag32,1,opt,name=key" protobuf_val:"zigzag32,2,opt,name=value"` - MapSint64Sint64 map[int64]int64 `protobuf:"bytes,61,rep,name=map_sint64_sint64,json=mapSint64Sint64" json:"map_sint64_sint64,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"zigzag64,2,opt,name=value"` - MapFixed32Fixed32 map[uint32]uint32 `protobuf:"bytes,62,rep,name=map_fixed32_fixed32,json=mapFixed32Fixed32" json:"map_fixed32_fixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` - MapFixed64Fixed64 map[uint64]uint64 `protobuf:"bytes,63,rep,name=map_fixed64_fixed64,json=mapFixed64Fixed64" json:"map_fixed64_fixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` - MapSfixed32Sfixed32 map[int32]int32 `protobuf:"bytes,64,rep,name=map_sfixed32_sfixed32,json=mapSfixed32Sfixed32" json:"map_sfixed32_sfixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` - MapSfixed64Sfixed64 map[int64]int64 `protobuf:"bytes,65,rep,name=map_sfixed64_sfixed64,json=mapSfixed64Sfixed64" json:"map_sfixed64_sfixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` - MapInt32Float map[int32]float32 `protobuf:"bytes,66,rep,name=map_int32_float,json=mapInt32Float" json:"map_int32_float,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` - MapInt32Double map[int32]float64 `protobuf:"bytes,67,rep,name=map_int32_double,json=mapInt32Double" json:"map_int32_double,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` - MapBoolBool map[bool]bool `protobuf:"bytes,68,rep,name=map_bool_bool,json=mapBoolBool" json:"map_bool_bool,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - MapStringString map[string]string `protobuf:"bytes,69,rep,name=map_string_string,json=mapStringString" json:"map_string_string,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MapStringBytes map[string][]byte `protobuf:"bytes,70,rep,name=map_string_bytes,json=mapStringBytes" json:"map_string_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` - MapStringNestedMessage map[string]*TestAllTypes_NestedMessage `protobuf:"bytes,71,rep,name=map_string_nested_message,json=mapStringNestedMessage" json:"map_string_nested_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MapStringForeignMessage map[string]*ForeignMessage `protobuf:"bytes,72,rep,name=map_string_foreign_message,json=mapStringForeignMessage" json:"map_string_foreign_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MapStringNestedEnum map[string]TestAllTypes_NestedEnum `protobuf:"bytes,73,rep,name=map_string_nested_enum,json=mapStringNestedEnum" json:"map_string_nested_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.TestAllTypes_NestedEnum"` - MapStringForeignEnum map[string]ForeignEnum `protobuf:"bytes,74,rep,name=map_string_foreign_enum,json=mapStringForeignEnum" json:"map_string_foreign_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.ForeignEnum"` - // Types that are valid to be assigned to OneofField: - // *TestAllTypes_OneofUint32 - // *TestAllTypes_OneofNestedMessage - // *TestAllTypes_OneofString - // *TestAllTypes_OneofBytes - OneofField isTestAllTypes_OneofField `protobuf_oneof:"oneof_field"` - // Well-known types - OptionalBoolWrapper *wrappers.BoolValue `protobuf:"bytes,201,opt,name=optional_bool_wrapper,json=optionalBoolWrapper" json:"optional_bool_wrapper,omitempty"` - OptionalInt32Wrapper *wrappers.Int32Value `protobuf:"bytes,202,opt,name=optional_int32_wrapper,json=optionalInt32Wrapper" json:"optional_int32_wrapper,omitempty"` - OptionalInt64Wrapper *wrappers.Int64Value `protobuf:"bytes,203,opt,name=optional_int64_wrapper,json=optionalInt64Wrapper" json:"optional_int64_wrapper,omitempty"` - OptionalUint32Wrapper *wrappers.UInt32Value `protobuf:"bytes,204,opt,name=optional_uint32_wrapper,json=optionalUint32Wrapper" json:"optional_uint32_wrapper,omitempty"` - OptionalUint64Wrapper *wrappers.UInt64Value `protobuf:"bytes,205,opt,name=optional_uint64_wrapper,json=optionalUint64Wrapper" json:"optional_uint64_wrapper,omitempty"` - OptionalFloatWrapper *wrappers.FloatValue `protobuf:"bytes,206,opt,name=optional_float_wrapper,json=optionalFloatWrapper" json:"optional_float_wrapper,omitempty"` - OptionalDoubleWrapper *wrappers.DoubleValue `protobuf:"bytes,207,opt,name=optional_double_wrapper,json=optionalDoubleWrapper" json:"optional_double_wrapper,omitempty"` - OptionalStringWrapper *wrappers.StringValue `protobuf:"bytes,208,opt,name=optional_string_wrapper,json=optionalStringWrapper" json:"optional_string_wrapper,omitempty"` - OptionalBytesWrapper *wrappers.BytesValue `protobuf:"bytes,209,opt,name=optional_bytes_wrapper,json=optionalBytesWrapper" json:"optional_bytes_wrapper,omitempty"` - RepeatedBoolWrapper []*wrappers.BoolValue `protobuf:"bytes,211,rep,name=repeated_bool_wrapper,json=repeatedBoolWrapper" json:"repeated_bool_wrapper,omitempty"` - RepeatedInt32Wrapper []*wrappers.Int32Value `protobuf:"bytes,212,rep,name=repeated_int32_wrapper,json=repeatedInt32Wrapper" json:"repeated_int32_wrapper,omitempty"` - RepeatedInt64Wrapper []*wrappers.Int64Value `protobuf:"bytes,213,rep,name=repeated_int64_wrapper,json=repeatedInt64Wrapper" json:"repeated_int64_wrapper,omitempty"` - RepeatedUint32Wrapper []*wrappers.UInt32Value `protobuf:"bytes,214,rep,name=repeated_uint32_wrapper,json=repeatedUint32Wrapper" json:"repeated_uint32_wrapper,omitempty"` - RepeatedUint64Wrapper []*wrappers.UInt64Value `protobuf:"bytes,215,rep,name=repeated_uint64_wrapper,json=repeatedUint64Wrapper" json:"repeated_uint64_wrapper,omitempty"` - RepeatedFloatWrapper []*wrappers.FloatValue `protobuf:"bytes,216,rep,name=repeated_float_wrapper,json=repeatedFloatWrapper" json:"repeated_float_wrapper,omitempty"` - RepeatedDoubleWrapper []*wrappers.DoubleValue `protobuf:"bytes,217,rep,name=repeated_double_wrapper,json=repeatedDoubleWrapper" json:"repeated_double_wrapper,omitempty"` - RepeatedStringWrapper []*wrappers.StringValue `protobuf:"bytes,218,rep,name=repeated_string_wrapper,json=repeatedStringWrapper" json:"repeated_string_wrapper,omitempty"` - RepeatedBytesWrapper []*wrappers.BytesValue `protobuf:"bytes,219,rep,name=repeated_bytes_wrapper,json=repeatedBytesWrapper" json:"repeated_bytes_wrapper,omitempty"` - OptionalDuration *duration.Duration `protobuf:"bytes,301,opt,name=optional_duration,json=optionalDuration" json:"optional_duration,omitempty"` - OptionalTimestamp *timestamp.Timestamp `protobuf:"bytes,302,opt,name=optional_timestamp,json=optionalTimestamp" json:"optional_timestamp,omitempty"` - OptionalFieldMask *field_mask.FieldMask `protobuf:"bytes,303,opt,name=optional_field_mask,json=optionalFieldMask" json:"optional_field_mask,omitempty"` - OptionalStruct *_struct.Struct `protobuf:"bytes,304,opt,name=optional_struct,json=optionalStruct" json:"optional_struct,omitempty"` - OptionalAny *any.Any `protobuf:"bytes,305,opt,name=optional_any,json=optionalAny" json:"optional_any,omitempty"` - OptionalValue *_struct.Value `protobuf:"bytes,306,opt,name=optional_value,json=optionalValue" json:"optional_value,omitempty"` - RepeatedDuration []*duration.Duration `protobuf:"bytes,311,rep,name=repeated_duration,json=repeatedDuration" json:"repeated_duration,omitempty"` - RepeatedTimestamp []*timestamp.Timestamp `protobuf:"bytes,312,rep,name=repeated_timestamp,json=repeatedTimestamp" json:"repeated_timestamp,omitempty"` - RepeatedFieldmask []*field_mask.FieldMask `protobuf:"bytes,313,rep,name=repeated_fieldmask,json=repeatedFieldmask" json:"repeated_fieldmask,omitempty"` - RepeatedStruct []*_struct.Struct `protobuf:"bytes,324,rep,name=repeated_struct,json=repeatedStruct" json:"repeated_struct,omitempty"` - RepeatedAny []*any.Any `protobuf:"bytes,315,rep,name=repeated_any,json=repeatedAny" json:"repeated_any,omitempty"` - RepeatedValue []*_struct.Value `protobuf:"bytes,316,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` - // Test field-name-to-JSON-name convention. - Fieldname1 int32 `protobuf:"varint,401,opt,name=fieldname1" json:"fieldname1,omitempty"` - FieldName2 int32 `protobuf:"varint,402,opt,name=field_name2,json=fieldName2" json:"field_name2,omitempty"` - XFieldName3 int32 `protobuf:"varint,403,opt,name=_field_name3,json=FieldName3" json:"_field_name3,omitempty"` - Field_Name4_ int32 `protobuf:"varint,404,opt,name=field__name4_,json=fieldName4" json:"field__name4_,omitempty"` - Field0Name5 int32 `protobuf:"varint,405,opt,name=field0name5" json:"field0name5,omitempty"` - Field_0Name6 int32 `protobuf:"varint,406,opt,name=field_0_name6,json=field0Name6" json:"field_0_name6,omitempty"` - FieldName7 int32 `protobuf:"varint,407,opt,name=fieldName7" json:"fieldName7,omitempty"` - FieldName8 int32 `protobuf:"varint,408,opt,name=FieldName8" json:"FieldName8,omitempty"` - Field_Name9 int32 `protobuf:"varint,409,opt,name=field_Name9,json=fieldName9" json:"field_Name9,omitempty"` - Field_Name10 int32 `protobuf:"varint,410,opt,name=Field_Name10,json=FieldName10" json:"Field_Name10,omitempty"` - FIELD_NAME11 int32 `protobuf:"varint,411,opt,name=FIELD_NAME11,json=FIELDNAME11" json:"FIELD_NAME11,omitempty"` - FIELDName12 int32 `protobuf:"varint,412,opt,name=FIELD_name12,json=FIELDName12" json:"FIELD_name12,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestAllTypes) Reset() { *m = TestAllTypes{} } -func (m *TestAllTypes) String() string { return proto.CompactTextString(m) } -func (*TestAllTypes) ProtoMessage() {} -func (*TestAllTypes) Descriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{2} -} -func (m *TestAllTypes) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestAllTypes.Unmarshal(m, b) -} -func (m *TestAllTypes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestAllTypes.Marshal(b, m, deterministic) -} -func (dst *TestAllTypes) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestAllTypes.Merge(dst, src) -} -func (m *TestAllTypes) XXX_Size() int { - return xxx_messageInfo_TestAllTypes.Size(m) -} -func (m *TestAllTypes) XXX_DiscardUnknown() { - xxx_messageInfo_TestAllTypes.DiscardUnknown(m) -} - -var xxx_messageInfo_TestAllTypes proto.InternalMessageInfo - -type isTestAllTypes_OneofField interface { - isTestAllTypes_OneofField() -} - -type TestAllTypes_OneofUint32 struct { - OneofUint32 uint32 `protobuf:"varint,111,opt,name=oneof_uint32,json=oneofUint32,oneof"` -} -type TestAllTypes_OneofNestedMessage struct { - OneofNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,112,opt,name=oneof_nested_message,json=oneofNestedMessage,oneof"` -} -type TestAllTypes_OneofString struct { - OneofString string `protobuf:"bytes,113,opt,name=oneof_string,json=oneofString,oneof"` -} -type TestAllTypes_OneofBytes struct { - OneofBytes []byte `protobuf:"bytes,114,opt,name=oneof_bytes,json=oneofBytes,proto3,oneof"` -} - -func (*TestAllTypes_OneofUint32) isTestAllTypes_OneofField() {} -func (*TestAllTypes_OneofNestedMessage) isTestAllTypes_OneofField() {} -func (*TestAllTypes_OneofString) isTestAllTypes_OneofField() {} -func (*TestAllTypes_OneofBytes) isTestAllTypes_OneofField() {} - -func (m *TestAllTypes) GetOneofField() isTestAllTypes_OneofField { - if m != nil { - return m.OneofField - } - return nil -} - -func (m *TestAllTypes) GetOptionalInt32() int32 { - if m != nil { - return m.OptionalInt32 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalInt64() int64 { - if m != nil { - return m.OptionalInt64 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalUint32() uint32 { - if m != nil { - return m.OptionalUint32 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalUint64() uint64 { - if m != nil { - return m.OptionalUint64 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalSint32() int32 { - if m != nil { - return m.OptionalSint32 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalSint64() int64 { - if m != nil { - return m.OptionalSint64 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalFixed32() uint32 { - if m != nil { - return m.OptionalFixed32 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalFixed64() uint64 { - if m != nil { - return m.OptionalFixed64 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalSfixed32() int32 { - if m != nil { - return m.OptionalSfixed32 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalSfixed64() int64 { - if m != nil { - return m.OptionalSfixed64 - } - return 0 -} - -func (m *TestAllTypes) GetOptionalFloat() float32 { - if m != nil { - return m.OptionalFloat - } - return 0 -} - -func (m *TestAllTypes) GetOptionalDouble() float64 { - if m != nil { - return m.OptionalDouble - } - return 0 -} - -func (m *TestAllTypes) GetOptionalBool() bool { - if m != nil { - return m.OptionalBool - } - return false -} - -func (m *TestAllTypes) GetOptionalString() string { - if m != nil { - return m.OptionalString - } - return "" -} - -func (m *TestAllTypes) GetOptionalBytes() []byte { - if m != nil { - return m.OptionalBytes - } - return nil -} - -func (m *TestAllTypes) GetOptionalNestedMessage() *TestAllTypes_NestedMessage { - if m != nil { - return m.OptionalNestedMessage - } - return nil -} - -func (m *TestAllTypes) GetOptionalForeignMessage() *ForeignMessage { - if m != nil { - return m.OptionalForeignMessage - } - return nil -} - -func (m *TestAllTypes) GetOptionalNestedEnum() TestAllTypes_NestedEnum { - if m != nil { - return m.OptionalNestedEnum - } - return TestAllTypes_FOO -} - -func (m *TestAllTypes) GetOptionalForeignEnum() ForeignEnum { - if m != nil { - return m.OptionalForeignEnum - } - return ForeignEnum_FOREIGN_FOO -} - -func (m *TestAllTypes) GetOptionalStringPiece() string { - if m != nil { - return m.OptionalStringPiece - } - return "" -} - -func (m *TestAllTypes) GetOptionalCord() string { - if m != nil { - return m.OptionalCord - } - return "" -} - -func (m *TestAllTypes) GetRecursiveMessage() *TestAllTypes { - if m != nil { - return m.RecursiveMessage - } - return nil -} - -func (m *TestAllTypes) GetRepeatedInt32() []int32 { - if m != nil { - return m.RepeatedInt32 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedInt64() []int64 { - if m != nil { - return m.RepeatedInt64 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedUint32() []uint32 { - if m != nil { - return m.RepeatedUint32 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedUint64() []uint64 { - if m != nil { - return m.RepeatedUint64 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedSint32() []int32 { - if m != nil { - return m.RepeatedSint32 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedSint64() []int64 { - if m != nil { - return m.RepeatedSint64 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedFixed32() []uint32 { - if m != nil { - return m.RepeatedFixed32 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedFixed64() []uint64 { - if m != nil { - return m.RepeatedFixed64 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedSfixed32() []int32 { - if m != nil { - return m.RepeatedSfixed32 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedSfixed64() []int64 { - if m != nil { - return m.RepeatedSfixed64 - } - return nil -} - -func (m *TestAllTypes) GetRepeatedFloat() []float32 { - if m != nil { - return m.RepeatedFloat - } - return nil -} - -func (m *TestAllTypes) GetRepeatedDouble() []float64 { - if m != nil { - return m.RepeatedDouble - } - return nil -} - -func (m *TestAllTypes) GetRepeatedBool() []bool { - if m != nil { - return m.RepeatedBool - } - return nil -} - -func (m *TestAllTypes) GetRepeatedString() []string { - if m != nil { - return m.RepeatedString - } - return nil -} - -func (m *TestAllTypes) GetRepeatedBytes() [][]byte { - if m != nil { - return m.RepeatedBytes - } - return nil -} - -func (m *TestAllTypes) GetRepeatedNestedMessage() []*TestAllTypes_NestedMessage { - if m != nil { - return m.RepeatedNestedMessage - } - return nil -} - -func (m *TestAllTypes) GetRepeatedForeignMessage() []*ForeignMessage { - if m != nil { - return m.RepeatedForeignMessage - } - return nil -} - -func (m *TestAllTypes) GetRepeatedNestedEnum() []TestAllTypes_NestedEnum { - if m != nil { - return m.RepeatedNestedEnum - } - return nil -} - -func (m *TestAllTypes) GetRepeatedForeignEnum() []ForeignEnum { - if m != nil { - return m.RepeatedForeignEnum - } - return nil -} - -func (m *TestAllTypes) GetRepeatedStringPiece() []string { - if m != nil { - return m.RepeatedStringPiece - } - return nil -} - -func (m *TestAllTypes) GetRepeatedCord() []string { - if m != nil { - return m.RepeatedCord - } - return nil -} - -func (m *TestAllTypes) GetMapInt32Int32() map[int32]int32 { - if m != nil { - return m.MapInt32Int32 - } - return nil -} - -func (m *TestAllTypes) GetMapInt64Int64() map[int64]int64 { - if m != nil { - return m.MapInt64Int64 - } - return nil -} - -func (m *TestAllTypes) GetMapUint32Uint32() map[uint32]uint32 { - if m != nil { - return m.MapUint32Uint32 - } - return nil -} - -func (m *TestAllTypes) GetMapUint64Uint64() map[uint64]uint64 { - if m != nil { - return m.MapUint64Uint64 - } - return nil -} - -func (m *TestAllTypes) GetMapSint32Sint32() map[int32]int32 { - if m != nil { - return m.MapSint32Sint32 - } - return nil -} - -func (m *TestAllTypes) GetMapSint64Sint64() map[int64]int64 { - if m != nil { - return m.MapSint64Sint64 - } - return nil -} - -func (m *TestAllTypes) GetMapFixed32Fixed32() map[uint32]uint32 { - if m != nil { - return m.MapFixed32Fixed32 - } - return nil -} - -func (m *TestAllTypes) GetMapFixed64Fixed64() map[uint64]uint64 { - if m != nil { - return m.MapFixed64Fixed64 - } - return nil -} - -func (m *TestAllTypes) GetMapSfixed32Sfixed32() map[int32]int32 { - if m != nil { - return m.MapSfixed32Sfixed32 - } - return nil -} - -func (m *TestAllTypes) GetMapSfixed64Sfixed64() map[int64]int64 { - if m != nil { - return m.MapSfixed64Sfixed64 - } - return nil -} - -func (m *TestAllTypes) GetMapInt32Float() map[int32]float32 { - if m != nil { - return m.MapInt32Float - } - return nil -} - -func (m *TestAllTypes) GetMapInt32Double() map[int32]float64 { - if m != nil { - return m.MapInt32Double - } - return nil -} - -func (m *TestAllTypes) GetMapBoolBool() map[bool]bool { - if m != nil { - return m.MapBoolBool - } - return nil -} - -func (m *TestAllTypes) GetMapStringString() map[string]string { - if m != nil { - return m.MapStringString - } - return nil -} - -func (m *TestAllTypes) GetMapStringBytes() map[string][]byte { - if m != nil { - return m.MapStringBytes - } - return nil -} - -func (m *TestAllTypes) GetMapStringNestedMessage() map[string]*TestAllTypes_NestedMessage { - if m != nil { - return m.MapStringNestedMessage - } - return nil -} - -func (m *TestAllTypes) GetMapStringForeignMessage() map[string]*ForeignMessage { - if m != nil { - return m.MapStringForeignMessage - } - return nil -} - -func (m *TestAllTypes) GetMapStringNestedEnum() map[string]TestAllTypes_NestedEnum { - if m != nil { - return m.MapStringNestedEnum - } - return nil -} - -func (m *TestAllTypes) GetMapStringForeignEnum() map[string]ForeignEnum { - if m != nil { - return m.MapStringForeignEnum - } - return nil -} - -func (m *TestAllTypes) GetOneofUint32() uint32 { - if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint32); ok { - return x.OneofUint32 - } - return 0 -} - -func (m *TestAllTypes) GetOneofNestedMessage() *TestAllTypes_NestedMessage { - if x, ok := m.GetOneofField().(*TestAllTypes_OneofNestedMessage); ok { - return x.OneofNestedMessage - } - return nil -} - -func (m *TestAllTypes) GetOneofString() string { - if x, ok := m.GetOneofField().(*TestAllTypes_OneofString); ok { - return x.OneofString - } - return "" -} - -func (m *TestAllTypes) GetOneofBytes() []byte { - if x, ok := m.GetOneofField().(*TestAllTypes_OneofBytes); ok { - return x.OneofBytes - } - return nil -} - -func (m *TestAllTypes) GetOptionalBoolWrapper() *wrappers.BoolValue { - if m != nil { - return m.OptionalBoolWrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalInt32Wrapper() *wrappers.Int32Value { - if m != nil { - return m.OptionalInt32Wrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalInt64Wrapper() *wrappers.Int64Value { - if m != nil { - return m.OptionalInt64Wrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalUint32Wrapper() *wrappers.UInt32Value { - if m != nil { - return m.OptionalUint32Wrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalUint64Wrapper() *wrappers.UInt64Value { - if m != nil { - return m.OptionalUint64Wrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalFloatWrapper() *wrappers.FloatValue { - if m != nil { - return m.OptionalFloatWrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalDoubleWrapper() *wrappers.DoubleValue { - if m != nil { - return m.OptionalDoubleWrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalStringWrapper() *wrappers.StringValue { - if m != nil { - return m.OptionalStringWrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalBytesWrapper() *wrappers.BytesValue { - if m != nil { - return m.OptionalBytesWrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedBoolWrapper() []*wrappers.BoolValue { - if m != nil { - return m.RepeatedBoolWrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedInt32Wrapper() []*wrappers.Int32Value { - if m != nil { - return m.RepeatedInt32Wrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedInt64Wrapper() []*wrappers.Int64Value { - if m != nil { - return m.RepeatedInt64Wrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedUint32Wrapper() []*wrappers.UInt32Value { - if m != nil { - return m.RepeatedUint32Wrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedUint64Wrapper() []*wrappers.UInt64Value { - if m != nil { - return m.RepeatedUint64Wrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedFloatWrapper() []*wrappers.FloatValue { - if m != nil { - return m.RepeatedFloatWrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedDoubleWrapper() []*wrappers.DoubleValue { - if m != nil { - return m.RepeatedDoubleWrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedStringWrapper() []*wrappers.StringValue { - if m != nil { - return m.RepeatedStringWrapper - } - return nil -} - -func (m *TestAllTypes) GetRepeatedBytesWrapper() []*wrappers.BytesValue { - if m != nil { - return m.RepeatedBytesWrapper - } - return nil -} - -func (m *TestAllTypes) GetOptionalDuration() *duration.Duration { - if m != nil { - return m.OptionalDuration - } - return nil -} - -func (m *TestAllTypes) GetOptionalTimestamp() *timestamp.Timestamp { - if m != nil { - return m.OptionalTimestamp - } - return nil -} - -func (m *TestAllTypes) GetOptionalFieldMask() *field_mask.FieldMask { - if m != nil { - return m.OptionalFieldMask - } - return nil -} - -func (m *TestAllTypes) GetOptionalStruct() *_struct.Struct { - if m != nil { - return m.OptionalStruct - } - return nil -} - -func (m *TestAllTypes) GetOptionalAny() *any.Any { - if m != nil { - return m.OptionalAny - } - return nil -} - -func (m *TestAllTypes) GetOptionalValue() *_struct.Value { - if m != nil { - return m.OptionalValue - } - return nil -} - -func (m *TestAllTypes) GetRepeatedDuration() []*duration.Duration { - if m != nil { - return m.RepeatedDuration - } - return nil -} - -func (m *TestAllTypes) GetRepeatedTimestamp() []*timestamp.Timestamp { - if m != nil { - return m.RepeatedTimestamp - } - return nil -} - -func (m *TestAllTypes) GetRepeatedFieldmask() []*field_mask.FieldMask { - if m != nil { - return m.RepeatedFieldmask - } - return nil -} - -func (m *TestAllTypes) GetRepeatedStruct() []*_struct.Struct { - if m != nil { - return m.RepeatedStruct - } - return nil -} - -func (m *TestAllTypes) GetRepeatedAny() []*any.Any { - if m != nil { - return m.RepeatedAny - } - return nil -} - -func (m *TestAllTypes) GetRepeatedValue() []*_struct.Value { - if m != nil { - return m.RepeatedValue - } - return nil -} - -func (m *TestAllTypes) GetFieldname1() int32 { - if m != nil { - return m.Fieldname1 - } - return 0 -} - -func (m *TestAllTypes) GetFieldName2() int32 { - if m != nil { - return m.FieldName2 - } - return 0 -} - -func (m *TestAllTypes) GetXFieldName3() int32 { - if m != nil { - return m.XFieldName3 - } - return 0 -} - -func (m *TestAllTypes) GetField_Name4_() int32 { - if m != nil { - return m.Field_Name4_ - } - return 0 -} - -func (m *TestAllTypes) GetField0Name5() int32 { - if m != nil { - return m.Field0Name5 - } - return 0 -} - -func (m *TestAllTypes) GetField_0Name6() int32 { - if m != nil { - return m.Field_0Name6 - } - return 0 -} - -func (m *TestAllTypes) GetFieldName7() int32 { - if m != nil { - return m.FieldName7 - } - return 0 -} - -func (m *TestAllTypes) GetFieldName8() int32 { - if m != nil { - return m.FieldName8 - } - return 0 -} - -func (m *TestAllTypes) GetField_Name9() int32 { - if m != nil { - return m.Field_Name9 - } - return 0 -} - -func (m *TestAllTypes) GetField_Name10() int32 { - if m != nil { - return m.Field_Name10 - } - return 0 -} - -func (m *TestAllTypes) GetFIELD_NAME11() int32 { - if m != nil { - return m.FIELD_NAME11 - } - return 0 -} - -func (m *TestAllTypes) GetFIELDName12() int32 { - if m != nil { - return m.FIELDName12 - } - return 0 -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*TestAllTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _TestAllTypes_OneofMarshaler, _TestAllTypes_OneofUnmarshaler, _TestAllTypes_OneofSizer, []interface{}{ - (*TestAllTypes_OneofUint32)(nil), - (*TestAllTypes_OneofNestedMessage)(nil), - (*TestAllTypes_OneofString)(nil), - (*TestAllTypes_OneofBytes)(nil), - } -} - -func _TestAllTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*TestAllTypes) - // oneof_field - switch x := m.OneofField.(type) { - case *TestAllTypes_OneofUint32: - b.EncodeVarint(111<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.OneofUint32)) - case *TestAllTypes_OneofNestedMessage: - b.EncodeVarint(112<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.OneofNestedMessage); err != nil { - return err - } - case *TestAllTypes_OneofString: - b.EncodeVarint(113<<3 | proto.WireBytes) - b.EncodeStringBytes(x.OneofString) - case *TestAllTypes_OneofBytes: - b.EncodeVarint(114<<3 | proto.WireBytes) - b.EncodeRawBytes(x.OneofBytes) - case nil: - default: - return fmt.Errorf("TestAllTypes.OneofField has unexpected type %T", x) - } - return nil -} - -func _TestAllTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*TestAllTypes) - switch tag { - case 111: // oneof_field.oneof_uint32 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.OneofField = &TestAllTypes_OneofUint32{uint32(x)} - return true, err - case 112: // oneof_field.oneof_nested_message - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(TestAllTypes_NestedMessage) - err := b.DecodeMessage(msg) - m.OneofField = &TestAllTypes_OneofNestedMessage{msg} - return true, err - case 113: // oneof_field.oneof_string - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.OneofField = &TestAllTypes_OneofString{x} - return true, err - case 114: // oneof_field.oneof_bytes - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.OneofField = &TestAllTypes_OneofBytes{x} - return true, err - default: - return false, nil - } -} - -func _TestAllTypes_OneofSizer(msg proto.Message) (n int) { - m := msg.(*TestAllTypes) - // oneof_field - switch x := m.OneofField.(type) { - case *TestAllTypes_OneofUint32: - n += 2 // tag and wire - n += proto.SizeVarint(uint64(x.OneofUint32)) - case *TestAllTypes_OneofNestedMessage: - s := proto.Size(x.OneofNestedMessage) - n += 2 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *TestAllTypes_OneofString: - n += 2 // tag and wire - n += proto.SizeVarint(uint64(len(x.OneofString))) - n += len(x.OneofString) - case *TestAllTypes_OneofBytes: - n += 2 // tag and wire - n += proto.SizeVarint(uint64(len(x.OneofBytes))) - n += len(x.OneofBytes) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type TestAllTypes_NestedMessage struct { - A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"` - Corecursive *TestAllTypes `protobuf:"bytes,2,opt,name=corecursive" json:"corecursive,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestAllTypes_NestedMessage) Reset() { *m = TestAllTypes_NestedMessage{} } -func (m *TestAllTypes_NestedMessage) String() string { return proto.CompactTextString(m) } -func (*TestAllTypes_NestedMessage) ProtoMessage() {} -func (*TestAllTypes_NestedMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{2, 0} -} -func (m *TestAllTypes_NestedMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestAllTypes_NestedMessage.Unmarshal(m, b) -} -func (m *TestAllTypes_NestedMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestAllTypes_NestedMessage.Marshal(b, m, deterministic) -} -func (dst *TestAllTypes_NestedMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestAllTypes_NestedMessage.Merge(dst, src) -} -func (m *TestAllTypes_NestedMessage) XXX_Size() int { - return xxx_messageInfo_TestAllTypes_NestedMessage.Size(m) -} -func (m *TestAllTypes_NestedMessage) XXX_DiscardUnknown() { - xxx_messageInfo_TestAllTypes_NestedMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_TestAllTypes_NestedMessage proto.InternalMessageInfo - -func (m *TestAllTypes_NestedMessage) GetA() int32 { - if m != nil { - return m.A - } - return 0 -} - -func (m *TestAllTypes_NestedMessage) GetCorecursive() *TestAllTypes { - if m != nil { - return m.Corecursive - } - return nil -} - -type ForeignMessage struct { - C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ForeignMessage) Reset() { *m = ForeignMessage{} } -func (m *ForeignMessage) String() string { return proto.CompactTextString(m) } -func (*ForeignMessage) ProtoMessage() {} -func (*ForeignMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_conformance_48ac832451f5d6c3, []int{3} -} -func (m *ForeignMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ForeignMessage.Unmarshal(m, b) -} -func (m *ForeignMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ForeignMessage.Marshal(b, m, deterministic) -} -func (dst *ForeignMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_ForeignMessage.Merge(dst, src) -} -func (m *ForeignMessage) XXX_Size() int { - return xxx_messageInfo_ForeignMessage.Size(m) -} -func (m *ForeignMessage) XXX_DiscardUnknown() { - xxx_messageInfo_ForeignMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_ForeignMessage proto.InternalMessageInfo - -func (m *ForeignMessage) GetC() int32 { - if m != nil { - return m.C - } - return 0 -} - -func init() { - proto.RegisterType((*ConformanceRequest)(nil), "conformance.ConformanceRequest") - proto.RegisterType((*ConformanceResponse)(nil), "conformance.ConformanceResponse") - proto.RegisterType((*TestAllTypes)(nil), "conformance.TestAllTypes") - proto.RegisterMapType((map[bool]bool)(nil), "conformance.TestAllTypes.MapBoolBoolEntry") - proto.RegisterMapType((map[uint32]uint32)(nil), "conformance.TestAllTypes.MapFixed32Fixed32Entry") - proto.RegisterMapType((map[uint64]uint64)(nil), "conformance.TestAllTypes.MapFixed64Fixed64Entry") - proto.RegisterMapType((map[int32]float64)(nil), "conformance.TestAllTypes.MapInt32DoubleEntry") - proto.RegisterMapType((map[int32]float32)(nil), "conformance.TestAllTypes.MapInt32FloatEntry") - proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapInt32Int32Entry") - proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapInt64Int64Entry") - proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapSfixed32Sfixed32Entry") - proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapSfixed64Sfixed64Entry") - proto.RegisterMapType((map[int32]int32)(nil), "conformance.TestAllTypes.MapSint32Sint32Entry") - proto.RegisterMapType((map[int64]int64)(nil), "conformance.TestAllTypes.MapSint64Sint64Entry") - proto.RegisterMapType((map[string][]byte)(nil), "conformance.TestAllTypes.MapStringBytesEntry") - proto.RegisterMapType((map[string]ForeignEnum)(nil), "conformance.TestAllTypes.MapStringForeignEnumEntry") - proto.RegisterMapType((map[string]*ForeignMessage)(nil), "conformance.TestAllTypes.MapStringForeignMessageEntry") - proto.RegisterMapType((map[string]TestAllTypes_NestedEnum)(nil), "conformance.TestAllTypes.MapStringNestedEnumEntry") - proto.RegisterMapType((map[string]*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.MapStringNestedMessageEntry") - proto.RegisterMapType((map[string]string)(nil), "conformance.TestAllTypes.MapStringStringEntry") - proto.RegisterMapType((map[uint32]uint32)(nil), "conformance.TestAllTypes.MapUint32Uint32Entry") - proto.RegisterMapType((map[uint64]uint64)(nil), "conformance.TestAllTypes.MapUint64Uint64Entry") - proto.RegisterType((*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.NestedMessage") - proto.RegisterType((*ForeignMessage)(nil), "conformance.ForeignMessage") - proto.RegisterEnum("conformance.WireFormat", WireFormat_name, WireFormat_value) - proto.RegisterEnum("conformance.ForeignEnum", ForeignEnum_name, ForeignEnum_value) - proto.RegisterEnum("conformance.TestAllTypes_NestedEnum", TestAllTypes_NestedEnum_name, TestAllTypes_NestedEnum_value) -} - -func init() { proto.RegisterFile("conformance.proto", fileDescriptor_conformance_48ac832451f5d6c3) } - -var fileDescriptor_conformance_48ac832451f5d6c3 = []byte{ - // 2600 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0x5b, 0x73, 0x13, 0xc9, - 0x15, 0xf6, 0x68, 0xc0, 0x36, 0x2d, 0xd9, 0x96, 0xdb, 0xb7, 0xc6, 0x50, 0xcb, 0x60, 0x96, 0x20, - 0x60, 0xd7, 0xeb, 0xcb, 0x30, 0x5c, 0x36, 0x4b, 0xb0, 0xc0, 0x02, 0x93, 0xc5, 0xa2, 0xc6, 0x78, - 0xa9, 0x22, 0x0f, 0xca, 0x20, 0x8f, 0x5d, 0x5a, 0x24, 0x8d, 0x76, 0x66, 0xb4, 0x89, 0xf3, 0x98, - 0x7f, 0x90, 0xfb, 0xf5, 0x2f, 0xe4, 0x5a, 0x95, 0x4a, 0x52, 0xc9, 0x53, 0x2a, 0x2f, 0xb9, 0x27, - 0x95, 0x7b, 0xf2, 0x63, 0x92, 0xea, 0xeb, 0x74, 0xb7, 0x7a, 0x64, 0xb1, 0x55, 0x2b, 0x5b, 0xa7, - 0xbf, 0xfe, 0xce, 0xe9, 0xd3, 0x67, 0xbe, 0x76, 0x9f, 0x01, 0xcc, 0x36, 0xa3, 0xee, 0x61, 0x14, - 0x77, 0x82, 0x6e, 0x33, 0x5c, 0xed, 0xc5, 0x51, 0x1a, 0xc1, 0xa2, 0x64, 0x5a, 0x3e, 0x7b, 0x14, - 0x45, 0x47, 0xed, 0xf0, 0x1d, 0x32, 0xf4, 0xb2, 0x7f, 0xf8, 0x4e, 0xd0, 0x3d, 0xa6, 0xb8, 0xe5, - 0x37, 0xf4, 0xa1, 0x83, 0x7e, 0x1c, 0xa4, 0xad, 0xa8, 0xcb, 0xc6, 0x1d, 0x7d, 0xfc, 0xb0, 0x15, - 0xb6, 0x0f, 0x1a, 0x9d, 0x20, 0x79, 0xc5, 0x10, 0xe7, 0x75, 0x44, 0x92, 0xc6, 0xfd, 0x66, 0xca, - 0x46, 0x2f, 0xe8, 0xa3, 0x69, 0xab, 0x13, 0x26, 0x69, 0xd0, 0xe9, 0xe5, 0x05, 0xf0, 0xb9, 0x38, - 0xe8, 0xf5, 0xc2, 0x38, 0xa1, 0xe3, 0x2b, 0xbf, 0xb2, 0x00, 0xbc, 0x9f, 0xad, 0xc5, 0x0f, 0x3f, - 0xea, 0x87, 0x49, 0x0a, 0xaf, 0x83, 0x32, 0x9f, 0xd1, 0xe8, 0x05, 0xc7, 0xed, 0x28, 0x38, 0x40, - 0x96, 0x63, 0x55, 0x4a, 0x8f, 0xc6, 0xfc, 0x19, 0x3e, 0xf2, 0x94, 0x0e, 0xc0, 0x4b, 0xa0, 0xf4, - 0x61, 0x12, 0x75, 0x05, 0xb0, 0xe0, 0x58, 0x95, 0x33, 0x8f, 0xc6, 0xfc, 0x22, 0xb6, 0x72, 0x50, - 0x1d, 0x2c, 0xc5, 0x94, 0x3c, 0x3c, 0x68, 0x44, 0xfd, 0xb4, 0xd7, 0x4f, 0x1b, 0xc4, 0x6b, 0x8a, - 0x6c, 0xc7, 0xaa, 0x4c, 0x6f, 0x2c, 0xad, 0xca, 0x69, 0x7e, 0xde, 0x8a, 0xc3, 0x1a, 0x19, 0xf6, - 0x17, 0xc4, 0xbc, 0x3a, 0x99, 0x46, 0xcd, 0xd5, 0x33, 0x60, 0x82, 0x39, 0x5c, 0xf9, 0x62, 0x01, - 0xcc, 0x29, 0x8b, 0x48, 0x7a, 0x51, 0x37, 0x09, 0xe1, 0x45, 0x50, 0xec, 0x05, 0x71, 0x12, 0x36, - 0xc2, 0x38, 0x8e, 0x62, 0xb2, 0x00, 0x1c, 0x17, 0x20, 0xc6, 0x6d, 0x6c, 0x83, 0x57, 0xc1, 0x4c, - 0x12, 0xc6, 0xad, 0xa0, 0xdd, 0xfa, 0x02, 0x87, 0x8d, 0x33, 0xd8, 0xb4, 0x18, 0xa0, 0xd0, 0xcb, - 0x60, 0x2a, 0xee, 0x77, 0x71, 0x82, 0x19, 0x90, 0xaf, 0xb3, 0xc4, 0xcc, 0x14, 0x66, 0x4a, 0x9d, - 0x3d, 0x6a, 0xea, 0x4e, 0x99, 0x52, 0xb7, 0x0c, 0x26, 0x92, 0x57, 0xad, 0x5e, 0x2f, 0x3c, 0x40, - 0xa7, 0xd9, 0x38, 0x37, 0x54, 0x27, 0xc1, 0x78, 0x1c, 0x26, 0xfd, 0x76, 0xba, 0xf2, 0x93, 0xfb, - 0xa0, 0xf4, 0x2c, 0x4c, 0xd2, 0xad, 0x76, 0xfb, 0xd9, 0x71, 0x2f, 0x4c, 0xe0, 0x65, 0x30, 0x1d, - 0xf5, 0x70, 0xad, 0x05, 0xed, 0x46, 0xab, 0x9b, 0x6e, 0x6e, 0x90, 0x04, 0x9c, 0xf6, 0xa7, 0xb8, - 0x75, 0x07, 0x1b, 0x75, 0x98, 0xe7, 0x92, 0x75, 0xd9, 0x0a, 0xcc, 0x73, 0xe1, 0x15, 0x30, 0x23, - 0x60, 0x7d, 0x4a, 0x87, 0x57, 0x35, 0xe5, 0x8b, 0xd9, 0xfb, 0xc4, 0x3a, 0x00, 0xf4, 0x5c, 0xb2, - 0xaa, 0x53, 0x2a, 0x50, 0x63, 0x4c, 0x28, 0x23, 0x5e, 0xde, 0x6c, 0x06, 0xdc, 0x1b, 0x64, 0x4c, - 0x28, 0x23, 0xde, 0x23, 0xa8, 0x02, 0x3d, 0x17, 0x5e, 0x05, 0x65, 0x01, 0x3c, 0x6c, 0x7d, 0x3e, - 0x3c, 0xd8, 0xdc, 0x40, 0x13, 0x8e, 0x55, 0x99, 0xf0, 0x05, 0x41, 0x8d, 0x9a, 0x07, 0xa1, 0x9e, - 0x8b, 0x26, 0x1d, 0xab, 0x32, 0xae, 0x41, 0x3d, 0x17, 0x5e, 0x07, 0xb3, 0x99, 0x7b, 0x4e, 0x7b, - 0xc6, 0xb1, 0x2a, 0x33, 0xbe, 0xe0, 0xd8, 0x63, 0x76, 0x03, 0xd8, 0x73, 0x11, 0x70, 0xac, 0x4a, - 0x59, 0x07, 0x7b, 0xae, 0x92, 0xfa, 0xc3, 0x76, 0x14, 0xa4, 0xa8, 0xe8, 0x58, 0x95, 0x42, 0x96, - 0xfa, 0x1a, 0x36, 0x2a, 0xeb, 0x3f, 0x88, 0xfa, 0x2f, 0xdb, 0x21, 0x2a, 0x39, 0x56, 0xc5, 0xca, - 0xd6, 0xff, 0x80, 0x58, 0xe1, 0x25, 0x20, 0x66, 0x36, 0x5e, 0x46, 0x51, 0x1b, 0x4d, 0x39, 0x56, - 0x65, 0xd2, 0x2f, 0x71, 0x63, 0x35, 0x8a, 0xda, 0x6a, 0x36, 0xd3, 0xb8, 0xd5, 0x3d, 0x42, 0xd3, - 0xb8, 0xaa, 0xa4, 0x6c, 0x12, 0xab, 0x12, 0xdd, 0xcb, 0xe3, 0x34, 0x4c, 0xd0, 0x0c, 0x2e, 0xe3, - 0x2c, 0xba, 0x2a, 0x36, 0xc2, 0x06, 0x58, 0x12, 0xb0, 0x2e, 0x7d, 0xbc, 0x3b, 0x61, 0x92, 0x04, - 0x47, 0x21, 0x82, 0x8e, 0x55, 0x29, 0x6e, 0x5c, 0x51, 0x1e, 0x6c, 0xb9, 0x44, 0x57, 0x77, 0x09, - 0xfe, 0x09, 0x85, 0xfb, 0x0b, 0x9c, 0x47, 0x31, 0xc3, 0x7d, 0x80, 0xb2, 0x2c, 0x45, 0x71, 0xd8, - 0x3a, 0xea, 0x0a, 0x0f, 0x73, 0xc4, 0xc3, 0x39, 0xc5, 0x43, 0x8d, 0x62, 0x38, 0xeb, 0xa2, 0x48, - 0xa6, 0x62, 0x87, 0x1f, 0x80, 0x79, 0x3d, 0xee, 0xb0, 0xdb, 0xef, 0xa0, 0x05, 0xa2, 0x46, 0x6f, - 0x9e, 0x14, 0xf4, 0x76, 0xb7, 0xdf, 0xf1, 0xa1, 0x1a, 0x31, 0xb6, 0xc1, 0xf7, 0xc1, 0xc2, 0x40, - 0xb8, 0x84, 0x78, 0x91, 0x10, 0x23, 0x53, 0xac, 0x84, 0x6c, 0x4e, 0x0b, 0x94, 0xb0, 0x79, 0x12, - 0x1b, 0xdd, 0xad, 0x46, 0xaf, 0x15, 0x36, 0x43, 0x84, 0xf0, 0x9e, 0x55, 0x0b, 0x93, 0x85, 0x6c, - 0x1e, 0xdd, 0xb7, 0xa7, 0x78, 0x18, 0x5e, 0x91, 0x4a, 0xa1, 0x19, 0xc5, 0x07, 0xe8, 0x2c, 0xc3, - 0x5b, 0x59, 0x39, 0xdc, 0x8f, 0xe2, 0x03, 0x58, 0x03, 0xb3, 0x71, 0xd8, 0xec, 0xc7, 0x49, 0xeb, - 0xe3, 0x50, 0xa4, 0xf5, 0x1c, 0x49, 0xeb, 0xd9, 0xdc, 0x1c, 0xf8, 0x65, 0x31, 0x87, 0xa7, 0xf3, - 0x32, 0x98, 0x8e, 0xc3, 0x5e, 0x18, 0xe0, 0x3c, 0xd2, 0x87, 0xf9, 0x82, 0x63, 0x63, 0xb5, 0xe1, - 0x56, 0xa1, 0x36, 0x32, 0xcc, 0x73, 0x91, 0xe3, 0xd8, 0x58, 0x6d, 0x24, 0x18, 0xd5, 0x06, 0x01, - 0x63, 0x6a, 0x73, 0xd1, 0xb1, 0xb1, 0xda, 0x70, 0x73, 0xa6, 0x36, 0x0a, 0xd0, 0x73, 0xd1, 0x8a, - 0x63, 0x63, 0xb5, 0x91, 0x81, 0x1a, 0x23, 0x53, 0x9b, 0x4b, 0x8e, 0x8d, 0xd5, 0x86, 0x9b, 0xf7, - 0x06, 0x19, 0x99, 0xda, 0xbc, 0xe9, 0xd8, 0x58, 0x6d, 0x64, 0x20, 0x55, 0x1b, 0x01, 0xe4, 0xb2, - 0x70, 0xd9, 0xb1, 0xb1, 0xda, 0x70, 0xbb, 0xa4, 0x36, 0x2a, 0xd4, 0x73, 0xd1, 0x27, 0x1c, 0x1b, - 0xab, 0x8d, 0x02, 0xa5, 0x6a, 0x93, 0xb9, 0xe7, 0xb4, 0x57, 0x1c, 0x1b, 0xab, 0x8d, 0x08, 0x40, - 0x52, 0x1b, 0x0d, 0xec, 0xb9, 0xa8, 0xe2, 0xd8, 0x58, 0x6d, 0x54, 0x30, 0x55, 0x9b, 0x2c, 0x08, - 0xa2, 0x36, 0x57, 0x1d, 0x1b, 0xab, 0x8d, 0x08, 0x81, 0xab, 0x8d, 0x80, 0x31, 0xb5, 0xb9, 0xe6, - 0xd8, 0x58, 0x6d, 0xb8, 0x39, 0x53, 0x1b, 0x01, 0x24, 0x6a, 0x73, 0xdd, 0xb1, 0xb1, 0xda, 0x70, - 0x23, 0x57, 0x9b, 0x2c, 0x42, 0xaa, 0x36, 0x6f, 0x39, 0x36, 0x56, 0x1b, 0x11, 0x9f, 0x50, 0x9b, - 0x8c, 0x8d, 0xa8, 0xcd, 0xdb, 0x8e, 0x8d, 0xd5, 0x46, 0xd0, 0x71, 0xb5, 0x11, 0x30, 0x4d, 0x6d, - 0xd6, 0x1c, 0xfb, 0xb5, 0xd4, 0x86, 0xf3, 0x0c, 0xa8, 0x4d, 0x96, 0x25, 0x4d, 0x6d, 0xd6, 0x89, - 0x87, 0xe1, 0x6a, 0x23, 0x92, 0x39, 0xa0, 0x36, 0x7a, 0xdc, 0x44, 0x14, 0x36, 0x1d, 0x7b, 0x74, - 0xb5, 0x51, 0x23, 0xe6, 0x6a, 0x33, 0x10, 0x2e, 0x21, 0x76, 0x09, 0xf1, 0x10, 0xb5, 0xd1, 0x02, - 0xe5, 0x6a, 0xa3, 0xed, 0x16, 0x53, 0x1b, 0x0f, 0xef, 0x19, 0x55, 0x1b, 0x75, 0xdf, 0x84, 0xda, - 0x88, 0x79, 0x44, 0x6d, 0x6e, 0x32, 0xbc, 0x95, 0x95, 0x03, 0x51, 0x9b, 0x67, 0x60, 0xa6, 0x13, - 0xf4, 0xa8, 0x40, 0x30, 0x99, 0xb8, 0x45, 0x92, 0xfa, 0x56, 0x7e, 0x06, 0x9e, 0x04, 0x3d, 0xa2, - 0x1d, 0xe4, 0x63, 0xbb, 0x9b, 0xc6, 0xc7, 0xfe, 0x54, 0x47, 0xb6, 0x49, 0xac, 0x9e, 0xcb, 0x54, - 0xe5, 0xf6, 0x68, 0xac, 0x9e, 0x4b, 0x3e, 0x14, 0x56, 0x66, 0x83, 0x2f, 0xc0, 0x2c, 0x66, 0xa5, - 0xf2, 0xc3, 0x55, 0xe8, 0x0e, 0xe1, 0x5d, 0x1d, 0xca, 0x4b, 0xa5, 0x89, 0x7e, 0x52, 0x66, 0x1c, - 0x9e, 0x6c, 0x95, 0xb9, 0x3d, 0x97, 0x0b, 0xd7, 0xbb, 0x23, 0x72, 0x7b, 0x2e, 0xfd, 0x54, 0xb9, - 0xb9, 0x95, 0x73, 0x53, 0x91, 0xe3, 0x5a, 0xf7, 0xc9, 0x11, 0xb8, 0xa9, 0x00, 0xee, 0x69, 0x71, - 0xcb, 0x56, 0x99, 0xdb, 0x73, 0xb9, 0x3c, 0xbe, 0x37, 0x22, 0xb7, 0xe7, 0xee, 0x69, 0x71, 0xcb, - 0x56, 0xf8, 0x59, 0x30, 0x87, 0xb9, 0x99, 0xb6, 0x09, 0x49, 0xbd, 0x4b, 0xd8, 0xd7, 0x86, 0xb2, - 0x33, 0x9d, 0x65, 0x3f, 0x28, 0x3f, 0x0e, 0x54, 0xb5, 0x2b, 0x1e, 0x3c, 0x57, 0x28, 0xf1, 0xa7, - 0x46, 0xf5, 0xe0, 0xb9, 0xec, 0x87, 0xe6, 0x41, 0xd8, 0xe1, 0x21, 0x58, 0x20, 0xf9, 0xe1, 0x8b, - 0x10, 0x0a, 0x7e, 0x8f, 0xf8, 0xd8, 0x18, 0x9e, 0x23, 0x06, 0xe6, 0x3f, 0xa9, 0x17, 0x1c, 0xb2, - 0x3e, 0xa2, 0xfa, 0xc1, 0x3b, 0xc1, 0xd7, 0xb2, 0x35, 0xb2, 0x1f, 0xcf, 0xe5, 0x3f, 0x75, 0x3f, - 0xd9, 0x88, 0xfa, 0xbc, 0xd2, 0x43, 0xa3, 0x3a, 0xea, 0xf3, 0x4a, 0x8e, 0x13, 0xed, 0x79, 0xa5, - 0x47, 0xcc, 0x73, 0x50, 0xce, 0x58, 0xd9, 0x19, 0x73, 0x9f, 0xd0, 0xbe, 0x7d, 0x32, 0x2d, 0x3d, - 0x7d, 0x28, 0xef, 0x74, 0x47, 0x31, 0xc2, 0x5d, 0x80, 0x3d, 0x91, 0xd3, 0x88, 0x1e, 0x49, 0x0f, - 0x08, 0xeb, 0xb5, 0xa1, 0xac, 0xf8, 0x9c, 0xc2, 0xff, 0x53, 0xca, 0x62, 0x27, 0xb3, 0x88, 0x72, - 0xa7, 0x52, 0xc8, 0xce, 0xaf, 0xed, 0x51, 0xca, 0x9d, 0x40, 0xe9, 0xa7, 0x54, 0xee, 0x92, 0x95, - 0x27, 0x81, 0x71, 0xd3, 0x23, 0xaf, 0x36, 0x42, 0x12, 0xe8, 0x74, 0x72, 0x1a, 0x66, 0x49, 0x90, - 0x8c, 0xb0, 0x07, 0xce, 0x4a, 0xc4, 0xda, 0x21, 0xf9, 0x90, 0x78, 0xb8, 0x31, 0x82, 0x07, 0xe5, - 0x58, 0xa4, 0x9e, 0x16, 0x3b, 0xc6, 0x41, 0x98, 0x80, 0x65, 0xc9, 0xa3, 0x7e, 0x6a, 0x3e, 0x22, - 0x2e, 0xbd, 0x11, 0x5c, 0xaa, 0x67, 0x26, 0xf5, 0xb9, 0xd4, 0x31, 0x8f, 0xc2, 0x23, 0xb0, 0x38, - 0xb8, 0x4c, 0x72, 0xf4, 0xed, 0x8c, 0xf2, 0x0c, 0x48, 0xcb, 0xc0, 0x47, 0x9f, 0xf4, 0x0c, 0x68, - 0x23, 0xf0, 0x43, 0xb0, 0x64, 0x58, 0x1d, 0xf1, 0xf4, 0x98, 0x78, 0xda, 0x1c, 0x7d, 0x69, 0x99, - 0xab, 0xf9, 0x8e, 0x61, 0x08, 0x5e, 0x02, 0xa5, 0xa8, 0x1b, 0x46, 0x87, 0xfc, 0xb8, 0x89, 0xf0, - 0x15, 0xfb, 0xd1, 0x98, 0x5f, 0x24, 0x56, 0x76, 0x78, 0x7c, 0x06, 0xcc, 0x53, 0x90, 0xb6, 0xb7, - 0xbd, 0xd7, 0xba, 0x6e, 0x3d, 0x1a, 0xf3, 0x21, 0xa1, 0x51, 0xf7, 0x52, 0x44, 0xc0, 0xaa, 0xfd, - 0x23, 0xde, 0x91, 0x20, 0x56, 0x56, 0xbb, 0x17, 0x01, 0xfd, 0xca, 0xca, 0x36, 0x66, 0xed, 0x0d, - 0x40, 0x8c, 0xb4, 0x0a, 0xeb, 0xd2, 0xc5, 0x85, 0x3c, 0x8f, 0xac, 0xf1, 0x84, 0x7e, 0x63, 0x91, - 0x30, 0x97, 0x57, 0x69, 0x67, 0x6a, 0x95, 0xb7, 0x44, 0x56, 0xf1, 0x13, 0xf7, 0x41, 0xd0, 0xee, - 0x87, 0xd9, 0x8d, 0x06, 0x9b, 0x9e, 0xd3, 0x79, 0xd0, 0x07, 0x8b, 0x6a, 0x3b, 0x43, 0x30, 0xfe, - 0xd6, 0x62, 0xb7, 0x40, 0x9d, 0x91, 0x48, 0x03, 0xa5, 0x9c, 0x57, 0x9a, 0x1e, 0x39, 0x9c, 0x9e, - 0x2b, 0x38, 0x7f, 0x37, 0x84, 0xd3, 0x73, 0x07, 0x39, 0x3d, 0x97, 0x73, 0xee, 0x4b, 0xf7, 0xe1, - 0xbe, 0x1a, 0xe8, 0xef, 0x29, 0xe9, 0xf9, 0x01, 0xd2, 0x7d, 0x29, 0xd2, 0x05, 0xb5, 0x9f, 0x92, - 0x47, 0x2b, 0xc5, 0xfa, 0x87, 0x61, 0xb4, 0x3c, 0xd8, 0x05, 0xb5, 0xfb, 0x62, 0xca, 0x00, 0xd1, - 0x77, 0xc1, 0xfa, 0xc7, 0xbc, 0x0c, 0x10, 0x0d, 0xd7, 0x32, 0x40, 0x6c, 0xa6, 0x50, 0xa9, 0xba, - 0x0b, 0xd2, 0x3f, 0xe5, 0x85, 0x4a, 0x05, 0x5c, 0x0b, 0x95, 0x1a, 0x4d, 0xb4, 0xec, 0x61, 0xe4, - 0xb4, 0x7f, 0xce, 0xa3, 0xa5, 0xf5, 0xaa, 0xd1, 0x52, 0xa3, 0x29, 0x03, 0xa4, 0x9c, 0x05, 0xeb, - 0x5f, 0xf2, 0x32, 0x40, 0x2a, 0x5c, 0xcb, 0x00, 0xb1, 0x71, 0xce, 0xba, 0xf4, 0x77, 0xb4, 0x52, - 0xfc, 0x7f, 0xb5, 0x88, 0x62, 0x0c, 0x2d, 0x7e, 0xf9, 0xfe, 0x24, 0x05, 0xa9, 0xde, 0xae, 0x05, - 0xe3, 0xdf, 0x2c, 0x76, 0x29, 0x19, 0x56, 0xfc, 0xca, 0x1d, 0x3c, 0x87, 0x53, 0x2a, 0xa8, 0xbf, - 0x0f, 0xe1, 0x14, 0xc5, 0xaf, 0x5c, 0xd8, 0xa5, 0x3d, 0xd2, 0xee, 0xed, 0x82, 0xf4, 0x1f, 0x94, - 0xf4, 0x84, 0xe2, 0x57, 0xaf, 0xf7, 0x79, 0xb4, 0x52, 0xac, 0xff, 0x1c, 0x46, 0x2b, 0x8a, 0x5f, - 0x6d, 0x06, 0x98, 0x32, 0xa0, 0x16, 0xff, 0xbf, 0xf2, 0x32, 0x20, 0x17, 0xbf, 0x72, 0x6f, 0x36, - 0x85, 0xaa, 0x15, 0xff, 0xbf, 0xf3, 0x42, 0x55, 0x8a, 0x5f, 0xbd, 0x65, 0x9b, 0x68, 0xb5, 0xe2, - 0xff, 0x4f, 0x1e, 0xad, 0x52, 0xfc, 0xea, 0xb5, 0xcd, 0x94, 0x01, 0xb5, 0xf8, 0xff, 0x9b, 0x97, - 0x01, 0xb9, 0xf8, 0x95, 0xbb, 0x39, 0xe7, 0x7c, 0x28, 0xb5, 0x40, 0xf9, 0xeb, 0x0e, 0xf4, 0xbd, - 0x02, 0x6b, 0x29, 0x0d, 0xac, 0x9d, 0x21, 0xb2, 0xf6, 0x28, 0xb7, 0xc0, 0xc7, 0x40, 0xf4, 0xd7, - 0x1a, 0xe2, 0xbd, 0x06, 0xfa, 0x7e, 0x21, 0xe7, 0xfc, 0x78, 0xc6, 0x21, 0xbe, 0xf0, 0x2f, 0x4c, - 0xf0, 0xd3, 0x60, 0x4e, 0xea, 0xf7, 0xf2, 0x77, 0x2c, 0xe8, 0x07, 0x79, 0x64, 0x35, 0x8c, 0x79, - 0x12, 0x24, 0xaf, 0x32, 0x32, 0x61, 0x82, 0x5b, 0x6a, 0x0b, 0xb5, 0xdf, 0x4c, 0xd1, 0x0f, 0x29, - 0xd1, 0x92, 0x69, 0x13, 0xfa, 0xcd, 0x54, 0x69, 0xae, 0xf6, 0x9b, 0x29, 0xbc, 0x05, 0x44, 0x1b, - 0xae, 0x11, 0x74, 0x8f, 0xd1, 0x8f, 0xe8, 0xfc, 0xf9, 0x81, 0xf9, 0x5b, 0xdd, 0x63, 0xbf, 0xc8, - 0xa1, 0x5b, 0xdd, 0x63, 0x78, 0x57, 0x6a, 0xcb, 0x7e, 0x8c, 0xb7, 0x01, 0xfd, 0x98, 0xce, 0x5d, - 0x1c, 0x98, 0x4b, 0x77, 0x49, 0x34, 0x02, 0xc9, 0x57, 0xbc, 0x3d, 0x59, 0x81, 0xf2, 0xed, 0xf9, - 0x69, 0x81, 0xec, 0xf6, 0xb0, 0xed, 0x11, 0x75, 0x29, 0x6d, 0x8f, 0x20, 0xca, 0xb6, 0xe7, 0x67, - 0x85, 0x1c, 0x85, 0x93, 0xb6, 0x87, 0x4f, 0xcb, 0xb6, 0x47, 0xe6, 0x22, 0xdb, 0x43, 0x76, 0xe7, - 0xe7, 0x79, 0x5c, 0xd2, 0xee, 0x64, 0xfd, 0x33, 0x36, 0x0b, 0xef, 0x8e, 0xfc, 0xa8, 0xe0, 0xdd, - 0xf9, 0x35, 0x25, 0xca, 0xdf, 0x1d, 0xe9, 0xe9, 0x60, 0xbb, 0x23, 0x28, 0xf0, 0xee, 0xfc, 0x82, - 0xce, 0xcf, 0xd9, 0x1d, 0x0e, 0x65, 0xbb, 0x23, 0x66, 0xd2, 0xdd, 0xf9, 0x25, 0x9d, 0x9b, 0xbb, - 0x3b, 0x1c, 0x4e, 0x77, 0xe7, 0x02, 0x00, 0x64, 0xfd, 0xdd, 0xa0, 0x13, 0xae, 0xa3, 0x2f, 0xd9, - 0xe4, 0x8d, 0x8d, 0x64, 0x82, 0x0e, 0x28, 0xd2, 0xfa, 0xc5, 0x5f, 0x37, 0xd0, 0x97, 0x65, 0xc4, - 0x2e, 0x36, 0xc1, 0x8b, 0xa0, 0xd4, 0xc8, 0x20, 0x9b, 0xe8, 0x2b, 0x0c, 0x52, 0xe3, 0x90, 0x4d, - 0xb8, 0x02, 0xa6, 0x28, 0x82, 0x40, 0xdc, 0x06, 0xfa, 0xaa, 0x4e, 0xe3, 0xe2, 0xbf, 0xf1, 0xc8, - 0xb7, 0x35, 0x0c, 0xb9, 0x81, 0xbe, 0x46, 0x11, 0xb2, 0x0d, 0x5e, 0xe2, 0x34, 0x6b, 0x84, 0xc7, - 0x43, 0x5f, 0x57, 0x40, 0x98, 0xc7, 0x13, 0x2b, 0xc2, 0xdf, 0x6e, 0xa2, 0x6f, 0xe8, 0x8e, 0x6e, - 0x62, 0x80, 0x08, 0xed, 0x16, 0xfa, 0xa6, 0x1e, 0xed, 0xad, 0x6c, 0xc9, 0xf8, 0xeb, 0x6d, 0xf4, - 0x2d, 0x9d, 0xe2, 0x36, 0x5c, 0x01, 0xa5, 0x9a, 0x40, 0xac, 0xaf, 0xa1, 0x6f, 0xb3, 0x38, 0x04, - 0xc9, 0xfa, 0x1a, 0xc1, 0xec, 0x6c, 0xbf, 0xff, 0xa0, 0xb1, 0xbb, 0xf5, 0x64, 0x7b, 0x7d, 0x1d, - 0x7d, 0x87, 0x63, 0xb0, 0x91, 0xda, 0x32, 0x0c, 0xc9, 0xf5, 0x06, 0xfa, 0xae, 0x82, 0x21, 0xb6, - 0xe5, 0x17, 0x60, 0x4a, 0xfd, 0x8b, 0xb9, 0x04, 0xac, 0x80, 0xbd, 0x5a, 0xb3, 0x02, 0xf8, 0x2e, - 0x28, 0x36, 0x23, 0xd1, 0x1d, 0x47, 0x85, 0x93, 0x3a, 0xe9, 0x32, 0x7a, 0xf9, 0x1e, 0x80, 0x83, - 0xdd, 0x2e, 0x58, 0x06, 0xf6, 0xab, 0xf0, 0x98, 0xb9, 0xc0, 0xbf, 0xc2, 0x79, 0x70, 0x9a, 0x16, - 0x57, 0x81, 0xd8, 0xe8, 0x97, 0x3b, 0x85, 0x5b, 0x56, 0xc6, 0x20, 0x77, 0xb6, 0x64, 0x06, 0xdb, - 0xc0, 0x60, 0xcb, 0x0c, 0x55, 0x30, 0x6f, 0xea, 0x61, 0xc9, 0x1c, 0x53, 0x06, 0x8e, 0x29, 0x33, - 0x87, 0xd2, 0xab, 0x92, 0x39, 0x4e, 0x19, 0x38, 0x4e, 0x0d, 0x72, 0x0c, 0xf4, 0xa4, 0x64, 0x8e, - 0x59, 0x03, 0xc7, 0xac, 0x99, 0x43, 0xe9, 0x3d, 0xc9, 0x1c, 0xd0, 0xc0, 0x01, 0x65, 0x8e, 0x07, - 0x60, 0xd1, 0xdc, 0x61, 0x92, 0x59, 0x26, 0x0c, 0x2c, 0x13, 0x39, 0x2c, 0x6a, 0x17, 0x49, 0x66, - 0x19, 0x37, 0xb0, 0x8c, 0xcb, 0x2c, 0x35, 0x80, 0xf2, 0xfa, 0x44, 0x32, 0xcf, 0x8c, 0x81, 0x67, - 0x26, 0x8f, 0x47, 0xeb, 0x03, 0xc9, 0x3c, 0x65, 0x03, 0x4f, 0xd9, 0x58, 0x6d, 0x72, 0xb7, 0xe7, - 0xa4, 0x7a, 0x2d, 0xc8, 0x0c, 0x5b, 0x60, 0xce, 0xd0, 0xd8, 0x39, 0x89, 0xc2, 0x92, 0x29, 0xee, - 0x82, 0xb2, 0xde, 0xc5, 0x91, 0xe7, 0x4f, 0x1a, 0xe6, 0x4f, 0x1a, 0x8a, 0x44, 0xef, 0xd8, 0xc8, - 0x1c, 0x67, 0x0c, 0x1c, 0x67, 0x06, 0x97, 0xa1, 0xb7, 0x66, 0x4e, 0xa2, 0x28, 0xc9, 0x14, 0x31, - 0x38, 0x37, 0xa4, 0xf7, 0x62, 0xa0, 0x7a, 0x4f, 0xa6, 0x7a, 0x8d, 0x17, 0x1f, 0x92, 0xcf, 0x23, - 0x70, 0x7e, 0x58, 0xf3, 0xc5, 0xe0, 0x74, 0x5d, 0x75, 0x3a, 0xf4, 0x5d, 0x88, 0xe4, 0xa8, 0x4d, - 0x0b, 0xce, 0xd4, 0x74, 0x31, 0x38, 0xb9, 0x23, 0x3b, 0x19, 0xf5, 0xed, 0x88, 0xe4, 0x2d, 0x00, - 0x67, 0x73, 0x1b, 0x2f, 0x06, 0x77, 0xab, 0xaa, 0xbb, 0xfc, 0x77, 0x26, 0x99, 0x8b, 0x95, 0xdb, - 0x00, 0x48, 0x2d, 0xa2, 0x09, 0x60, 0xd7, 0xea, 0xf5, 0xf2, 0x18, 0xfe, 0xa5, 0xba, 0xe5, 0x97, - 0x2d, 0xfa, 0xcb, 0x8b, 0x72, 0x01, 0xbb, 0xdb, 0xdd, 0x7e, 0x58, 0xfe, 0x1f, 0xff, 0xcf, 0xaa, - 0x4e, 0xf1, 0xe6, 0x09, 0x39, 0xc0, 0x56, 0xde, 0x00, 0xd3, 0x5a, 0x67, 0xab, 0x04, 0xac, 0x26, - 0x3f, 0x50, 0x9a, 0xd7, 0x6e, 0x00, 0x90, 0xfd, 0x63, 0x18, 0x38, 0x03, 0x8a, 0xfb, 0xbb, 0x7b, - 0x4f, 0xb7, 0xef, 0xef, 0xd4, 0x76, 0xb6, 0x1f, 0x94, 0xc7, 0x60, 0x09, 0x4c, 0x3e, 0xf5, 0xeb, - 0xcf, 0xea, 0xd5, 0xfd, 0x5a, 0xd9, 0x82, 0x93, 0xe0, 0xd4, 0xe3, 0xbd, 0xfa, 0x6e, 0xb9, 0x70, - 0xed, 0x1e, 0x28, 0xca, 0x8d, 0xa5, 0x19, 0x50, 0xac, 0xd5, 0xfd, 0xed, 0x9d, 0x87, 0xbb, 0x0d, - 0x1a, 0xa9, 0x64, 0xa0, 0x11, 0x2b, 0x86, 0x17, 0xe5, 0x42, 0xf5, 0x22, 0xb8, 0xd0, 0x8c, 0x3a, - 0x03, 0x7f, 0xb6, 0x48, 0xc9, 0x79, 0x39, 0x4e, 0xac, 0x9b, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, - 0x29, 0x30, 0x51, 0x54, 0x22, 0x25, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto b/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto deleted file mode 100755 index fc96074..0000000 --- a/examples/github.com/golang/protobuf/conformance/internal/conformance_proto/conformance.proto +++ /dev/null @@ -1,273 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package conformance; -option java_package = "com.google.protobuf.conformance"; - -import "google/protobuf/any.proto"; -import "google/protobuf/duration.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; -import "google/protobuf/wrappers.proto"; - -// This defines the conformance testing protocol. This protocol exists between -// the conformance test suite itself and the code being tested. For each test, -// the suite will send a ConformanceRequest message and expect a -// ConformanceResponse message. -// -// You can either run the tests in two different ways: -// -// 1. in-process (using the interface in conformance_test.h). -// -// 2. as a sub-process communicating over a pipe. Information about how to -// do this is in conformance_test_runner.cc. -// -// Pros/cons of the two approaches: -// -// - running as a sub-process is much simpler for languages other than C/C++. -// -// - running as a sub-process may be more tricky in unusual environments like -// iOS apps, where fork/stdin/stdout are not available. - -enum WireFormat { - UNSPECIFIED = 0; - PROTOBUF = 1; - JSON = 2; -} - -// Represents a single test case's input. The testee should: -// -// 1. parse this proto (which should always succeed) -// 2. parse the protobuf or JSON payload in "payload" (which may fail) -// 3. if the parse succeeded, serialize the message in the requested format. -message ConformanceRequest { - // The payload (whether protobuf of JSON) is always for a TestAllTypes proto - // (see below). - oneof payload { - bytes protobuf_payload = 1; - string json_payload = 2; - } - - // Which format should the testee serialize its message to? - WireFormat requested_output_format = 3; -} - -// Represents a single test case's output. -message ConformanceResponse { - oneof result { - // This string should be set to indicate parsing failed. The string can - // provide more information about the parse error if it is available. - // - // Setting this string does not necessarily mean the testee failed the - // test. Some of the test cases are intentionally invalid input. - string parse_error = 1; - - // If the input was successfully parsed but errors occurred when - // serializing it to the requested output format, set the error message in - // this field. - string serialize_error = 6; - - // This should be set if some other error occurred. This will always - // indicate that the test failed. The string can provide more information - // about the failure. - string runtime_error = 2; - - // If the input was successfully parsed and the requested output was - // protobuf, serialize it to protobuf and set it in this field. - bytes protobuf_payload = 3; - - // If the input was successfully parsed and the requested output was JSON, - // serialize to JSON and set it in this field. - string json_payload = 4; - - // For when the testee skipped the test, likely because a certain feature - // wasn't supported, like JSON input/output. - string skipped = 5; - } -} - -// This proto includes every type of field in both singular and repeated -// forms. -message TestAllTypes { - message NestedMessage { - int32 a = 1; - TestAllTypes corecursive = 2; - } - - enum NestedEnum { - FOO = 0; - BAR = 1; - BAZ = 2; - NEG = -1; // Intentionally negative. - } - - // Singular - int32 optional_int32 = 1; - int64 optional_int64 = 2; - uint32 optional_uint32 = 3; - uint64 optional_uint64 = 4; - sint32 optional_sint32 = 5; - sint64 optional_sint64 = 6; - fixed32 optional_fixed32 = 7; - fixed64 optional_fixed64 = 8; - sfixed32 optional_sfixed32 = 9; - sfixed64 optional_sfixed64 = 10; - float optional_float = 11; - double optional_double = 12; - bool optional_bool = 13; - string optional_string = 14; - bytes optional_bytes = 15; - - NestedMessage optional_nested_message = 18; - ForeignMessage optional_foreign_message = 19; - - NestedEnum optional_nested_enum = 21; - ForeignEnum optional_foreign_enum = 22; - - string optional_string_piece = 24 [ctype=STRING_PIECE]; - string optional_cord = 25 [ctype=CORD]; - - TestAllTypes recursive_message = 27; - - // Repeated - repeated int32 repeated_int32 = 31; - repeated int64 repeated_int64 = 32; - repeated uint32 repeated_uint32 = 33; - repeated uint64 repeated_uint64 = 34; - repeated sint32 repeated_sint32 = 35; - repeated sint64 repeated_sint64 = 36; - repeated fixed32 repeated_fixed32 = 37; - repeated fixed64 repeated_fixed64 = 38; - repeated sfixed32 repeated_sfixed32 = 39; - repeated sfixed64 repeated_sfixed64 = 40; - repeated float repeated_float = 41; - repeated double repeated_double = 42; - repeated bool repeated_bool = 43; - repeated string repeated_string = 44; - repeated bytes repeated_bytes = 45; - - repeated NestedMessage repeated_nested_message = 48; - repeated ForeignMessage repeated_foreign_message = 49; - - repeated NestedEnum repeated_nested_enum = 51; - repeated ForeignEnum repeated_foreign_enum = 52; - - repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord = 55 [ctype=CORD]; - - // Map - map < int32, int32> map_int32_int32 = 56; - map < int64, int64> map_int64_int64 = 57; - map < uint32, uint32> map_uint32_uint32 = 58; - map < uint64, uint64> map_uint64_uint64 = 59; - map < sint32, sint32> map_sint32_sint32 = 60; - map < sint64, sint64> map_sint64_sint64 = 61; - map < fixed32, fixed32> map_fixed32_fixed32 = 62; - map < fixed64, fixed64> map_fixed64_fixed64 = 63; - map map_sfixed32_sfixed32 = 64; - map map_sfixed64_sfixed64 = 65; - map < int32, float> map_int32_float = 66; - map < int32, double> map_int32_double = 67; - map < bool, bool> map_bool_bool = 68; - map < string, string> map_string_string = 69; - map < string, bytes> map_string_bytes = 70; - map < string, NestedMessage> map_string_nested_message = 71; - map < string, ForeignMessage> map_string_foreign_message = 72; - map < string, NestedEnum> map_string_nested_enum = 73; - map < string, ForeignEnum> map_string_foreign_enum = 74; - - oneof oneof_field { - uint32 oneof_uint32 = 111; - NestedMessage oneof_nested_message = 112; - string oneof_string = 113; - bytes oneof_bytes = 114; - } - - // Well-known types - google.protobuf.BoolValue optional_bool_wrapper = 201; - google.protobuf.Int32Value optional_int32_wrapper = 202; - google.protobuf.Int64Value optional_int64_wrapper = 203; - google.protobuf.UInt32Value optional_uint32_wrapper = 204; - google.protobuf.UInt64Value optional_uint64_wrapper = 205; - google.protobuf.FloatValue optional_float_wrapper = 206; - google.protobuf.DoubleValue optional_double_wrapper = 207; - google.protobuf.StringValue optional_string_wrapper = 208; - google.protobuf.BytesValue optional_bytes_wrapper = 209; - - repeated google.protobuf.BoolValue repeated_bool_wrapper = 211; - repeated google.protobuf.Int32Value repeated_int32_wrapper = 212; - repeated google.protobuf.Int64Value repeated_int64_wrapper = 213; - repeated google.protobuf.UInt32Value repeated_uint32_wrapper = 214; - repeated google.protobuf.UInt64Value repeated_uint64_wrapper = 215; - repeated google.protobuf.FloatValue repeated_float_wrapper = 216; - repeated google.protobuf.DoubleValue repeated_double_wrapper = 217; - repeated google.protobuf.StringValue repeated_string_wrapper = 218; - repeated google.protobuf.BytesValue repeated_bytes_wrapper = 219; - - google.protobuf.Duration optional_duration = 301; - google.protobuf.Timestamp optional_timestamp = 302; - google.protobuf.FieldMask optional_field_mask = 303; - google.protobuf.Struct optional_struct = 304; - google.protobuf.Any optional_any = 305; - google.protobuf.Value optional_value = 306; - - repeated google.protobuf.Duration repeated_duration = 311; - repeated google.protobuf.Timestamp repeated_timestamp = 312; - repeated google.protobuf.FieldMask repeated_fieldmask = 313; - repeated google.protobuf.Struct repeated_struct = 324; - repeated google.protobuf.Any repeated_any = 315; - repeated google.protobuf.Value repeated_value = 316; - - // Test field-name-to-JSON-name convention. - int32 fieldname1 = 401; - int32 field_name2 = 402; - int32 _field_name3 = 403; - int32 field__name4_ = 404; - int32 field0name5 = 405; - int32 field_0_name6 = 406; - int32 fieldName7 = 407; - int32 FieldName8 = 408; - int32 field_Name9 = 409; - int32 Field_Name10 = 410; - int32 FIELD_NAME11 = 411; - int32 FIELD_name12 = 412; -} - -message ForeignMessage { - int32 c = 1; -} - -enum ForeignEnum { - FOREIGN_FOO = 0; - FOREIGN_BAR = 1; - FOREIGN_BAZ = 2; -} diff --git a/examples/github.com/golang/protobuf/conformance/test.sh b/examples/github.com/golang/protobuf/conformance/test.sh deleted file mode 100755 index e6de29b..0000000 --- a/examples/github.com/golang/protobuf/conformance/test.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -PROTOBUF_ROOT=$1 -CONFORMANCE_ROOT=$1/conformance -CONFORMANCE_TEST_RUNNER=$CONFORMANCE_ROOT/conformance-test-runner - -cd $(dirname $0) - -if [[ $PROTOBUF_ROOT == "" ]]; then - echo "usage: test.sh " >/dev/stderr - exit 1 -fi - -if [[ ! -x $CONFORMANCE_TEST_RUNNER ]]; then - echo "SKIP: conformance test runner not installed" >/dev/stderr - exit 0 -fi - -a=$CONFORMANCE_ROOT/conformance.proto -b=internal/conformance_proto/conformance.proto -if [[ $(diff $a $b) != "" ]]; then - cp $a $b - echo "WARNING: conformance.proto is out of date" >/dev/stderr -fi - -$CONFORMANCE_TEST_RUNNER --failure_list failure_list_go.txt ./conformance.sh diff --git a/examples/github.com/golang/protobuf/descriptor/descriptor.go b/examples/github.com/golang/protobuf/descriptor/descriptor.go deleted file mode 100755 index ac7e51b..0000000 --- a/examples/github.com/golang/protobuf/descriptor/descriptor.go +++ /dev/null @@ -1,93 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package descriptor provides functions for obtaining protocol buffer -// descriptors for generated Go types. -// -// These functions cannot go in package proto because they depend on the -// generated protobuf descriptor messages, which themselves depend on proto. -package descriptor - -import ( - "bytes" - "compress/gzip" - "fmt" - "io/ioutil" - - "github.com/golang/protobuf/proto" - protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" -) - -// extractFile extracts a FileDescriptorProto from a gzip'd buffer. -func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) { - r, err := gzip.NewReader(bytes.NewReader(gz)) - if err != nil { - return nil, fmt.Errorf("failed to open gzip reader: %v", err) - } - defer r.Close() - - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("failed to uncompress descriptor: %v", err) - } - - fd := new(protobuf.FileDescriptorProto) - if err := proto.Unmarshal(b, fd); err != nil { - return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err) - } - - return fd, nil -} - -// Message is a proto.Message with a method to return its descriptor. -// -// Message types generated by the protocol compiler always satisfy -// the Message interface. -type Message interface { - proto.Message - Descriptor() ([]byte, []int) -} - -// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it -// describing the given message. -func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) { - gz, path := msg.Descriptor() - fd, err := extractFile(gz) - if err != nil { - panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err)) - } - - md = fd.MessageType[path[0]] - for _, i := range path[1:] { - md = md.NestedType[i] - } - return fd, md -} diff --git a/examples/github.com/golang/protobuf/descriptor/descriptor_test.go b/examples/github.com/golang/protobuf/descriptor/descriptor_test.go deleted file mode 100755 index bf5174d..0000000 --- a/examples/github.com/golang/protobuf/descriptor/descriptor_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package descriptor_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/descriptor" - tpb "github.com/golang/protobuf/proto/test_proto" - protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" -) - -func TestMessage(t *testing.T) { - var msg *protobuf.DescriptorProto - fd, md := descriptor.ForMessage(msg) - if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want { - t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want) - } - if name, want := md.GetName(), "DescriptorProto"; name != want { - t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want) - } -} - -func Example_options() { - var msg *tpb.MyMessageSet - _, md := descriptor.ForMessage(msg) - if md.GetOptions().GetMessageSetWireFormat() { - fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName()) - } - - // Output: - // MyMessageSet uses option message_set_wire_format. -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb.go b/examples/github.com/golang/protobuf/jsonpb/jsonpb.go deleted file mode 100755 index ff368f3..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb.go +++ /dev/null @@ -1,1241 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. -It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. - -This package produces a different output than the standard "encoding/json" package, -which does not operate correctly on protocol buffers. -*/ -package jsonpb - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "math" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/golang/protobuf/proto" - - stpb "github.com/golang/protobuf/ptypes/struct" -) - -const secondInNanos = int64(time.Second / time.Nanosecond) - -// Marshaler is a configurable object for converting between -// protocol buffer objects and a JSON representation for them. -type Marshaler struct { - // Whether to render enum values as integers, as opposed to string values. - EnumsAsInts bool - - // Whether to render fields with zero values. - EmitDefaults bool - - // A string to indent each level by. The presence of this field will - // also cause a space to appear between the field separator and - // value, and for newlines to be appear between fields and array - // elements. - Indent string - - // Whether to use the original (.proto) name for fields. - OrigName bool - - // A custom URL resolver to use when marshaling Any messages to JSON. - // If unset, the default resolution strategy is to extract the - // fully-qualified type name from the type URL and pass that to - // proto.MessageType(string). - AnyResolver AnyResolver -} - -// AnyResolver takes a type URL, present in an Any message, and resolves it into -// an instance of the associated message. -type AnyResolver interface { - Resolve(typeUrl string) (proto.Message, error) -} - -func defaultResolveAny(typeUrl string) (proto.Message, error) { - // Only the part of typeUrl after the last slash is relevant. - mname := typeUrl - if slash := strings.LastIndex(mname, "/"); slash >= 0 { - mname = mname[slash+1:] - } - mt := proto.MessageType(mname) - if mt == nil { - return nil, fmt.Errorf("unknown message type %q", mname) - } - return reflect.New(mt.Elem()).Interface().(proto.Message), nil -} - -// JSONPBMarshaler is implemented by protobuf messages that customize the -// way they are marshaled to JSON. Messages that implement this should -// also implement JSONPBUnmarshaler so that the custom format can be -// parsed. -type JSONPBMarshaler interface { - MarshalJSONPB(*Marshaler) ([]byte, error) -} - -// JSONPBUnmarshaler is implemented by protobuf messages that customize -// the way they are unmarshaled from JSON. Messages that implement this -// should also implement JSONPBMarshaler so that the custom format can be -// produced. -type JSONPBUnmarshaler interface { - UnmarshalJSONPB(*Unmarshaler, []byte) error -} - -// Marshal marshals a protocol buffer into JSON. -func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { - v := reflect.ValueOf(pb) - if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { - return errors.New("Marshal called with nil") - } - // Check for unset required fields first. - if err := checkRequiredFields(pb); err != nil { - return err - } - writer := &errWriter{writer: out} - return m.marshalObject(writer, pb, "", "") -} - -// MarshalToString converts a protocol buffer object to JSON string. -func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { - var buf bytes.Buffer - if err := m.Marshal(&buf, pb); err != nil { - return "", err - } - return buf.String(), nil -} - -type int32Slice []int32 - -var nonFinite = map[string]float64{ - `"NaN"`: math.NaN(), - `"Infinity"`: math.Inf(1), - `"-Infinity"`: math.Inf(-1), -} - -// For sorting extensions ids to ensure stable output. -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -type wkt interface { - XXX_WellKnownType() string -} - -// marshalObject writes a struct to the Writer. -func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error { - if jsm, ok := v.(JSONPBMarshaler); ok { - b, err := jsm.MarshalJSONPB(m) - if err != nil { - return err - } - if typeURL != "" { - // we are marshaling this object to an Any type - var js map[string]*json.RawMessage - if err = json.Unmarshal(b, &js); err != nil { - return fmt.Errorf("type %T produced invalid JSON: %v", v, err) - } - turl, err := json.Marshal(typeURL) - if err != nil { - return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) - } - js["@type"] = (*json.RawMessage)(&turl) - if b, err = json.Marshal(js); err != nil { - return err - } - } - - out.write(string(b)) - return out.err - } - - s := reflect.ValueOf(v).Elem() - - // Handle well-known types. - if wkt, ok := v.(wkt); ok { - switch wkt.XXX_WellKnownType() { - case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", - "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": - // "Wrappers use the same representation in JSON - // as the wrapped primitive type, ..." - sprop := proto.GetProperties(s.Type()) - return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent) - case "Any": - // Any is a bit more involved. - return m.marshalAny(out, v, indent) - case "Duration": - // "Generated output always contains 0, 3, 6, or 9 fractional digits, - // depending on required precision." - s, ns := s.Field(0).Int(), s.Field(1).Int() - if ns <= -secondInNanos || ns >= secondInNanos { - return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) - } - if (s > 0 && ns < 0) || (s < 0 && ns > 0) { - return errors.New("signs of seconds and nanos do not match") - } - if s < 0 { - ns = -ns - } - x := fmt.Sprintf("%d.%09d", s, ns) - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, ".000") - out.write(`"`) - out.write(x) - out.write(`s"`) - return out.err - case "Struct", "ListValue": - // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice. - // TODO: pass the correct Properties if needed. - return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent) - case "Timestamp": - // "RFC 3339, where generated output will always be Z-normalized - // and uses 0, 3, 6 or 9 fractional digits." - s, ns := s.Field(0).Int(), s.Field(1).Int() - if ns < 0 || ns >= secondInNanos { - return fmt.Errorf("ns out of range [0, %v)", secondInNanos) - } - t := time.Unix(s, ns).UTC() - // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). - x := t.Format("2006-01-02T15:04:05.000000000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, ".000") - out.write(`"`) - out.write(x) - out.write(`Z"`) - return out.err - case "Value": - // Value has a single oneof. - kind := s.Field(0) - if kind.IsNil() { - // "absence of any variant indicates an error" - return errors.New("nil Value") - } - // oneof -> *T -> T -> T.F - x := kind.Elem().Elem().Field(0) - // TODO: pass the correct Properties if needed. - return m.marshalValue(out, &proto.Properties{}, x, indent) - } - } - - out.write("{") - if m.Indent != "" { - out.write("\n") - } - - firstField := true - - if typeURL != "" { - if err := m.marshalTypeURL(out, indent, typeURL); err != nil { - return err - } - firstField = false - } - - for i := 0; i < s.NumField(); i++ { - value := s.Field(i) - valueField := s.Type().Field(i) - if strings.HasPrefix(valueField.Name, "XXX_") { - continue - } - - // IsNil will panic on most value kinds. - switch value.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface: - if value.IsNil() { - continue - } - } - - if !m.EmitDefaults { - switch value.Kind() { - case reflect.Bool: - if !value.Bool() { - continue - } - case reflect.Int32, reflect.Int64: - if value.Int() == 0 { - continue - } - case reflect.Uint32, reflect.Uint64: - if value.Uint() == 0 { - continue - } - case reflect.Float32, reflect.Float64: - if value.Float() == 0 { - continue - } - case reflect.String: - if value.Len() == 0 { - continue - } - case reflect.Map, reflect.Ptr, reflect.Slice: - if value.IsNil() { - continue - } - } - } - - // Oneof fields need special handling. - if valueField.Tag.Get("protobuf_oneof") != "" { - // value is an interface containing &T{real_value}. - sv := value.Elem().Elem() // interface -> *T -> T - value = sv.Field(0) - valueField = sv.Type().Field(0) - } - prop := jsonProperties(valueField, m.OrigName) - if !firstField { - m.writeSep(out) - } - if err := m.marshalField(out, prop, value, indent); err != nil { - return err - } - firstField = false - } - - // Handle proto2 extensions. - if ep, ok := v.(proto.Message); ok { - extensions := proto.RegisteredExtensions(v) - // Sort extensions for stable output. - ids := make([]int32, 0, len(extensions)) - for id, desc := range extensions { - if !proto.HasExtension(ep, desc) { - continue - } - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - for _, id := range ids { - desc := extensions[id] - if desc == nil { - // unknown extension - continue - } - ext, extErr := proto.GetExtension(ep, desc) - if extErr != nil { - return extErr - } - value := reflect.ValueOf(ext) - var prop proto.Properties - prop.Parse(desc.Tag) - prop.JSONName = fmt.Sprintf("[%s]", desc.Name) - if !firstField { - m.writeSep(out) - } - if err := m.marshalField(out, &prop, value, indent); err != nil { - return err - } - firstField = false - } - - } - - if m.Indent != "" { - out.write("\n") - out.write(indent) - } - out.write("}") - return out.err -} - -func (m *Marshaler) writeSep(out *errWriter) { - if m.Indent != "" { - out.write(",\n") - } else { - out.write(",") - } -} - -func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error { - // "If the Any contains a value that has a special JSON mapping, - // it will be converted as follows: {"@type": xxx, "value": yyy}. - // Otherwise, the value will be converted into a JSON object, - // and the "@type" field will be inserted to indicate the actual data type." - v := reflect.ValueOf(any).Elem() - turl := v.Field(0).String() - val := v.Field(1).Bytes() - - var msg proto.Message - var err error - if m.AnyResolver != nil { - msg, err = m.AnyResolver.Resolve(turl) - } else { - msg, err = defaultResolveAny(turl) - } - if err != nil { - return err - } - - if err := proto.Unmarshal(val, msg); err != nil { - return err - } - - if _, ok := msg.(wkt); ok { - out.write("{") - if m.Indent != "" { - out.write("\n") - } - if err := m.marshalTypeURL(out, indent, turl); err != nil { - return err - } - m.writeSep(out) - if m.Indent != "" { - out.write(indent) - out.write(m.Indent) - out.write(`"value": `) - } else { - out.write(`"value":`) - } - if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil { - return err - } - if m.Indent != "" { - out.write("\n") - out.write(indent) - } - out.write("}") - return out.err - } - - return m.marshalObject(out, msg, indent, turl) -} - -func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error { - if m.Indent != "" { - out.write(indent) - out.write(m.Indent) - } - out.write(`"@type":`) - if m.Indent != "" { - out.write(" ") - } - b, err := json.Marshal(typeURL) - if err != nil { - return err - } - out.write(string(b)) - return out.err -} - -// marshalField writes field description and value to the Writer. -func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { - if m.Indent != "" { - out.write(indent) - out.write(m.Indent) - } - out.write(`"`) - out.write(prop.JSONName) - out.write(`":`) - if m.Indent != "" { - out.write(" ") - } - if err := m.marshalValue(out, prop, v, indent); err != nil { - return err - } - return nil -} - -// marshalValue writes the value to the Writer. -func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { - var err error - v = reflect.Indirect(v) - - // Handle nil pointer - if v.Kind() == reflect.Invalid { - out.write("null") - return out.err - } - - // Handle repeated elements. - if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 { - out.write("[") - comma := "" - for i := 0; i < v.Len(); i++ { - sliceVal := v.Index(i) - out.write(comma) - if m.Indent != "" { - out.write("\n") - out.write(indent) - out.write(m.Indent) - out.write(m.Indent) - } - if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil { - return err - } - comma = "," - } - if m.Indent != "" { - out.write("\n") - out.write(indent) - out.write(m.Indent) - } - out.write("]") - return out.err - } - - // Handle well-known types. - // Most are handled up in marshalObject (because 99% are messages). - if wkt, ok := v.Interface().(wkt); ok { - switch wkt.XXX_WellKnownType() { - case "NullValue": - out.write("null") - return out.err - } - } - - // Handle enumerations. - if !m.EnumsAsInts && prop.Enum != "" { - // Unknown enum values will are stringified by the proto library as their - // value. Such values should _not_ be quoted or they will be interpreted - // as an enum string instead of their value. - enumStr := v.Interface().(fmt.Stringer).String() - var valStr string - if v.Kind() == reflect.Ptr { - valStr = strconv.Itoa(int(v.Elem().Int())) - } else { - valStr = strconv.Itoa(int(v.Int())) - } - isKnownEnum := enumStr != valStr - if isKnownEnum { - out.write(`"`) - } - out.write(enumStr) - if isKnownEnum { - out.write(`"`) - } - return out.err - } - - // Handle nested messages. - if v.Kind() == reflect.Struct { - return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "") - } - - // Handle maps. - // Since Go randomizes map iteration, we sort keys for stable output. - if v.Kind() == reflect.Map { - out.write(`{`) - keys := v.MapKeys() - sort.Sort(mapKeys(keys)) - for i, k := range keys { - if i > 0 { - out.write(`,`) - } - if m.Indent != "" { - out.write("\n") - out.write(indent) - out.write(m.Indent) - out.write(m.Indent) - } - - b, err := json.Marshal(k.Interface()) - if err != nil { - return err - } - s := string(b) - - // If the JSON is not a string value, encode it again to make it one. - if !strings.HasPrefix(s, `"`) { - b, err := json.Marshal(s) - if err != nil { - return err - } - s = string(b) - } - - out.write(s) - out.write(`:`) - if m.Indent != "" { - out.write(` `) - } - - if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil { - return err - } - } - if m.Indent != "" { - out.write("\n") - out.write(indent) - out.write(m.Indent) - } - out.write(`}`) - return out.err - } - - // Handle non-finite floats, e.g. NaN, Infinity and -Infinity. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - f := v.Float() - var sval string - switch { - case math.IsInf(f, 1): - sval = `"Infinity"` - case math.IsInf(f, -1): - sval = `"-Infinity"` - case math.IsNaN(f): - sval = `"NaN"` - } - if sval != "" { - out.write(sval) - return out.err - } - } - - // Default handling defers to the encoding/json library. - b, err := json.Marshal(v.Interface()) - if err != nil { - return err - } - needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) - if needToQuote { - out.write(`"`) - } - out.write(string(b)) - if needToQuote { - out.write(`"`) - } - return out.err -} - -// Unmarshaler is a configurable object for converting from a JSON -// representation to a protocol buffer object. -type Unmarshaler struct { - // Whether to allow messages to contain unknown fields, as opposed to - // failing to unmarshal. - AllowUnknownFields bool - - // A custom URL resolver to use when unmarshaling Any messages from JSON. - // If unset, the default resolution strategy is to extract the - // fully-qualified type name from the type URL and pass that to - // proto.MessageType(string). - AnyResolver AnyResolver -} - -// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. -// This function is lenient and will decode any options permutations of the -// related Marshaler. -func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { - inputValue := json.RawMessage{} - if err := dec.Decode(&inputValue); err != nil { - return err - } - if err := u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil); err != nil { - return err - } - return checkRequiredFields(pb) -} - -// Unmarshal unmarshals a JSON object stream into a protocol -// buffer. This function is lenient and will decode any options -// permutations of the related Marshaler. -func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error { - dec := json.NewDecoder(r) - return u.UnmarshalNext(dec, pb) -} - -// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. -// This function is lenient and will decode any options permutations of the -// related Marshaler. -func UnmarshalNext(dec *json.Decoder, pb proto.Message) error { - return new(Unmarshaler).UnmarshalNext(dec, pb) -} - -// Unmarshal unmarshals a JSON object stream into a protocol -// buffer. This function is lenient and will decode any options -// permutations of the related Marshaler. -func Unmarshal(r io.Reader, pb proto.Message) error { - return new(Unmarshaler).Unmarshal(r, pb) -} - -// UnmarshalString will populate the fields of a protocol buffer based -// on a JSON string. This function is lenient and will decode any options -// permutations of the related Marshaler. -func UnmarshalString(str string, pb proto.Message) error { - return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb) -} - -// unmarshalValue converts/copies a value into the target. -// prop may be nil. -func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error { - targetType := target.Type() - - // Allocate memory for pointer fields. - if targetType.Kind() == reflect.Ptr { - // If input value is "null" and target is a pointer type, then the field should be treated as not set - // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue. - _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler) - if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler { - return nil - } - target.Set(reflect.New(targetType.Elem())) - - return u.unmarshalValue(target.Elem(), inputValue, prop) - } - - if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok { - return jsu.UnmarshalJSONPB(u, []byte(inputValue)) - } - - // Handle well-known types that are not pointers. - if w, ok := target.Addr().Interface().(wkt); ok { - switch w.XXX_WellKnownType() { - case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", - "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": - return u.unmarshalValue(target.Field(0), inputValue, prop) - case "Any": - // Use json.RawMessage pointer type instead of value to support pre-1.8 version. - // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see - // https://github.com/golang/go/issues/14493 - var jsonFields map[string]*json.RawMessage - if err := json.Unmarshal(inputValue, &jsonFields); err != nil { - return err - } - - val, ok := jsonFields["@type"] - if !ok || val == nil { - return errors.New("Any JSON doesn't have '@type'") - } - - var turl string - if err := json.Unmarshal([]byte(*val), &turl); err != nil { - return fmt.Errorf("can't unmarshal Any's '@type': %q", *val) - } - target.Field(0).SetString(turl) - - var m proto.Message - var err error - if u.AnyResolver != nil { - m, err = u.AnyResolver.Resolve(turl) - } else { - m, err = defaultResolveAny(turl) - } - if err != nil { - return err - } - - if _, ok := m.(wkt); ok { - val, ok := jsonFields["value"] - if !ok { - return errors.New("Any JSON doesn't have 'value'") - } - - if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil { - return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) - } - } else { - delete(jsonFields, "@type") - nestedProto, err := json.Marshal(jsonFields) - if err != nil { - return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) - } - - if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil { - return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) - } - } - - b, err := proto.Marshal(m) - if err != nil { - return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err) - } - target.Field(1).SetBytes(b) - - return nil - case "Duration": - unq, err := strconv.Unquote(string(inputValue)) - if err != nil { - return err - } - - d, err := time.ParseDuration(unq) - if err != nil { - return fmt.Errorf("bad Duration: %v", err) - } - - ns := d.Nanoseconds() - s := ns / 1e9 - ns %= 1e9 - target.Field(0).SetInt(s) - target.Field(1).SetInt(ns) - return nil - case "Timestamp": - unq, err := strconv.Unquote(string(inputValue)) - if err != nil { - return err - } - - t, err := time.Parse(time.RFC3339Nano, unq) - if err != nil { - return fmt.Errorf("bad Timestamp: %v", err) - } - - target.Field(0).SetInt(t.Unix()) - target.Field(1).SetInt(int64(t.Nanosecond())) - return nil - case "Struct": - var m map[string]json.RawMessage - if err := json.Unmarshal(inputValue, &m); err != nil { - return fmt.Errorf("bad StructValue: %v", err) - } - - target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{})) - for k, jv := range m { - pv := &stpb.Value{} - if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil { - return fmt.Errorf("bad value in StructValue for key %q: %v", k, err) - } - target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv)) - } - return nil - case "ListValue": - var s []json.RawMessage - if err := json.Unmarshal(inputValue, &s); err != nil { - return fmt.Errorf("bad ListValue: %v", err) - } - - target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s)))) - for i, sv := range s { - if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil { - return err - } - } - return nil - case "Value": - ivStr := string(inputValue) - if ivStr == "null" { - target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{})) - } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil { - target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v})) - } else if v, err := strconv.Unquote(ivStr); err == nil { - target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v})) - } else if v, err := strconv.ParseBool(ivStr); err == nil { - target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v})) - } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil { - lv := &stpb.ListValue{} - target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv})) - return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop) - } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil { - sv := &stpb.Struct{} - target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv})) - return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop) - } else { - return fmt.Errorf("unrecognized type for Value %q", ivStr) - } - return nil - } - } - - // Handle enums, which have an underlying type of int32, - // and may appear as strings. - // The case of an enum appearing as a number is handled - // at the bottom of this function. - if inputValue[0] == '"' && prop != nil && prop.Enum != "" { - vmap := proto.EnumValueMap(prop.Enum) - // Don't need to do unquoting; valid enum names - // are from a limited character set. - s := inputValue[1 : len(inputValue)-1] - n, ok := vmap[string(s)] - if !ok { - return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum) - } - if target.Kind() == reflect.Ptr { // proto2 - target.Set(reflect.New(targetType.Elem())) - target = target.Elem() - } - target.SetInt(int64(n)) - return nil - } - - // Handle nested messages. - if targetType.Kind() == reflect.Struct { - var jsonFields map[string]json.RawMessage - if err := json.Unmarshal(inputValue, &jsonFields); err != nil { - return err - } - - consumeField := func(prop *proto.Properties) (json.RawMessage, bool) { - // Be liberal in what names we accept; both orig_name and camelName are okay. - fieldNames := acceptedJSONFieldNames(prop) - - vOrig, okOrig := jsonFields[fieldNames.orig] - vCamel, okCamel := jsonFields[fieldNames.camel] - if !okOrig && !okCamel { - return nil, false - } - // If, for some reason, both are present in the data, favour the camelName. - var raw json.RawMessage - if okOrig { - raw = vOrig - delete(jsonFields, fieldNames.orig) - } - if okCamel { - raw = vCamel - delete(jsonFields, fieldNames.camel) - } - return raw, true - } - - sprops := proto.GetProperties(targetType) - for i := 0; i < target.NumField(); i++ { - ft := target.Type().Field(i) - if strings.HasPrefix(ft.Name, "XXX_") { - continue - } - - valueForField, ok := consumeField(sprops.Prop[i]) - if !ok { - continue - } - - if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil { - return err - } - } - // Check for any oneof fields. - if len(jsonFields) > 0 { - for _, oop := range sprops.OneofTypes { - raw, ok := consumeField(oop.Prop) - if !ok { - continue - } - nv := reflect.New(oop.Type.Elem()) - target.Field(oop.Field).Set(nv) - if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil { - return err - } - } - } - // Handle proto2 extensions. - if len(jsonFields) > 0 { - if ep, ok := target.Addr().Interface().(proto.Message); ok { - for _, ext := range proto.RegisteredExtensions(ep) { - name := fmt.Sprintf("[%s]", ext.Name) - raw, ok := jsonFields[name] - if !ok { - continue - } - delete(jsonFields, name) - nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem()) - if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil { - return err - } - if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil { - return err - } - } - } - } - if !u.AllowUnknownFields && len(jsonFields) > 0 { - // Pick any field to be the scapegoat. - var f string - for fname := range jsonFields { - f = fname - break - } - return fmt.Errorf("unknown field %q in %v", f, targetType) - } - return nil - } - - // Handle arrays (which aren't encoded bytes) - if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 { - var slc []json.RawMessage - if err := json.Unmarshal(inputValue, &slc); err != nil { - return err - } - if slc != nil { - l := len(slc) - target.Set(reflect.MakeSlice(targetType, l, l)) - for i := 0; i < l; i++ { - if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil { - return err - } - } - } - return nil - } - - // Handle maps (whose keys are always strings) - if targetType.Kind() == reflect.Map { - var mp map[string]json.RawMessage - if err := json.Unmarshal(inputValue, &mp); err != nil { - return err - } - if mp != nil { - target.Set(reflect.MakeMap(targetType)) - for ks, raw := range mp { - // Unmarshal map key. The core json library already decoded the key into a - // string, so we handle that specially. Other types were quoted post-serialization. - var k reflect.Value - if targetType.Key().Kind() == reflect.String { - k = reflect.ValueOf(ks) - } else { - k = reflect.New(targetType.Key()).Elem() - // TODO: pass the correct Properties if needed. - if err := u.unmarshalValue(k, json.RawMessage(ks), nil); err != nil { - return err - } - } - - // Unmarshal map value. - v := reflect.New(targetType.Elem()).Elem() - // TODO: pass the correct Properties if needed. - if err := u.unmarshalValue(v, raw, nil); err != nil { - return err - } - target.SetMapIndex(k, v) - } - } - return nil - } - - // 64-bit integers can be encoded as strings. In this case we drop - // the quotes and proceed as normal. - isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 - if isNum && strings.HasPrefix(string(inputValue), `"`) { - inputValue = inputValue[1 : len(inputValue)-1] - } - - // Non-finite numbers can be encoded as strings. - isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64 - if isFloat { - if num, ok := nonFinite[string(inputValue)]; ok { - target.SetFloat(num) - return nil - } - } - - // Use the encoding/json for parsing other value types. - return json.Unmarshal(inputValue, target.Addr().Interface()) -} - -// jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute. -func jsonProperties(f reflect.StructField, origName bool) *proto.Properties { - var prop proto.Properties - prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) - if origName || prop.JSONName == "" { - prop.JSONName = prop.OrigName - } - return &prop -} - -type fieldNames struct { - orig, camel string -} - -func acceptedJSONFieldNames(prop *proto.Properties) fieldNames { - opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName} - if prop.JSONName != "" { - opts.camel = prop.JSONName - } - return opts -} - -// Writer wrapper inspired by https://blog.golang.org/errors-are-values -type errWriter struct { - writer io.Writer - err error -} - -func (w *errWriter) write(str string) { - if w.err != nil { - return - } - _, w.err = w.writer.Write([]byte(str)) -} - -// Map fields may have key types of non-float scalars, strings and enums. -// The easiest way to sort them in some deterministic order is to use fmt. -// If this turns out to be inefficient we can always consider other options, -// such as doing a Schwartzian transform. -// -// Numeric keys are sorted in numeric order per -// https://developers.google.com/protocol-buffers/docs/proto#maps. -type mapKeys []reflect.Value - -func (s mapKeys) Len() int { return len(s) } -func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s mapKeys) Less(i, j int) bool { - if k := s[i].Kind(); k == s[j].Kind() { - switch k { - case reflect.Int32, reflect.Int64: - return s[i].Int() < s[j].Int() - case reflect.Uint32, reflect.Uint64: - return s[i].Uint() < s[j].Uint() - } - } - return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) -} - -// checkRequiredFields returns an error if any required field in the given proto message is not set. -// This function is used by both Marshal and Unmarshal. While required fields only exist in a -// proto2 message, a proto3 message can contain proto2 message(s). -func checkRequiredFields(pb proto.Message) error { - // Most well-known type messages do not contain required fields. The "Any" type may contain - // a message that has required fields. - // - // When an Any message is being marshaled, the code will invoked proto.Unmarshal on Any.Value - // field in order to transform that into JSON, and that should have returned an error if a - // required field is not set in the embedded message. - // - // When an Any message is being unmarshaled, the code will have invoked proto.Marshal on the - // embedded message to store the serialized message in Any.Value field, and that should have - // returned an error if a required field is not set. - if _, ok := pb.(wkt); ok { - return nil - } - - v := reflect.ValueOf(pb) - // Skip message if it is not a struct pointer. - if v.Kind() != reflect.Ptr { - return nil - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return nil - } - - for i := 0; i < v.NumField(); i++ { - field := v.Field(i) - sfield := v.Type().Field(i) - - if sfield.PkgPath != "" { - // blank PkgPath means the field is exported; skip if not exported - continue - } - - if strings.HasPrefix(sfield.Name, "XXX_") { - continue - } - - // Oneof field is an interface implemented by wrapper structs containing the actual oneof - // field, i.e. an interface containing &T{real_value}. - if sfield.Tag.Get("protobuf_oneof") != "" { - if field.Kind() != reflect.Interface { - continue - } - v := field.Elem() - if v.Kind() != reflect.Ptr || v.IsNil() { - continue - } - v = v.Elem() - if v.Kind() != reflect.Struct || v.NumField() < 1 { - continue - } - field = v.Field(0) - sfield = v.Type().Field(0) - } - - protoTag := sfield.Tag.Get("protobuf") - if protoTag == "" { - continue - } - var prop proto.Properties - prop.Init(sfield.Type, sfield.Name, protoTag, &sfield) - - switch field.Kind() { - case reflect.Map: - if field.IsNil() { - continue - } - // Check each map value. - keys := field.MapKeys() - for _, k := range keys { - v := field.MapIndex(k) - if err := checkRequiredFieldsInValue(v); err != nil { - return err - } - } - case reflect.Slice: - // Handle non-repeated type, e.g. bytes. - if !prop.Repeated { - if prop.Required && field.IsNil() { - return fmt.Errorf("required field %q is not set", prop.Name) - } - continue - } - - // Handle repeated type. - if field.IsNil() { - continue - } - // Check each slice item. - for i := 0; i < field.Len(); i++ { - v := field.Index(i) - if err := checkRequiredFieldsInValue(v); err != nil { - return err - } - } - case reflect.Ptr: - if field.IsNil() { - if prop.Required { - return fmt.Errorf("required field %q is not set", prop.Name) - } - continue - } - if err := checkRequiredFieldsInValue(field); err != nil { - return err - } - } - } - - // Handle proto2 extensions. - for _, ext := range proto.RegisteredExtensions(pb) { - if !proto.HasExtension(pb, ext) { - continue - } - ep, err := proto.GetExtension(pb, ext) - if err != nil { - return err - } - err = checkRequiredFieldsInValue(reflect.ValueOf(ep)) - if err != nil { - return err - } - } - - return nil -} - -func checkRequiredFieldsInValue(v reflect.Value) error { - if pm, ok := v.Interface().(proto.Message); ok { - return checkRequiredFields(pm) - } - return nil -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test.go b/examples/github.com/golang/protobuf/jsonpb/jsonpb_test.go deleted file mode 100755 index c9934d9..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test.go +++ /dev/null @@ -1,1150 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package jsonpb - -import ( - "bytes" - "encoding/json" - "io" - "math" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - "github.com/golang/protobuf/ptypes" - anypb "github.com/golang/protobuf/ptypes/any" - durpb "github.com/golang/protobuf/ptypes/duration" - stpb "github.com/golang/protobuf/ptypes/struct" - tspb "github.com/golang/protobuf/ptypes/timestamp" - wpb "github.com/golang/protobuf/ptypes/wrappers" -) - -var ( - marshaler = Marshaler{} - - marshalerAllOptions = Marshaler{ - Indent: " ", - } - - simpleObject = &pb.Simple{ - OInt32: proto.Int32(-32), - OInt64: proto.Int64(-6400000000), - OUint32: proto.Uint32(32), - OUint64: proto.Uint64(6400000000), - OSint32: proto.Int32(-13), - OSint64: proto.Int64(-2600000000), - OFloat: proto.Float32(3.14), - ODouble: proto.Float64(6.02214179e23), - OBool: proto.Bool(true), - OString: proto.String("hello \"there\""), - OBytes: []byte("beep boop"), - } - - simpleObjectJSON = `{` + - `"oBool":true,` + - `"oInt32":-32,` + - `"oInt64":"-6400000000",` + - `"oUint32":32,` + - `"oUint64":"6400000000",` + - `"oSint32":-13,` + - `"oSint64":"-2600000000",` + - `"oFloat":3.14,` + - `"oDouble":6.02214179e+23,` + - `"oString":"hello \"there\"",` + - `"oBytes":"YmVlcCBib29w"` + - `}` - - simpleObjectPrettyJSON = `{ - "oBool": true, - "oInt32": -32, - "oInt64": "-6400000000", - "oUint32": 32, - "oUint64": "6400000000", - "oSint32": -13, - "oSint64": "-2600000000", - "oFloat": 3.14, - "oDouble": 6.02214179e+23, - "oString": "hello \"there\"", - "oBytes": "YmVlcCBib29w" -}` - - repeatsObject = &pb.Repeats{ - RBool: []bool{true, false, true}, - RInt32: []int32{-3, -4, -5}, - RInt64: []int64{-123456789, -987654321}, - RUint32: []uint32{1, 2, 3}, - RUint64: []uint64{6789012345, 3456789012}, - RSint32: []int32{-1, -2, -3}, - RSint64: []int64{-6789012345, -3456789012}, - RFloat: []float32{3.14, 6.28}, - RDouble: []float64{299792458 * 1e20, 6.62606957e-34}, - RString: []string{"happy", "days"}, - RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, - } - - repeatsObjectJSON = `{` + - `"rBool":[true,false,true],` + - `"rInt32":[-3,-4,-5],` + - `"rInt64":["-123456789","-987654321"],` + - `"rUint32":[1,2,3],` + - `"rUint64":["6789012345","3456789012"],` + - `"rSint32":[-1,-2,-3],` + - `"rSint64":["-6789012345","-3456789012"],` + - `"rFloat":[3.14,6.28],` + - `"rDouble":[2.99792458e+28,6.62606957e-34],` + - `"rString":["happy","days"],` + - `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` + - `}` - - repeatsObjectPrettyJSON = `{ - "rBool": [ - true, - false, - true - ], - "rInt32": [ - -3, - -4, - -5 - ], - "rInt64": [ - "-123456789", - "-987654321" - ], - "rUint32": [ - 1, - 2, - 3 - ], - "rUint64": [ - "6789012345", - "3456789012" - ], - "rSint32": [ - -1, - -2, - -3 - ], - "rSint64": [ - "-6789012345", - "-3456789012" - ], - "rFloat": [ - 3.14, - 6.28 - ], - "rDouble": [ - 2.99792458e+28, - 6.62606957e-34 - ], - "rString": [ - "happy", - "days" - ], - "rBytes": [ - "c2tpdHRsZXM=", - "bSZtJ3M=" - ] -}` - - innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} - innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} - innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} - innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} - complexObject = &pb.Widget{ - Color: pb.Widget_GREEN.Enum(), - RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, - Simple: innerSimple, - RSimple: []*pb.Simple{innerSimple, innerSimple2}, - Repeats: innerRepeats, - RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, - } - - complexObjectJSON = `{"color":"GREEN",` + - `"rColor":["RED","GREEN","BLUE"],` + - `"simple":{"oInt32":-32},` + - `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` + - `"repeats":{"rString":["roses","red"]},` + - `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` + - `}` - - complexObjectPrettyJSON = `{ - "color": "GREEN", - "rColor": [ - "RED", - "GREEN", - "BLUE" - ], - "simple": { - "oInt32": -32 - }, - "rSimple": [ - { - "oInt32": -32 - }, - { - "oInt64": "25" - } - ], - "repeats": { - "rString": [ - "roses", - "red" - ] - }, - "rRepeats": [ - { - "rString": [ - "roses", - "red" - ] - }, - { - "rString": [ - "violets", - "blue" - ] - } - ] -}` - - colorPrettyJSON = `{ - "color": 2 -}` - - colorListPrettyJSON = `{ - "color": 1000, - "rColor": [ - "RED" - ] -}` - - nummyPrettyJSON = `{ - "nummy": { - "1": 2, - "3": 4 - } -}` - - objjyPrettyJSON = `{ - "objjy": { - "1": { - "dub": 1 - } - } -}` - realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} - realNumberName = "Pi" - complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} - realNumberJSON = `{` + - `"value":3.14159265359,` + - `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + - `"[jsonpb.name]":"Pi"` + - `}` - - anySimple = &pb.KnownTypes{ - An: &anypb.Any{ - TypeUrl: "something.example.com/jsonpb.Simple", - Value: []byte{ - // &pb.Simple{OBool:true} - 1 << 3, 1, - }, - }, - } - anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}` - anySimplePrettyJSON = `{ - "an": { - "@type": "something.example.com/jsonpb.Simple", - "oBool": true - } -}` - - anyWellKnown = &pb.KnownTypes{ - An: &anypb.Any{ - TypeUrl: "type.googleapis.com/google.protobuf.Duration", - Value: []byte{ - // &durpb.Duration{Seconds: 1, Nanos: 212000000 } - 1 << 3, 1, // seconds - 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos - }, - }, - } - anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}` - anyWellKnownPrettyJSON = `{ - "an": { - "@type": "type.googleapis.com/google.protobuf.Duration", - "value": "1.212s" - } -}` - - nonFinites = &pb.NonFinites{ - FNan: proto.Float32(float32(math.NaN())), - FPinf: proto.Float32(float32(math.Inf(1))), - FNinf: proto.Float32(float32(math.Inf(-1))), - DNan: proto.Float64(float64(math.NaN())), - DPinf: proto.Float64(float64(math.Inf(1))), - DNinf: proto.Float64(float64(math.Inf(-1))), - } - nonFinitesJSON = `{` + - `"fNan":"NaN",` + - `"fPinf":"Infinity",` + - `"fNinf":"-Infinity",` + - `"dNan":"NaN",` + - `"dPinf":"Infinity",` + - `"dNinf":"-Infinity"` + - `}` -) - -func init() { - if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { - panic(err) - } - if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { - panic(err) - } -} - -var marshalingTests = []struct { - desc string - marshaler Marshaler - pb proto.Message - json string -}{ - {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, - {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, - {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON}, - {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, - {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, - {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, - {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, - {"enum-string flat object", Marshaler{}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, - {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, - &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, - {"unknown enum value object", marshalerAllOptions, - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, - {"repeated proto3 enum", Marshaler{}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":["PUNS","SLAPSTICK"]}`}, - {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true}, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}, - `{"rFunny":[1,2]}`}, - {"empty value", marshaler, &pb.Simple3{}, `{}`}, - {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, - {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`}, - {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`}, - {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`}, - {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, - {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, - {"map", marshaler, - &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, - `{"strry":{"\"one\"":"two","three":"four"}}`}, - {"map", marshaler, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, - {"map", marshalerAllOptions, - &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON}, - {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, - `{"buggy":{"1234":"yup"}}`}, - {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, - // TODO: This is broken. - //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`}, - {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`}, - {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`}, - {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, - `{"mInt64Str":{"213":"cat"}}`}, - {"proto2 map", marshaler, - &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}}, - `{"mBoolSimple":{"true":{"oInt32":1}}}`}, - {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, - {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`}, - {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)}, - `{"o_int32":4}`}, - {"proto2 extension", marshaler, realNumber, realNumberJSON}, - {"Any with message", marshaler, anySimple, anySimpleJSON}, - {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON}, - {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON}, - {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON}, - {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3s"}`}, - {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3, Nanos: 1e6}}, `{"dur":"3.001s"}`}, - {"Duration beyond float64 precision", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 100000000, Nanos: 1}}, `{"dur":"100000000.000000001s"}`}, - {"negative Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: -123, Nanos: -456}}, `{"dur":"-123.000000456s"}`}, - {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{ - Fields: map[string]*stpb.Value{ - "one": {Kind: &stpb.Value_StringValue{"loneliest number"}}, - "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}, - }, - }}, `{"st":{"one":"loneliest number","two":null}}`}, - {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`}, - {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_NullValue{}}, - {Kind: &stpb.Value_NumberValue{3}}, - {Kind: &stpb.Value_BoolValue{true}}, - }}}, `{"lv":["x",null,3,true]}`}, - {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`}, - {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}, `{"ts":"2014-05-13T16:53:20Z"}`}, - {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`}, - {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`}, - {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`}, - {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{ - Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, - }}}, - {Kind: &stpb.Value_StringValue{"z"}}, - }, - }}}, - }, - }}, - }}, `{"val":["x",[["y"],"z"]]}`}, - - {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`}, - {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`}, - {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`}, - {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`}, - {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`}, - {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`}, - {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`}, - {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`}, - {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`}, - - {"required", marshaler, &pb.MsgWithRequired{Str: proto.String("hello")}, `{"str":"hello"}`}, - {"required bytes", marshaler, &pb.MsgWithRequiredBytes{Byts: []byte{}}, `{"byts":""}`}, -} - -func TestMarshaling(t *testing.T) { - for _, tt := range marshalingTests { - json, err := tt.marshaler.MarshalToString(tt.pb) - if err != nil { - t.Errorf("%s: marshaling error: %v", tt.desc, err) - } else if tt.json != json { - t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) - } - } -} - -func TestMarshalingNil(t *testing.T) { - var msg *pb.Simple - m := &Marshaler{} - if _, err := m.MarshalToString(msg); err == nil { - t.Errorf("mashaling nil returned no error") - } -} - -func TestMarshalIllegalTime(t *testing.T) { - tests := []struct { - pb proto.Message - fail bool - }{ - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 0}}, false}, - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 0}}, false}, - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: -1}}, true}, - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: 1}}, true}, - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: 1, Nanos: 1000000000}}, true}, - {&pb.KnownTypes{Dur: &durpb.Duration{Seconds: -1, Nanos: -1000000000}}, true}, - {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1}}, false}, - {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: -1}}, true}, - {&pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 1, Nanos: 1000000000}}, true}, - } - for _, tt := range tests { - _, err := marshaler.MarshalToString(tt.pb) - if err == nil && tt.fail { - t.Errorf("marshaler.MarshalToString(%v) = _, ; want _, ", tt.pb) - } - if err != nil && !tt.fail { - t.Errorf("marshaler.MarshalToString(%v) = _, %v; want _, ", tt.pb, err) - } - } -} - -func TestMarshalJSONPBMarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - msg := dynamicMessage{rawJson: rawJson} - str, err := new(Marshaler).MarshalToString(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err) - } - if str != rawJson { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson) - } -} - -func TestMarshalAnyJSONPBMarshaler(t *testing.T) { - msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`} - a, err := ptypes.MarshalAny(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling to Any: %v", err) - } - str, err := new(Marshaler).MarshalToString(a) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err) - } - // after custom marshaling, it's round-tripped through JSON decoding/encoding already, - // so the keys are sorted, whitespace is compacted, and "@type" key has been added - expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}` - if str != expected { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected) - } -} - -func TestMarshalWithCustomValidation(t *testing.T) { - msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, dummy: &dynamicMessage{}} - - js, err := new(Marshaler).MarshalToString(&msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshalling to json: %v", err) - } - err = Unmarshal(strings.NewReader(js), &msg) - if err != nil { - t.Errorf("an unexpected error occurred when unmarshalling from json: %v", err) - } -} - -// Test marshaling message containing unset required fields should produce error. -func TestMarshalUnsetRequiredFields(t *testing.T) { - msgExt := &pb.Real{} - proto.SetExtension(msgExt, pb.E_Extm, &pb.MsgWithRequired{}) - - tests := []struct { - desc string - marshaler *Marshaler - pb proto.Message - }{ - { - desc: "direct required field", - marshaler: &Marshaler{}, - pb: &pb.MsgWithRequired{}, - }, - { - desc: "direct required field + emit defaults", - marshaler: &Marshaler{EmitDefaults: true}, - pb: &pb.MsgWithRequired{}, - }, - { - desc: "indirect required field", - marshaler: &Marshaler{}, - pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}}, - }, - { - desc: "indirect required field + emit defaults", - marshaler: &Marshaler{EmitDefaults: true}, - pb: &pb.MsgWithIndirectRequired{Subm: &pb.MsgWithRequired{}}, - }, - { - desc: "direct required wkt field", - marshaler: &Marshaler{}, - pb: &pb.MsgWithRequiredWKT{}, - }, - { - desc: "direct required wkt field + emit defaults", - marshaler: &Marshaler{EmitDefaults: true}, - pb: &pb.MsgWithRequiredWKT{}, - }, - { - desc: "direct required bytes field", - marshaler: &Marshaler{}, - pb: &pb.MsgWithRequiredBytes{}, - }, - { - desc: "required in map value", - marshaler: &Marshaler{}, - pb: &pb.MsgWithIndirectRequired{ - MapField: map[string]*pb.MsgWithRequired{ - "key": {}, - }, - }, - }, - { - desc: "required in repeated item", - marshaler: &Marshaler{}, - pb: &pb.MsgWithIndirectRequired{ - SliceField: []*pb.MsgWithRequired{ - {Str: proto.String("hello")}, - {}, - }, - }, - }, - { - desc: "required inside oneof", - marshaler: &Marshaler{}, - pb: &pb.MsgWithOneof{ - Union: &pb.MsgWithOneof_MsgWithRequired{&pb.MsgWithRequired{}}, - }, - }, - { - desc: "required inside extension", - marshaler: &Marshaler{}, - pb: msgExt, - }, - } - - for _, tc := range tests { - if _, err := tc.marshaler.MarshalToString(tc.pb); err == nil { - t.Errorf("%s: expecting error in marshaling with unset required fields %+v", tc.desc, tc.pb) - } - } -} - -var unmarshalingTests = []struct { - desc string - unmarshaler Unmarshaler - json string - pb proto.Message -}{ - {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject}, - {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject}, - {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject}, - {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject}, - {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject}, - {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject}, - {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, - {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)}, - {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"unknown enum value object", - Unmarshaler{}, - "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", - &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, - {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`, - &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ - proto3pb.Message_PUNS, - proto3pb.Message_SLAPSTICK, - }}}, - {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, - {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, - {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}}, - {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}}, - {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}}, - {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, - {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, - {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}}, - {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber}, - {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple}, - {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple}, - {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown}, - {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown}, - // TODO: This is broken. - //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, - {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}}, - {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, - {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, - {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, - {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, - {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, - - {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}}, - {"Duration", Unmarshaler{}, `{"dur":"4s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 4}}}, - {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}}, - {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}}, - {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 0}}}, - {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}}, - {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}}, - {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}}, - {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}}, - {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}}, - {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ - "a": {Kind: &stpb.Value_StringValue{"x"}}, - "b": {Kind: &stpb.Value_NullValue{}}, - "c": {Kind: &stpb.Value_NumberValue{3}}, - "d": {Kind: &stpb.Value_BoolValue{true}}, - }}}}, - {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ - "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{ - "b": {Kind: &stpb.Value_NumberValue{1}}, - "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}}, - {Kind: &stpb.Value_StringValue{"f"}}, - }}}}, - }}}}, - }}}}, - {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}}, - {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}}, - {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_NullValue{}}, - {Kind: &stpb.Value_NumberValue{3}}, - {Kind: &stpb.Value_BoolValue{true}}, - }}}}, - {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}}, - {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}}, - {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}}, - {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}}, - {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}}, - {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{ - Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_StringValue{"x"}}, - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{ - {Kind: &stpb.Value_ListValue{&stpb.ListValue{ - Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, - }}}, - {Kind: &stpb.Value_StringValue{"z"}}, - }, - }}}, - }, - }}}}}, - - {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}}, - {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}}, - {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}}, - {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}}, - {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}}, - {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}}, - {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}}, - {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}}, - {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}}, - - // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct. - {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}}, - {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}}, - {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}}, - {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}}, - {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}}, - {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}}, - {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}}, - {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}}, - {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}}, - - {"required", Unmarshaler{}, `{"str":"hello"}`, &pb.MsgWithRequired{Str: proto.String("hello")}}, - {"required bytes", Unmarshaler{}, `{"byts": []}`, &pb.MsgWithRequiredBytes{Byts: []byte{}}}, -} - -func TestUnmarshaling(t *testing.T) { - for _, tt := range unmarshalingTests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } -} - -func TestUnmarshalNullArray(t *testing.T) { - var repeats pb.Repeats - if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(repeats, pb.Repeats{}) { - t.Errorf("got non-nil fields in [%#v]", repeats) - } -} - -func TestUnmarshalNullObject(t *testing.T) { - var maps pb.Maps - if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(maps, pb.Maps{}) { - t.Errorf("got non-nil fields in [%#v]", maps) - } -} - -func TestUnmarshalNext(t *testing.T) { - // We only need to check against a few, not all of them. - tests := unmarshalingTests[:5] - - // Create a buffer with many concatenated JSON objects. - var b bytes.Buffer - for _, tt := range tests { - b.WriteString(tt.json) - } - - dec := json.NewDecoder(&b) - for _, tt := range tests { - // Make a new instance of the type of our expected object. - p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) - - err := tt.unmarshaler.UnmarshalNext(dec, p) - if err != nil { - t.Errorf("%s: %v", tt.desc, err) - continue - } - - // For easier diffs, compare text strings of the protos. - exp := proto.MarshalTextString(tt.pb) - act := proto.MarshalTextString(p) - if string(exp) != string(act) { - t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) - } - } - - p := &pb.Simple{} - err := new(Unmarshaler).UnmarshalNext(dec, p) - if err != io.EOF { - t.Errorf("eof: got %v, expected io.EOF", err) - } -} - -var unmarshalingShouldError = []struct { - desc string - in string - pb proto.Message -}{ - {"a value", "666", new(pb.Simple)}, - {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, - {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)}, - {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, -} - -func TestUnmarshalingBadInput(t *testing.T) { - for _, tt := range unmarshalingShouldError { - err := UnmarshalString(tt.in, tt.pb) - if err == nil { - t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) - } - } -} - -type funcResolver func(turl string) (proto.Message, error) - -func (fn funcResolver) Resolve(turl string) (proto.Message, error) { - return fn(turl) -} - -func TestAnyWithCustomResolver(t *testing.T) { - var resolvedTypeUrls []string - resolver := funcResolver(func(turl string) (proto.Message, error) { - resolvedTypeUrls = append(resolvedTypeUrls, turl) - return new(pb.Simple), nil - }) - msg := &pb.Simple{ - OBytes: []byte{1, 2, 3, 4}, - OBool: proto.Bool(true), - OString: proto.String("foobar"), - OInt64: proto.Int64(1020304), - } - msgBytes, err := proto.Marshal(msg) - if err != nil { - t.Errorf("an unexpected error occurred when marshaling message: %v", err) - } - // make an Any with a type URL that won't resolve w/out custom resolver - any := &anypb.Any{ - TypeUrl: "https://foobar.com/some.random.MessageKind", - Value: msgBytes, - } - - m := Marshaler{AnyResolver: resolver} - js, err := m.MarshalToString(any) - if err != nil { - t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err) - } - if len(resolvedTypeUrls) != 1 { - t.Errorf("custom resolver was not invoked during marshaling") - } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" { - t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind") - } - wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}` - if js != wanted { - t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted) - } - - u := Unmarshaler{AnyResolver: resolver} - roundTrip := &anypb.Any{} - err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip) - if err != nil { - t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err) - } - if len(resolvedTypeUrls) != 2 { - t.Errorf("custom resolver was not invoked during marshaling") - } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" { - t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind") - } - if !proto.Equal(any, roundTrip) { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any) - } -} - -func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` - var msg dynamicMessage - if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - if msg.rawJson != rawJson { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson) - } -} - -func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) { - rawJson := `{"stringField":null}` - var ptrFieldMsg ptrFieldMessage - if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil { - t.Errorf("unmarshal error: %v", err) - } - - want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}} - if !proto.Equal(&ptrFieldMsg, &want) { - t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want) - } -} - -func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) { - rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }` - var got anypb.Any - if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil { - t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) - } - - dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`} - var want anypb.Any - if b, err := proto.Marshal(dm); err != nil { - t.Errorf("an unexpected error occurred when marshaling message: %v", err) - } else { - want.TypeUrl = "blah.com/" + dynamicMessageName - want.Value = b - } - - if !proto.Equal(&got, &want) { - t.Errorf("message contents not set correctly after unmarshalling JSON: got %v, wanted %v", got, want) - } -} - -const ( - dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage" -) - -func init() { - // we register the custom type below so that we can use it in Any types - proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName) -} - -type ptrFieldMessage struct { - StringField *stringField `protobuf:"bytes,1,opt,name=stringField"` -} - -func (m *ptrFieldMessage) Reset() { -} - -func (m *ptrFieldMessage) String() string { - return m.StringField.StringValue -} - -func (m *ptrFieldMessage) ProtoMessage() { -} - -type stringField struct { - IsSet bool `protobuf:"varint,1,opt,name=isSet"` - StringValue string `protobuf:"bytes,2,opt,name=stringValue"` -} - -func (s *stringField) Reset() { -} - -func (s *stringField) String() string { - return s.StringValue -} - -func (s *stringField) ProtoMessage() { -} - -func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { - s.IsSet = true - s.StringValue = string(js) - return nil -} - -// dynamicMessage implements protobuf.Message but is not a normal generated message type. -// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support. -type dynamicMessage struct { - rawJson string `protobuf:"bytes,1,opt,name=rawJson"` - - // an unexported nested message is present just to ensure that it - // won't result in a panic (see issue #509) - dummy *dynamicMessage `protobuf:"bytes,2,opt,name=dummy"` -} - -func (m *dynamicMessage) Reset() { - m.rawJson = "{}" -} - -func (m *dynamicMessage) String() string { - return m.rawJson -} - -func (m *dynamicMessage) ProtoMessage() { -} - -func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) { - return []byte(m.rawJson), nil -} - -func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { - m.rawJson = string(js) - return nil -} - -// Test unmarshaling message containing unset required fields should produce error. -func TestUnmarshalUnsetRequiredFields(t *testing.T) { - tests := []struct { - desc string - pb proto.Message - json string - }{ - { - desc: "direct required field missing", - pb: &pb.MsgWithRequired{}, - json: `{}`, - }, - { - desc: "direct required field set to null", - pb: &pb.MsgWithRequired{}, - json: `{"str": null}`, - }, - { - desc: "indirect required field missing", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"subm": {}}`, - }, - { - desc: "indirect required field set to null", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"subm": {"str": null}}`, - }, - { - desc: "direct required bytes field missing", - pb: &pb.MsgWithRequiredBytes{}, - json: `{}`, - }, - { - desc: "direct required bytes field set to null", - pb: &pb.MsgWithRequiredBytes{}, - json: `{"byts": null}`, - }, - { - desc: "direct required wkt field missing", - pb: &pb.MsgWithRequiredWKT{}, - json: `{}`, - }, - { - desc: "direct required wkt field set to null", - pb: &pb.MsgWithRequiredWKT{}, - json: `{"str": null}`, - }, - { - desc: "any containing message with required field set to null", - pb: &pb.KnownTypes{}, - json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired", "str": null}}`, - }, - { - desc: "any containing message with missing required field", - pb: &pb.KnownTypes{}, - json: `{"an": {"@type": "example.com/jsonpb.MsgWithRequired"}}`, - }, - { - desc: "missing required in map value", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"map_field": {"a": {}, "b": {"str": "hi"}}}`, - }, - { - desc: "required in map value set to null", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"map_field": {"a": {"str": "hello"}, "b": {"str": null}}}`, - }, - { - desc: "missing required in slice item", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"slice_field": [{}, {"str": "hi"}]}`, - }, - { - desc: "required in slice item set to null", - pb: &pb.MsgWithIndirectRequired{}, - json: `{"slice_field": [{"str": "hello"}, {"str": null}]}`, - }, - { - desc: "required inside oneof missing", - pb: &pb.MsgWithOneof{}, - json: `{"msgWithRequired": {}}`, - }, - { - desc: "required inside oneof set to null", - pb: &pb.MsgWithOneof{}, - json: `{"msgWithRequired": {"str": null}}`, - }, - { - desc: "required field in extension missing", - pb: &pb.Real{}, - json: `{"[jsonpb.extm]":{}}`, - }, - { - desc: "required field in extension set to null", - pb: &pb.Real{}, - json: `{"[jsonpb.extm]":{"str": null}}`, - }, - } - - for _, tc := range tests { - if err := UnmarshalString(tc.json, tc.pb); err == nil { - t.Errorf("%s: expecting error in unmarshaling with unset required fields %s", tc.desc, tc.json) - } - } -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go b/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go deleted file mode 100755 index 1bcce02..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go +++ /dev/null @@ -1,368 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: more_test_objects.proto - -package jsonpb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Numeral int32 - -const ( - Numeral_UNKNOWN Numeral = 0 - Numeral_ARABIC Numeral = 1 - Numeral_ROMAN Numeral = 2 -) - -var Numeral_name = map[int32]string{ - 0: "UNKNOWN", - 1: "ARABIC", - 2: "ROMAN", -} -var Numeral_value = map[string]int32{ - "UNKNOWN": 0, - "ARABIC": 1, - "ROMAN": 2, -} - -func (x Numeral) String() string { - return proto.EnumName(Numeral_name, int32(x)) -} -func (Numeral) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0} -} - -type Simple3 struct { - Dub float64 `protobuf:"fixed64,1,opt,name=dub" json:"dub,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Simple3) Reset() { *m = Simple3{} } -func (m *Simple3) String() string { return proto.CompactTextString(m) } -func (*Simple3) ProtoMessage() {} -func (*Simple3) Descriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{0} -} -func (m *Simple3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Simple3.Unmarshal(m, b) -} -func (m *Simple3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Simple3.Marshal(b, m, deterministic) -} -func (dst *Simple3) XXX_Merge(src proto.Message) { - xxx_messageInfo_Simple3.Merge(dst, src) -} -func (m *Simple3) XXX_Size() int { - return xxx_messageInfo_Simple3.Size(m) -} -func (m *Simple3) XXX_DiscardUnknown() { - xxx_messageInfo_Simple3.DiscardUnknown(m) -} - -var xxx_messageInfo_Simple3 proto.InternalMessageInfo - -func (m *Simple3) GetDub() float64 { - if m != nil { - return m.Dub - } - return 0 -} - -type SimpleSlice3 struct { - Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} } -func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) } -func (*SimpleSlice3) ProtoMessage() {} -func (*SimpleSlice3) Descriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{1} -} -func (m *SimpleSlice3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleSlice3.Unmarshal(m, b) -} -func (m *SimpleSlice3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleSlice3.Marshal(b, m, deterministic) -} -func (dst *SimpleSlice3) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleSlice3.Merge(dst, src) -} -func (m *SimpleSlice3) XXX_Size() int { - return xxx_messageInfo_SimpleSlice3.Size(m) -} -func (m *SimpleSlice3) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleSlice3.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleSlice3 proto.InternalMessageInfo - -func (m *SimpleSlice3) GetSlices() []string { - if m != nil { - return m.Slices - } - return nil -} - -type SimpleMap3 struct { - Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleMap3) Reset() { *m = SimpleMap3{} } -func (m *SimpleMap3) String() string { return proto.CompactTextString(m) } -func (*SimpleMap3) ProtoMessage() {} -func (*SimpleMap3) Descriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{2} -} -func (m *SimpleMap3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleMap3.Unmarshal(m, b) -} -func (m *SimpleMap3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleMap3.Marshal(b, m, deterministic) -} -func (dst *SimpleMap3) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleMap3.Merge(dst, src) -} -func (m *SimpleMap3) XXX_Size() int { - return xxx_messageInfo_SimpleMap3.Size(m) -} -func (m *SimpleMap3) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleMap3.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleMap3 proto.InternalMessageInfo - -func (m *SimpleMap3) GetStringy() map[string]string { - if m != nil { - return m.Stringy - } - return nil -} - -type SimpleNull3 struct { - Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleNull3) Reset() { *m = SimpleNull3{} } -func (m *SimpleNull3) String() string { return proto.CompactTextString(m) } -func (*SimpleNull3) ProtoMessage() {} -func (*SimpleNull3) Descriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{3} -} -func (m *SimpleNull3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleNull3.Unmarshal(m, b) -} -func (m *SimpleNull3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleNull3.Marshal(b, m, deterministic) -} -func (dst *SimpleNull3) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleNull3.Merge(dst, src) -} -func (m *SimpleNull3) XXX_Size() int { - return xxx_messageInfo_SimpleNull3.Size(m) -} -func (m *SimpleNull3) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleNull3.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleNull3 proto.InternalMessageInfo - -func (m *SimpleNull3) GetSimple() *Simple3 { - if m != nil { - return m.Simple - } - return nil -} - -type Mappy struct { - Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=jsonpb.Numeral"` - S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Mappy) Reset() { *m = Mappy{} } -func (m *Mappy) String() string { return proto.CompactTextString(m) } -func (*Mappy) ProtoMessage() {} -func (*Mappy) Descriptor() ([]byte, []int) { - return fileDescriptor_more_test_objects_bef0d79b901f4c4a, []int{4} -} -func (m *Mappy) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Mappy.Unmarshal(m, b) -} -func (m *Mappy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Mappy.Marshal(b, m, deterministic) -} -func (dst *Mappy) XXX_Merge(src proto.Message) { - xxx_messageInfo_Mappy.Merge(dst, src) -} -func (m *Mappy) XXX_Size() int { - return xxx_messageInfo_Mappy.Size(m) -} -func (m *Mappy) XXX_DiscardUnknown() { - xxx_messageInfo_Mappy.DiscardUnknown(m) -} - -var xxx_messageInfo_Mappy proto.InternalMessageInfo - -func (m *Mappy) GetNummy() map[int64]int32 { - if m != nil { - return m.Nummy - } - return nil -} - -func (m *Mappy) GetStrry() map[string]string { - if m != nil { - return m.Strry - } - return nil -} - -func (m *Mappy) GetObjjy() map[int32]*Simple3 { - if m != nil { - return m.Objjy - } - return nil -} - -func (m *Mappy) GetBuggy() map[int64]string { - if m != nil { - return m.Buggy - } - return nil -} - -func (m *Mappy) GetBooly() map[bool]bool { - if m != nil { - return m.Booly - } - return nil -} - -func (m *Mappy) GetEnumy() map[string]Numeral { - if m != nil { - return m.Enumy - } - return nil -} - -func (m *Mappy) GetS32Booly() map[int32]bool { - if m != nil { - return m.S32Booly - } - return nil -} - -func (m *Mappy) GetS64Booly() map[int64]bool { - if m != nil { - return m.S64Booly - } - return nil -} - -func (m *Mappy) GetU32Booly() map[uint32]bool { - if m != nil { - return m.U32Booly - } - return nil -} - -func (m *Mappy) GetU64Booly() map[uint64]bool { - if m != nil { - return m.U64Booly - } - return nil -} - -func init() { - proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3") - proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3") - proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3") - proto.RegisterMapType((map[string]string)(nil), "jsonpb.SimpleMap3.StringyEntry") - proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3") - proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy") - proto.RegisterMapType((map[bool]bool)(nil), "jsonpb.Mappy.BoolyEntry") - proto.RegisterMapType((map[int64]string)(nil), "jsonpb.Mappy.BuggyEntry") - proto.RegisterMapType((map[string]Numeral)(nil), "jsonpb.Mappy.EnumyEntry") - proto.RegisterMapType((map[int64]int32)(nil), "jsonpb.Mappy.NummyEntry") - proto.RegisterMapType((map[int32]*Simple3)(nil), "jsonpb.Mappy.ObjjyEntry") - proto.RegisterMapType((map[int32]bool)(nil), "jsonpb.Mappy.S32boolyEntry") - proto.RegisterMapType((map[int64]bool)(nil), "jsonpb.Mappy.S64boolyEntry") - proto.RegisterMapType((map[string]string)(nil), "jsonpb.Mappy.StrryEntry") - proto.RegisterMapType((map[uint32]bool)(nil), "jsonpb.Mappy.U32boolyEntry") - proto.RegisterMapType((map[uint64]bool)(nil), "jsonpb.Mappy.U64boolyEntry") - proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value) -} - -func init() { - proto.RegisterFile("more_test_objects.proto", fileDescriptor_more_test_objects_bef0d79b901f4c4a) -} - -var fileDescriptor_more_test_objects_bef0d79b901f4c4a = []byte{ - // 526 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c, - 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0, - 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2, - 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48, - 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3, - 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79, - 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e, - 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94, - 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e, - 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5, - 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13, - 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3, - 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe, - 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46, - 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7, - 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01, - 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0, - 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2, - 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93, - 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8, - 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7, - 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15, - 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11, - 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f, - 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b, - 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf, - 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda, - 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43, - 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9, - 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0, - 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe, - 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe, - 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto b/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto deleted file mode 100755 index d254fa5..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto +++ /dev/null @@ -1,69 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package jsonpb; - -message Simple3 { - double dub = 1; -} - -message SimpleSlice3 { - repeated string slices = 1; -} - -message SimpleMap3 { - map stringy = 1; -} - -message SimpleNull3 { - Simple3 simple = 1; -} - -enum Numeral { - UNKNOWN = 0; - ARABIC = 1; - ROMAN = 2; -} - -message Mappy { - map nummy = 1; - map strry = 2; - map objjy = 3; - map buggy = 4; - map booly = 5; - map enumy = 6; - map s32booly = 7; - map s64booly = 8; - map u32booly = 9; - map u64booly = 10; -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go b/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go deleted file mode 100755 index d9e24db..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go +++ /dev/null @@ -1,1278 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: test_objects.proto - -package jsonpb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" -import duration "github.com/golang/protobuf/ptypes/duration" -import _struct "github.com/golang/protobuf/ptypes/struct" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" -import wrappers "github.com/golang/protobuf/ptypes/wrappers" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Widget_Color int32 - -const ( - Widget_RED Widget_Color = 0 - Widget_GREEN Widget_Color = 1 - Widget_BLUE Widget_Color = 2 -) - -var Widget_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Widget_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Widget_Color) Enum() *Widget_Color { - p := new(Widget_Color) - *p = x - return p -} -func (x Widget_Color) String() string { - return proto.EnumName(Widget_Color_name, int32(x)) -} -func (x *Widget_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Widget_Color_value, data, "Widget_Color") - if err != nil { - return err - } - *x = Widget_Color(value) - return nil -} -func (Widget_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{3, 0} -} - -// Test message for holding primitive types. -type Simple struct { - OBool *bool `protobuf:"varint,1,opt,name=o_bool,json=oBool" json:"o_bool,omitempty"` - OInt32 *int32 `protobuf:"varint,2,opt,name=o_int32,json=oInt32" json:"o_int32,omitempty"` - OInt64 *int64 `protobuf:"varint,3,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"` - OUint32 *uint32 `protobuf:"varint,4,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"` - OUint64 *uint64 `protobuf:"varint,5,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"` - OSint32 *int32 `protobuf:"zigzag32,6,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"` - OSint64 *int64 `protobuf:"zigzag64,7,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"` - OFloat *float32 `protobuf:"fixed32,8,opt,name=o_float,json=oFloat" json:"o_float,omitempty"` - ODouble *float64 `protobuf:"fixed64,9,opt,name=o_double,json=oDouble" json:"o_double,omitempty"` - OString *string `protobuf:"bytes,10,opt,name=o_string,json=oString" json:"o_string,omitempty"` - OBytes []byte `protobuf:"bytes,11,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Simple) Reset() { *m = Simple{} } -func (m *Simple) String() string { return proto.CompactTextString(m) } -func (*Simple) ProtoMessage() {} -func (*Simple) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{0} -} -func (m *Simple) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Simple.Unmarshal(m, b) -} -func (m *Simple) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Simple.Marshal(b, m, deterministic) -} -func (dst *Simple) XXX_Merge(src proto.Message) { - xxx_messageInfo_Simple.Merge(dst, src) -} -func (m *Simple) XXX_Size() int { - return xxx_messageInfo_Simple.Size(m) -} -func (m *Simple) XXX_DiscardUnknown() { - xxx_messageInfo_Simple.DiscardUnknown(m) -} - -var xxx_messageInfo_Simple proto.InternalMessageInfo - -func (m *Simple) GetOBool() bool { - if m != nil && m.OBool != nil { - return *m.OBool - } - return false -} - -func (m *Simple) GetOInt32() int32 { - if m != nil && m.OInt32 != nil { - return *m.OInt32 - } - return 0 -} - -func (m *Simple) GetOInt64() int64 { - if m != nil && m.OInt64 != nil { - return *m.OInt64 - } - return 0 -} - -func (m *Simple) GetOUint32() uint32 { - if m != nil && m.OUint32 != nil { - return *m.OUint32 - } - return 0 -} - -func (m *Simple) GetOUint64() uint64 { - if m != nil && m.OUint64 != nil { - return *m.OUint64 - } - return 0 -} - -func (m *Simple) GetOSint32() int32 { - if m != nil && m.OSint32 != nil { - return *m.OSint32 - } - return 0 -} - -func (m *Simple) GetOSint64() int64 { - if m != nil && m.OSint64 != nil { - return *m.OSint64 - } - return 0 -} - -func (m *Simple) GetOFloat() float32 { - if m != nil && m.OFloat != nil { - return *m.OFloat - } - return 0 -} - -func (m *Simple) GetODouble() float64 { - if m != nil && m.ODouble != nil { - return *m.ODouble - } - return 0 -} - -func (m *Simple) GetOString() string { - if m != nil && m.OString != nil { - return *m.OString - } - return "" -} - -func (m *Simple) GetOBytes() []byte { - if m != nil { - return m.OBytes - } - return nil -} - -// Test message for holding special non-finites primitives. -type NonFinites struct { - FNan *float32 `protobuf:"fixed32,1,opt,name=f_nan,json=fNan" json:"f_nan,omitempty"` - FPinf *float32 `protobuf:"fixed32,2,opt,name=f_pinf,json=fPinf" json:"f_pinf,omitempty"` - FNinf *float32 `protobuf:"fixed32,3,opt,name=f_ninf,json=fNinf" json:"f_ninf,omitempty"` - DNan *float64 `protobuf:"fixed64,4,opt,name=d_nan,json=dNan" json:"d_nan,omitempty"` - DPinf *float64 `protobuf:"fixed64,5,opt,name=d_pinf,json=dPinf" json:"d_pinf,omitempty"` - DNinf *float64 `protobuf:"fixed64,6,opt,name=d_ninf,json=dNinf" json:"d_ninf,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NonFinites) Reset() { *m = NonFinites{} } -func (m *NonFinites) String() string { return proto.CompactTextString(m) } -func (*NonFinites) ProtoMessage() {} -func (*NonFinites) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{1} -} -func (m *NonFinites) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NonFinites.Unmarshal(m, b) -} -func (m *NonFinites) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NonFinites.Marshal(b, m, deterministic) -} -func (dst *NonFinites) XXX_Merge(src proto.Message) { - xxx_messageInfo_NonFinites.Merge(dst, src) -} -func (m *NonFinites) XXX_Size() int { - return xxx_messageInfo_NonFinites.Size(m) -} -func (m *NonFinites) XXX_DiscardUnknown() { - xxx_messageInfo_NonFinites.DiscardUnknown(m) -} - -var xxx_messageInfo_NonFinites proto.InternalMessageInfo - -func (m *NonFinites) GetFNan() float32 { - if m != nil && m.FNan != nil { - return *m.FNan - } - return 0 -} - -func (m *NonFinites) GetFPinf() float32 { - if m != nil && m.FPinf != nil { - return *m.FPinf - } - return 0 -} - -func (m *NonFinites) GetFNinf() float32 { - if m != nil && m.FNinf != nil { - return *m.FNinf - } - return 0 -} - -func (m *NonFinites) GetDNan() float64 { - if m != nil && m.DNan != nil { - return *m.DNan - } - return 0 -} - -func (m *NonFinites) GetDPinf() float64 { - if m != nil && m.DPinf != nil { - return *m.DPinf - } - return 0 -} - -func (m *NonFinites) GetDNinf() float64 { - if m != nil && m.DNinf != nil { - return *m.DNinf - } - return 0 -} - -// Test message for holding repeated primitives. -type Repeats struct { - RBool []bool `protobuf:"varint,1,rep,name=r_bool,json=rBool" json:"r_bool,omitempty"` - RInt32 []int32 `protobuf:"varint,2,rep,name=r_int32,json=rInt32" json:"r_int32,omitempty"` - RInt64 []int64 `protobuf:"varint,3,rep,name=r_int64,json=rInt64" json:"r_int64,omitempty"` - RUint32 []uint32 `protobuf:"varint,4,rep,name=r_uint32,json=rUint32" json:"r_uint32,omitempty"` - RUint64 []uint64 `protobuf:"varint,5,rep,name=r_uint64,json=rUint64" json:"r_uint64,omitempty"` - RSint32 []int32 `protobuf:"zigzag32,6,rep,name=r_sint32,json=rSint32" json:"r_sint32,omitempty"` - RSint64 []int64 `protobuf:"zigzag64,7,rep,name=r_sint64,json=rSint64" json:"r_sint64,omitempty"` - RFloat []float32 `protobuf:"fixed32,8,rep,name=r_float,json=rFloat" json:"r_float,omitempty"` - RDouble []float64 `protobuf:"fixed64,9,rep,name=r_double,json=rDouble" json:"r_double,omitempty"` - RString []string `protobuf:"bytes,10,rep,name=r_string,json=rString" json:"r_string,omitempty"` - RBytes [][]byte `protobuf:"bytes,11,rep,name=r_bytes,json=rBytes" json:"r_bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Repeats) Reset() { *m = Repeats{} } -func (m *Repeats) String() string { return proto.CompactTextString(m) } -func (*Repeats) ProtoMessage() {} -func (*Repeats) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{2} -} -func (m *Repeats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Repeats.Unmarshal(m, b) -} -func (m *Repeats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Repeats.Marshal(b, m, deterministic) -} -func (dst *Repeats) XXX_Merge(src proto.Message) { - xxx_messageInfo_Repeats.Merge(dst, src) -} -func (m *Repeats) XXX_Size() int { - return xxx_messageInfo_Repeats.Size(m) -} -func (m *Repeats) XXX_DiscardUnknown() { - xxx_messageInfo_Repeats.DiscardUnknown(m) -} - -var xxx_messageInfo_Repeats proto.InternalMessageInfo - -func (m *Repeats) GetRBool() []bool { - if m != nil { - return m.RBool - } - return nil -} - -func (m *Repeats) GetRInt32() []int32 { - if m != nil { - return m.RInt32 - } - return nil -} - -func (m *Repeats) GetRInt64() []int64 { - if m != nil { - return m.RInt64 - } - return nil -} - -func (m *Repeats) GetRUint32() []uint32 { - if m != nil { - return m.RUint32 - } - return nil -} - -func (m *Repeats) GetRUint64() []uint64 { - if m != nil { - return m.RUint64 - } - return nil -} - -func (m *Repeats) GetRSint32() []int32 { - if m != nil { - return m.RSint32 - } - return nil -} - -func (m *Repeats) GetRSint64() []int64 { - if m != nil { - return m.RSint64 - } - return nil -} - -func (m *Repeats) GetRFloat() []float32 { - if m != nil { - return m.RFloat - } - return nil -} - -func (m *Repeats) GetRDouble() []float64 { - if m != nil { - return m.RDouble - } - return nil -} - -func (m *Repeats) GetRString() []string { - if m != nil { - return m.RString - } - return nil -} - -func (m *Repeats) GetRBytes() [][]byte { - if m != nil { - return m.RBytes - } - return nil -} - -// Test message for holding enums and nested messages. -type Widget struct { - Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb.Widget_Color" json:"color,omitempty"` - RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb.Widget_Color" json:"r_color,omitempty"` - Simple *Simple `protobuf:"bytes,10,opt,name=simple" json:"simple,omitempty"` - RSimple []*Simple `protobuf:"bytes,11,rep,name=r_simple,json=rSimple" json:"r_simple,omitempty"` - Repeats *Repeats `protobuf:"bytes,20,opt,name=repeats" json:"repeats,omitempty"` - RRepeats []*Repeats `protobuf:"bytes,21,rep,name=r_repeats,json=rRepeats" json:"r_repeats,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Widget) Reset() { *m = Widget{} } -func (m *Widget) String() string { return proto.CompactTextString(m) } -func (*Widget) ProtoMessage() {} -func (*Widget) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{3} -} -func (m *Widget) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Widget.Unmarshal(m, b) -} -func (m *Widget) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Widget.Marshal(b, m, deterministic) -} -func (dst *Widget) XXX_Merge(src proto.Message) { - xxx_messageInfo_Widget.Merge(dst, src) -} -func (m *Widget) XXX_Size() int { - return xxx_messageInfo_Widget.Size(m) -} -func (m *Widget) XXX_DiscardUnknown() { - xxx_messageInfo_Widget.DiscardUnknown(m) -} - -var xxx_messageInfo_Widget proto.InternalMessageInfo - -func (m *Widget) GetColor() Widget_Color { - if m != nil && m.Color != nil { - return *m.Color - } - return Widget_RED -} - -func (m *Widget) GetRColor() []Widget_Color { - if m != nil { - return m.RColor - } - return nil -} - -func (m *Widget) GetSimple() *Simple { - if m != nil { - return m.Simple - } - return nil -} - -func (m *Widget) GetRSimple() []*Simple { - if m != nil { - return m.RSimple - } - return nil -} - -func (m *Widget) GetRepeats() *Repeats { - if m != nil { - return m.Repeats - } - return nil -} - -func (m *Widget) GetRRepeats() []*Repeats { - if m != nil { - return m.RRepeats - } - return nil -} - -type Maps struct { - MInt64Str map[int64]string `protobuf:"bytes,1,rep,name=m_int64_str,json=mInt64Str" json:"m_int64_str,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MBoolSimple map[bool]*Simple `protobuf:"bytes,2,rep,name=m_bool_simple,json=mBoolSimple" json:"m_bool_simple,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Maps) Reset() { *m = Maps{} } -func (m *Maps) String() string { return proto.CompactTextString(m) } -func (*Maps) ProtoMessage() {} -func (*Maps) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{4} -} -func (m *Maps) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Maps.Unmarshal(m, b) -} -func (m *Maps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Maps.Marshal(b, m, deterministic) -} -func (dst *Maps) XXX_Merge(src proto.Message) { - xxx_messageInfo_Maps.Merge(dst, src) -} -func (m *Maps) XXX_Size() int { - return xxx_messageInfo_Maps.Size(m) -} -func (m *Maps) XXX_DiscardUnknown() { - xxx_messageInfo_Maps.DiscardUnknown(m) -} - -var xxx_messageInfo_Maps proto.InternalMessageInfo - -func (m *Maps) GetMInt64Str() map[int64]string { - if m != nil { - return m.MInt64Str - } - return nil -} - -func (m *Maps) GetMBoolSimple() map[bool]*Simple { - if m != nil { - return m.MBoolSimple - } - return nil -} - -type MsgWithOneof struct { - // Types that are valid to be assigned to Union: - // *MsgWithOneof_Title - // *MsgWithOneof_Salary - // *MsgWithOneof_Country - // *MsgWithOneof_HomeAddress - // *MsgWithOneof_MsgWithRequired - Union isMsgWithOneof_Union `protobuf_oneof:"union"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} } -func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) } -func (*MsgWithOneof) ProtoMessage() {} -func (*MsgWithOneof) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{5} -} -func (m *MsgWithOneof) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MsgWithOneof.Unmarshal(m, b) -} -func (m *MsgWithOneof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MsgWithOneof.Marshal(b, m, deterministic) -} -func (dst *MsgWithOneof) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithOneof.Merge(dst, src) -} -func (m *MsgWithOneof) XXX_Size() int { - return xxx_messageInfo_MsgWithOneof.Size(m) -} -func (m *MsgWithOneof) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithOneof.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithOneof proto.InternalMessageInfo - -type isMsgWithOneof_Union interface { - isMsgWithOneof_Union() -} - -type MsgWithOneof_Title struct { - Title string `protobuf:"bytes,1,opt,name=title,oneof"` -} -type MsgWithOneof_Salary struct { - Salary int64 `protobuf:"varint,2,opt,name=salary,oneof"` -} -type MsgWithOneof_Country struct { - Country string `protobuf:"bytes,3,opt,name=Country,oneof"` -} -type MsgWithOneof_HomeAddress struct { - HomeAddress string `protobuf:"bytes,4,opt,name=home_address,json=homeAddress,oneof"` -} -type MsgWithOneof_MsgWithRequired struct { - MsgWithRequired *MsgWithRequired `protobuf:"bytes,5,opt,name=msg_with_required,json=msgWithRequired,oneof"` -} - -func (*MsgWithOneof_Title) isMsgWithOneof_Union() {} -func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {} -func (*MsgWithOneof_Country) isMsgWithOneof_Union() {} -func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {} -func (*MsgWithOneof_MsgWithRequired) isMsgWithOneof_Union() {} - -func (m *MsgWithOneof) GetUnion() isMsgWithOneof_Union { - if m != nil { - return m.Union - } - return nil -} - -func (m *MsgWithOneof) GetTitle() string { - if x, ok := m.GetUnion().(*MsgWithOneof_Title); ok { - return x.Title - } - return "" -} - -func (m *MsgWithOneof) GetSalary() int64 { - if x, ok := m.GetUnion().(*MsgWithOneof_Salary); ok { - return x.Salary - } - return 0 -} - -func (m *MsgWithOneof) GetCountry() string { - if x, ok := m.GetUnion().(*MsgWithOneof_Country); ok { - return x.Country - } - return "" -} - -func (m *MsgWithOneof) GetHomeAddress() string { - if x, ok := m.GetUnion().(*MsgWithOneof_HomeAddress); ok { - return x.HomeAddress - } - return "" -} - -func (m *MsgWithOneof) GetMsgWithRequired() *MsgWithRequired { - if x, ok := m.GetUnion().(*MsgWithOneof_MsgWithRequired); ok { - return x.MsgWithRequired - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _MsgWithOneof_OneofMarshaler, _MsgWithOneof_OneofUnmarshaler, _MsgWithOneof_OneofSizer, []interface{}{ - (*MsgWithOneof_Title)(nil), - (*MsgWithOneof_Salary)(nil), - (*MsgWithOneof_Country)(nil), - (*MsgWithOneof_HomeAddress)(nil), - (*MsgWithOneof_MsgWithRequired)(nil), - } -} - -func _MsgWithOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*MsgWithOneof) - // union - switch x := m.Union.(type) { - case *MsgWithOneof_Title: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Title) - case *MsgWithOneof_Salary: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Salary)) - case *MsgWithOneof_Country: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Country) - case *MsgWithOneof_HomeAddress: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.HomeAddress) - case *MsgWithOneof_MsgWithRequired: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.MsgWithRequired); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("MsgWithOneof.Union has unexpected type %T", x) - } - return nil -} - -func _MsgWithOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*MsgWithOneof) - switch tag { - case 1: // union.title - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &MsgWithOneof_Title{x} - return true, err - case 2: // union.salary - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &MsgWithOneof_Salary{int64(x)} - return true, err - case 3: // union.Country - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &MsgWithOneof_Country{x} - return true, err - case 4: // union.home_address - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &MsgWithOneof_HomeAddress{x} - return true, err - case 5: // union.msg_with_required - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(MsgWithRequired) - err := b.DecodeMessage(msg) - m.Union = &MsgWithOneof_MsgWithRequired{msg} - return true, err - default: - return false, nil - } -} - -func _MsgWithOneof_OneofSizer(msg proto.Message) (n int) { - m := msg.(*MsgWithOneof) - // union - switch x := m.Union.(type) { - case *MsgWithOneof_Title: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Title))) - n += len(x.Title) - case *MsgWithOneof_Salary: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Salary)) - case *MsgWithOneof_Country: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Country))) - n += len(x.Country) - case *MsgWithOneof_HomeAddress: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.HomeAddress))) - n += len(x.HomeAddress) - case *MsgWithOneof_MsgWithRequired: - s := proto.Size(x.MsgWithRequired) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Real struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Real) Reset() { *m = Real{} } -func (m *Real) String() string { return proto.CompactTextString(m) } -func (*Real) ProtoMessage() {} -func (*Real) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{6} -} - -var extRange_Real = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*Real) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_Real -} -func (m *Real) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Real.Unmarshal(m, b) -} -func (m *Real) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Real.Marshal(b, m, deterministic) -} -func (dst *Real) XXX_Merge(src proto.Message) { - xxx_messageInfo_Real.Merge(dst, src) -} -func (m *Real) XXX_Size() int { - return xxx_messageInfo_Real.Size(m) -} -func (m *Real) XXX_DiscardUnknown() { - xxx_messageInfo_Real.DiscardUnknown(m) -} - -var xxx_messageInfo_Real proto.InternalMessageInfo - -func (m *Real) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value - } - return 0 -} - -type Complex struct { - Imaginary *float64 `protobuf:"fixed64,1,opt,name=imaginary" json:"imaginary,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Complex) Reset() { *m = Complex{} } -func (m *Complex) String() string { return proto.CompactTextString(m) } -func (*Complex) ProtoMessage() {} -func (*Complex) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{7} -} - -var extRange_Complex = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*Complex) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_Complex -} -func (m *Complex) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Complex.Unmarshal(m, b) -} -func (m *Complex) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Complex.Marshal(b, m, deterministic) -} -func (dst *Complex) XXX_Merge(src proto.Message) { - xxx_messageInfo_Complex.Merge(dst, src) -} -func (m *Complex) XXX_Size() int { - return xxx_messageInfo_Complex.Size(m) -} -func (m *Complex) XXX_DiscardUnknown() { - xxx_messageInfo_Complex.DiscardUnknown(m) -} - -var xxx_messageInfo_Complex proto.InternalMessageInfo - -func (m *Complex) GetImaginary() float64 { - if m != nil && m.Imaginary != nil { - return *m.Imaginary - } - return 0 -} - -var E_Complex_RealExtension = &proto.ExtensionDesc{ - ExtendedType: (*Real)(nil), - ExtensionType: (*Complex)(nil), - Field: 123, - Name: "jsonpb.Complex.real_extension", - Tag: "bytes,123,opt,name=real_extension,json=realExtension", - Filename: "test_objects.proto", -} - -type KnownTypes struct { - An *any.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"` - Dur *duration.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"` - St *_struct.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"` - Ts *timestamp.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"` - Lv *_struct.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"` - Val *_struct.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"` - Dbl *wrappers.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"` - Flt *wrappers.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"` - I64 *wrappers.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"` - U64 *wrappers.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"` - I32 *wrappers.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"` - U32 *wrappers.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"` - Bool *wrappers.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"` - Str *wrappers.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"` - Bytes *wrappers.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *KnownTypes) Reset() { *m = KnownTypes{} } -func (m *KnownTypes) String() string { return proto.CompactTextString(m) } -func (*KnownTypes) ProtoMessage() {} -func (*KnownTypes) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{8} -} -func (m *KnownTypes) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_KnownTypes.Unmarshal(m, b) -} -func (m *KnownTypes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_KnownTypes.Marshal(b, m, deterministic) -} -func (dst *KnownTypes) XXX_Merge(src proto.Message) { - xxx_messageInfo_KnownTypes.Merge(dst, src) -} -func (m *KnownTypes) XXX_Size() int { - return xxx_messageInfo_KnownTypes.Size(m) -} -func (m *KnownTypes) XXX_DiscardUnknown() { - xxx_messageInfo_KnownTypes.DiscardUnknown(m) -} - -var xxx_messageInfo_KnownTypes proto.InternalMessageInfo - -func (m *KnownTypes) GetAn() *any.Any { - if m != nil { - return m.An - } - return nil -} - -func (m *KnownTypes) GetDur() *duration.Duration { - if m != nil { - return m.Dur - } - return nil -} - -func (m *KnownTypes) GetSt() *_struct.Struct { - if m != nil { - return m.St - } - return nil -} - -func (m *KnownTypes) GetTs() *timestamp.Timestamp { - if m != nil { - return m.Ts - } - return nil -} - -func (m *KnownTypes) GetLv() *_struct.ListValue { - if m != nil { - return m.Lv - } - return nil -} - -func (m *KnownTypes) GetVal() *_struct.Value { - if m != nil { - return m.Val - } - return nil -} - -func (m *KnownTypes) GetDbl() *wrappers.DoubleValue { - if m != nil { - return m.Dbl - } - return nil -} - -func (m *KnownTypes) GetFlt() *wrappers.FloatValue { - if m != nil { - return m.Flt - } - return nil -} - -func (m *KnownTypes) GetI64() *wrappers.Int64Value { - if m != nil { - return m.I64 - } - return nil -} - -func (m *KnownTypes) GetU64() *wrappers.UInt64Value { - if m != nil { - return m.U64 - } - return nil -} - -func (m *KnownTypes) GetI32() *wrappers.Int32Value { - if m != nil { - return m.I32 - } - return nil -} - -func (m *KnownTypes) GetU32() *wrappers.UInt32Value { - if m != nil { - return m.U32 - } - return nil -} - -func (m *KnownTypes) GetBool() *wrappers.BoolValue { - if m != nil { - return m.Bool - } - return nil -} - -func (m *KnownTypes) GetStr() *wrappers.StringValue { - if m != nil { - return m.Str - } - return nil -} - -func (m *KnownTypes) GetBytes() *wrappers.BytesValue { - if m != nil { - return m.Bytes - } - return nil -} - -// Test messages for marshaling/unmarshaling required fields. -type MsgWithRequired struct { - Str *string `protobuf:"bytes,1,req,name=str" json:"str,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MsgWithRequired) Reset() { *m = MsgWithRequired{} } -func (m *MsgWithRequired) String() string { return proto.CompactTextString(m) } -func (*MsgWithRequired) ProtoMessage() {} -func (*MsgWithRequired) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{9} -} -func (m *MsgWithRequired) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MsgWithRequired.Unmarshal(m, b) -} -func (m *MsgWithRequired) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MsgWithRequired.Marshal(b, m, deterministic) -} -func (dst *MsgWithRequired) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithRequired.Merge(dst, src) -} -func (m *MsgWithRequired) XXX_Size() int { - return xxx_messageInfo_MsgWithRequired.Size(m) -} -func (m *MsgWithRequired) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithRequired.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithRequired proto.InternalMessageInfo - -func (m *MsgWithRequired) GetStr() string { - if m != nil && m.Str != nil { - return *m.Str - } - return "" -} - -type MsgWithIndirectRequired struct { - Subm *MsgWithRequired `protobuf:"bytes,1,opt,name=subm" json:"subm,omitempty"` - MapField map[string]*MsgWithRequired `protobuf:"bytes,2,rep,name=map_field,json=mapField" json:"map_field,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - SliceField []*MsgWithRequired `protobuf:"bytes,3,rep,name=slice_field,json=sliceField" json:"slice_field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MsgWithIndirectRequired) Reset() { *m = MsgWithIndirectRequired{} } -func (m *MsgWithIndirectRequired) String() string { return proto.CompactTextString(m) } -func (*MsgWithIndirectRequired) ProtoMessage() {} -func (*MsgWithIndirectRequired) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{10} -} -func (m *MsgWithIndirectRequired) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MsgWithIndirectRequired.Unmarshal(m, b) -} -func (m *MsgWithIndirectRequired) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MsgWithIndirectRequired.Marshal(b, m, deterministic) -} -func (dst *MsgWithIndirectRequired) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithIndirectRequired.Merge(dst, src) -} -func (m *MsgWithIndirectRequired) XXX_Size() int { - return xxx_messageInfo_MsgWithIndirectRequired.Size(m) -} -func (m *MsgWithIndirectRequired) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithIndirectRequired.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithIndirectRequired proto.InternalMessageInfo - -func (m *MsgWithIndirectRequired) GetSubm() *MsgWithRequired { - if m != nil { - return m.Subm - } - return nil -} - -func (m *MsgWithIndirectRequired) GetMapField() map[string]*MsgWithRequired { - if m != nil { - return m.MapField - } - return nil -} - -func (m *MsgWithIndirectRequired) GetSliceField() []*MsgWithRequired { - if m != nil { - return m.SliceField - } - return nil -} - -type MsgWithRequiredBytes struct { - Byts []byte `protobuf:"bytes,1,req,name=byts" json:"byts,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MsgWithRequiredBytes) Reset() { *m = MsgWithRequiredBytes{} } -func (m *MsgWithRequiredBytes) String() string { return proto.CompactTextString(m) } -func (*MsgWithRequiredBytes) ProtoMessage() {} -func (*MsgWithRequiredBytes) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{11} -} -func (m *MsgWithRequiredBytes) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MsgWithRequiredBytes.Unmarshal(m, b) -} -func (m *MsgWithRequiredBytes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MsgWithRequiredBytes.Marshal(b, m, deterministic) -} -func (dst *MsgWithRequiredBytes) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithRequiredBytes.Merge(dst, src) -} -func (m *MsgWithRequiredBytes) XXX_Size() int { - return xxx_messageInfo_MsgWithRequiredBytes.Size(m) -} -func (m *MsgWithRequiredBytes) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithRequiredBytes.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithRequiredBytes proto.InternalMessageInfo - -func (m *MsgWithRequiredBytes) GetByts() []byte { - if m != nil { - return m.Byts - } - return nil -} - -type MsgWithRequiredWKT struct { - Str *wrappers.StringValue `protobuf:"bytes,1,req,name=str" json:"str,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MsgWithRequiredWKT) Reset() { *m = MsgWithRequiredWKT{} } -func (m *MsgWithRequiredWKT) String() string { return proto.CompactTextString(m) } -func (*MsgWithRequiredWKT) ProtoMessage() {} -func (*MsgWithRequiredWKT) Descriptor() ([]byte, []int) { - return fileDescriptor_test_objects_c6f6c615ab823e65, []int{12} -} -func (m *MsgWithRequiredWKT) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MsgWithRequiredWKT.Unmarshal(m, b) -} -func (m *MsgWithRequiredWKT) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MsgWithRequiredWKT.Marshal(b, m, deterministic) -} -func (dst *MsgWithRequiredWKT) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgWithRequiredWKT.Merge(dst, src) -} -func (m *MsgWithRequiredWKT) XXX_Size() int { - return xxx_messageInfo_MsgWithRequiredWKT.Size(m) -} -func (m *MsgWithRequiredWKT) XXX_DiscardUnknown() { - xxx_messageInfo_MsgWithRequiredWKT.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgWithRequiredWKT proto.InternalMessageInfo - -func (m *MsgWithRequiredWKT) GetStr() *wrappers.StringValue { - if m != nil { - return m.Str - } - return nil -} - -var E_Name = &proto.ExtensionDesc{ - ExtendedType: (*Real)(nil), - ExtensionType: (*string)(nil), - Field: 124, - Name: "jsonpb.name", - Tag: "bytes,124,opt,name=name", - Filename: "test_objects.proto", -} - -var E_Extm = &proto.ExtensionDesc{ - ExtendedType: (*Real)(nil), - ExtensionType: (*MsgWithRequired)(nil), - Field: 125, - Name: "jsonpb.extm", - Tag: "bytes,125,opt,name=extm", - Filename: "test_objects.proto", -} - -func init() { - proto.RegisterType((*Simple)(nil), "jsonpb.Simple") - proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites") - proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats") - proto.RegisterType((*Widget)(nil), "jsonpb.Widget") - proto.RegisterType((*Maps)(nil), "jsonpb.Maps") - proto.RegisterMapType((map[bool]*Simple)(nil), "jsonpb.Maps.MBoolSimpleEntry") - proto.RegisterMapType((map[int64]string)(nil), "jsonpb.Maps.MInt64StrEntry") - proto.RegisterType((*MsgWithOneof)(nil), "jsonpb.MsgWithOneof") - proto.RegisterType((*Real)(nil), "jsonpb.Real") - proto.RegisterType((*Complex)(nil), "jsonpb.Complex") - proto.RegisterType((*KnownTypes)(nil), "jsonpb.KnownTypes") - proto.RegisterType((*MsgWithRequired)(nil), "jsonpb.MsgWithRequired") - proto.RegisterType((*MsgWithIndirectRequired)(nil), "jsonpb.MsgWithIndirectRequired") - proto.RegisterMapType((map[string]*MsgWithRequired)(nil), "jsonpb.MsgWithIndirectRequired.MapFieldEntry") - proto.RegisterType((*MsgWithRequiredBytes)(nil), "jsonpb.MsgWithRequiredBytes") - proto.RegisterType((*MsgWithRequiredWKT)(nil), "jsonpb.MsgWithRequiredWKT") - proto.RegisterEnum("jsonpb.Widget_Color", Widget_Color_name, Widget_Color_value) - proto.RegisterExtension(E_Complex_RealExtension) - proto.RegisterExtension(E_Name) - proto.RegisterExtension(E_Extm) -} - -func init() { proto.RegisterFile("test_objects.proto", fileDescriptor_test_objects_c6f6c615ab823e65) } - -var fileDescriptor_test_objects_c6f6c615ab823e65 = []byte{ - // 1357 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x56, 0xdd, 0x72, 0x13, 0xc7, - 0x12, 0xf6, 0xee, 0x6a, 0xf5, 0xd3, 0xf2, 0x1f, 0x83, 0x81, 0xc5, 0x87, 0x73, 0x8e, 0x4a, 0x70, - 0x38, 0x0a, 0xc4, 0xa2, 0x22, 0xbb, 0x5c, 0x84, 0xe4, 0x06, 0x63, 0x13, 0x08, 0xe0, 0xa4, 0xc6, - 0x26, 0x5c, 0xaa, 0x56, 0xde, 0x91, 0x59, 0xb2, 0xbb, 0xa3, 0xcc, 0xcc, 0xda, 0xa8, 0x92, 0x54, - 0xf9, 0x19, 0x52, 0x79, 0x82, 0x54, 0x25, 0x8f, 0x90, 0x8b, 0xbc, 0x45, 0xde, 0x28, 0x35, 0x3d, - 0xb3, 0x5a, 0x59, 0x42, 0x95, 0x5c, 0x79, 0xbb, 0xfb, 0xeb, 0x4f, 0x33, 0xfd, 0xf5, 0x74, 0x1b, - 0x88, 0x62, 0x52, 0xf5, 0xf9, 0xe0, 0x1d, 0x3b, 0x51, 0xb2, 0x3b, 0x12, 0x5c, 0x71, 0x52, 0x7d, - 0x27, 0x79, 0x36, 0x1a, 0x6c, 0xde, 0x3c, 0xe5, 0xfc, 0x34, 0x61, 0x0f, 0xd0, 0x3b, 0xc8, 0x87, - 0x0f, 0xc2, 0x6c, 0x6c, 0x20, 0x9b, 0xff, 0x99, 0x0d, 0x45, 0xb9, 0x08, 0x55, 0xcc, 0x33, 0x1b, - 0xbf, 0x35, 0x1b, 0x97, 0x4a, 0xe4, 0x27, 0xca, 0x46, 0xff, 0x3b, 0x1b, 0x55, 0x71, 0xca, 0xa4, - 0x0a, 0xd3, 0xd1, 0x22, 0xfa, 0x73, 0x11, 0x8e, 0x46, 0x4c, 0xd8, 0x13, 0xb6, 0x7f, 0x75, 0xa1, - 0x7a, 0x14, 0xa7, 0xa3, 0x84, 0x91, 0x6b, 0x50, 0xe5, 0xfd, 0x01, 0xe7, 0x49, 0xe0, 0xb4, 0x9c, - 0x4e, 0x9d, 0xfa, 0x7c, 0x8f, 0xf3, 0x84, 0xdc, 0x80, 0x1a, 0xef, 0xc7, 0x99, 0xda, 0xee, 0x05, - 0x6e, 0xcb, 0xe9, 0xf8, 0xb4, 0xca, 0x9f, 0x6b, 0x6b, 0x12, 0xd8, 0xdd, 0x09, 0xbc, 0x96, 0xd3, - 0xf1, 0x4c, 0x60, 0x77, 0x87, 0xdc, 0x84, 0x3a, 0xef, 0xe7, 0x26, 0xa5, 0xd2, 0x72, 0x3a, 0x2b, - 0xb4, 0xc6, 0x5f, 0xa3, 0x59, 0x86, 0x76, 0x77, 0x02, 0xbf, 0xe5, 0x74, 0x2a, 0x36, 0x54, 0x64, - 0x49, 0x93, 0x55, 0x6d, 0x39, 0x9d, 0x2b, 0xb4, 0xc6, 0x8f, 0xa6, 0xb2, 0xa4, 0xc9, 0xaa, 0xb5, - 0x9c, 0x0e, 0xb1, 0xa1, 0xdd, 0x1d, 0x73, 0x88, 0x61, 0xc2, 0x43, 0x15, 0xd4, 0x5b, 0x4e, 0xc7, - 0xa5, 0x55, 0xfe, 0x54, 0x5b, 0x26, 0x27, 0xe2, 0xf9, 0x20, 0x61, 0x41, 0xa3, 0xe5, 0x74, 0x1c, - 0x5a, 0xe3, 0xfb, 0x68, 0x5a, 0x3a, 0x25, 0xe2, 0xec, 0x34, 0x80, 0x96, 0xd3, 0x69, 0x68, 0x3a, - 0x34, 0x0d, 0xdd, 0x60, 0xac, 0x98, 0x0c, 0x9a, 0x2d, 0xa7, 0xb3, 0x4c, 0xab, 0x7c, 0x4f, 0x5b, - 0xed, 0x9f, 0x1c, 0x80, 0x43, 0x9e, 0x3d, 0x8d, 0xb3, 0x58, 0x31, 0x49, 0xae, 0x82, 0x3f, 0xec, - 0x67, 0x61, 0x86, 0xa5, 0x72, 0x69, 0x65, 0x78, 0x18, 0x66, 0xba, 0x80, 0xc3, 0xfe, 0x28, 0xce, - 0x86, 0x58, 0x28, 0x97, 0xfa, 0xc3, 0xaf, 0xe3, 0x6c, 0x68, 0xdc, 0x99, 0x76, 0x7b, 0xd6, 0x7d, - 0xa8, 0xdd, 0x57, 0xc1, 0x8f, 0x90, 0xa2, 0x82, 0xa7, 0xab, 0x44, 0x96, 0x22, 0x32, 0x14, 0x3e, - 0x7a, 0xfd, 0xa8, 0xa0, 0x88, 0x0c, 0x45, 0xd5, 0xba, 0x35, 0x45, 0xfb, 0x37, 0x17, 0x6a, 0x94, - 0x8d, 0x58, 0xa8, 0xa4, 0x86, 0x88, 0x42, 0x3d, 0x4f, 0xab, 0x27, 0x0a, 0xf5, 0xc4, 0x44, 0x3d, - 0x4f, 0xab, 0x27, 0x26, 0xea, 0x89, 0x89, 0x7a, 0x9e, 0x56, 0x4f, 0x4c, 0xd4, 0x13, 0xa5, 0x7a, - 0x9e, 0x56, 0x4f, 0x94, 0xea, 0x89, 0x52, 0x3d, 0x4f, 0xab, 0x27, 0x4a, 0xf5, 0x44, 0xa9, 0x9e, - 0xa7, 0xd5, 0x13, 0x47, 0x53, 0x59, 0x13, 0xf5, 0x3c, 0xad, 0x9e, 0x28, 0xd5, 0x13, 0x13, 0xf5, - 0x3c, 0xad, 0x9e, 0x98, 0xa8, 0x27, 0x4a, 0xf5, 0x3c, 0xad, 0x9e, 0x28, 0xd5, 0x13, 0xa5, 0x7a, - 0x9e, 0x56, 0x4f, 0x94, 0xea, 0x89, 0x89, 0x7a, 0x9e, 0x56, 0x4f, 0x18, 0xf5, 0x7e, 0x77, 0xa1, - 0xfa, 0x26, 0x8e, 0x4e, 0x99, 0x22, 0xf7, 0xc0, 0x3f, 0xe1, 0x09, 0x17, 0xa8, 0xdc, 0x6a, 0x6f, - 0xa3, 0x6b, 0x9e, 0x68, 0xd7, 0x84, 0xbb, 0x4f, 0x74, 0x8c, 0x1a, 0x08, 0xd9, 0xd2, 0x7c, 0x06, - 0xad, 0x8b, 0xb7, 0x08, 0x5d, 0x15, 0xf8, 0x97, 0xdc, 0x85, 0xaa, 0xc4, 0xa7, 0x84, 0x5d, 0xd5, - 0xec, 0xad, 0x16, 0x68, 0xf3, 0xc0, 0xa8, 0x8d, 0x92, 0x8f, 0x4c, 0x41, 0x10, 0xa9, 0xcf, 0x39, - 0x8f, 0xd4, 0x05, 0xb2, 0xd0, 0x9a, 0x30, 0x02, 0x07, 0x1b, 0xc8, 0xb9, 0x56, 0x20, 0xad, 0xee, - 0xb4, 0x88, 0x93, 0x8f, 0xa1, 0x21, 0xfa, 0x05, 0xf8, 0x1a, 0xd2, 0xce, 0x81, 0xeb, 0xc2, 0x7e, - 0xb5, 0xff, 0x07, 0xbe, 0x39, 0x74, 0x0d, 0x3c, 0x7a, 0xb0, 0xbf, 0xbe, 0x44, 0x1a, 0xe0, 0x7f, - 0x41, 0x0f, 0x0e, 0x0e, 0xd7, 0x1d, 0x52, 0x87, 0xca, 0xde, 0xcb, 0xd7, 0x07, 0xeb, 0x6e, 0xfb, - 0x67, 0x17, 0x2a, 0xaf, 0xc2, 0x91, 0x24, 0x9f, 0x41, 0x33, 0x35, 0xed, 0xa2, 0x6b, 0x8f, 0x3d, - 0xd6, 0xec, 0xfd, 0xab, 0xe0, 0xd7, 0x90, 0xee, 0x2b, 0xec, 0x9f, 0x23, 0x25, 0x0e, 0x32, 0x25, - 0xc6, 0xb4, 0x91, 0x16, 0x36, 0x79, 0x0c, 0x2b, 0x29, 0xf6, 0x66, 0x71, 0x6b, 0x17, 0xd3, 0xff, - 0x7d, 0x39, 0x5d, 0xf7, 0xab, 0xb9, 0xb6, 0x21, 0x68, 0xa6, 0xa5, 0x67, 0xf3, 0x73, 0x58, 0xbd, - 0xcc, 0x4f, 0xd6, 0xc1, 0xfb, 0x96, 0x8d, 0x51, 0x46, 0x8f, 0xea, 0x4f, 0xb2, 0x01, 0xfe, 0x59, - 0x98, 0xe4, 0x0c, 0x9f, 0x5f, 0x83, 0x1a, 0xe3, 0x91, 0xfb, 0xd0, 0xd9, 0x3c, 0x84, 0xf5, 0x59, - 0xfa, 0xe9, 0xfc, 0xba, 0xc9, 0xbf, 0x33, 0x9d, 0x3f, 0x2f, 0x4a, 0xc9, 0xd7, 0xfe, 0xd3, 0x81, - 0xe5, 0x57, 0xf2, 0xf4, 0x4d, 0xac, 0xde, 0x7e, 0x95, 0x31, 0x3e, 0x24, 0xd7, 0xc1, 0x57, 0xb1, - 0x4a, 0x18, 0xd2, 0x35, 0x9e, 0x2d, 0x51, 0x63, 0x92, 0x00, 0xaa, 0x32, 0x4c, 0x42, 0x31, 0x46, - 0x4e, 0xef, 0xd9, 0x12, 0xb5, 0x36, 0xd9, 0x84, 0xda, 0x13, 0x9e, 0xeb, 0x93, 0xe0, 0x58, 0xd0, - 0x39, 0x85, 0x83, 0xdc, 0x86, 0xe5, 0xb7, 0x3c, 0x65, 0xfd, 0x30, 0x8a, 0x04, 0x93, 0x12, 0x27, - 0x84, 0x06, 0x34, 0xb5, 0xf7, 0xb1, 0x71, 0x92, 0x03, 0xb8, 0x92, 0xca, 0xd3, 0xfe, 0x79, 0xac, - 0xde, 0xf6, 0x05, 0xfb, 0x2e, 0x8f, 0x05, 0x8b, 0x70, 0x6a, 0x34, 0x7b, 0x37, 0x26, 0x85, 0x35, - 0x67, 0xa4, 0x36, 0xfc, 0x6c, 0x89, 0xae, 0xa5, 0x97, 0x5d, 0x7b, 0x35, 0xf0, 0xf3, 0x2c, 0xe6, - 0x59, 0xfb, 0x2e, 0x54, 0x28, 0x0b, 0x93, 0xb2, 0x8a, 0x8e, 0x19, 0x35, 0x68, 0xdc, 0xab, 0xd7, - 0xa3, 0xf5, 0x8b, 0x8b, 0x8b, 0x0b, 0xb7, 0x7d, 0xae, 0x0f, 0xae, 0x0b, 0xf2, 0x9e, 0xdc, 0x82, - 0x46, 0x9c, 0x86, 0xa7, 0x71, 0xa6, 0x2f, 0x68, 0xe0, 0xa5, 0xa3, 0x4c, 0xe9, 0xed, 0xc3, 0xaa, - 0x60, 0x61, 0xd2, 0x67, 0xef, 0x15, 0xcb, 0x64, 0xcc, 0x33, 0xb2, 0x5c, 0x76, 0x66, 0x98, 0x04, - 0xdf, 0x5f, 0x6e, 0x6d, 0x4b, 0x4f, 0x57, 0x74, 0xd2, 0x41, 0x91, 0xd3, 0xfe, 0xc3, 0x07, 0x78, - 0x91, 0xf1, 0xf3, 0xec, 0x78, 0x3c, 0x62, 0x92, 0xdc, 0x01, 0x37, 0xcc, 0x82, 0x55, 0x4c, 0xdd, - 0xe8, 0x9a, 0x35, 0xd7, 0x2d, 0xd6, 0x5c, 0xf7, 0x71, 0x36, 0xa6, 0x6e, 0x98, 0x91, 0xfb, 0xe0, - 0x45, 0xb9, 0x79, 0xec, 0xcd, 0xde, 0xcd, 0x39, 0xd8, 0xbe, 0x5d, 0xb6, 0x54, 0xa3, 0xc8, 0xff, - 0xc1, 0x95, 0x2a, 0x58, 0xb6, 0x35, 0x9c, 0xc5, 0x1e, 0xe1, 0xe2, 0xa5, 0xae, 0xd4, 0x43, 0xc4, - 0x55, 0xd2, 0xb6, 0xc9, 0xe6, 0x1c, 0xf0, 0xb8, 0xd8, 0xc1, 0xd4, 0x55, 0x52, 0x63, 0x93, 0xb3, - 0x60, 0x6d, 0x01, 0xf6, 0x65, 0x2c, 0xd5, 0x37, 0xba, 0xc2, 0xd4, 0x4d, 0xce, 0x48, 0x07, 0xbc, - 0xb3, 0x30, 0x09, 0xd6, 0x11, 0x7c, 0x7d, 0x0e, 0x6c, 0x80, 0x1a, 0x42, 0xba, 0xe0, 0x45, 0x83, - 0x04, 0x5b, 0xa7, 0xd9, 0xbb, 0x35, 0x7f, 0x2f, 0x9c, 0x95, 0x16, 0x1f, 0x0d, 0x12, 0xb2, 0x05, - 0xde, 0x30, 0x51, 0xd8, 0x49, 0xfa, 0xdd, 0xce, 0xe2, 0x71, 0xea, 0x5a, 0xf8, 0x30, 0x51, 0x1a, - 0x1e, 0xdb, 0x15, 0xfd, 0x21, 0x38, 0xbe, 0x44, 0x0b, 0x8f, 0x77, 0x77, 0xf4, 0x69, 0xf2, 0xdd, - 0x1d, 0x5c, 0x4e, 0x1f, 0x3a, 0xcd, 0xeb, 0x69, 0x7c, 0xbe, 0xbb, 0x83, 0xf4, 0xdb, 0x3d, 0xdc, - 0xe5, 0x0b, 0xe8, 0xb7, 0x7b, 0x05, 0xfd, 0x76, 0x0f, 0xe9, 0xb7, 0x7b, 0xb8, 0xe0, 0x17, 0xd1, - 0x4f, 0xf0, 0x39, 0xe2, 0x2b, 0xb8, 0x09, 0x1b, 0x0b, 0x8a, 0xae, 0x47, 0x81, 0x81, 0x23, 0x4e, - 0xf3, 0xeb, 0xa1, 0x06, 0x0b, 0xf8, 0xcd, 0x76, 0xb1, 0xfc, 0x52, 0x09, 0xf2, 0x09, 0xf8, 0xe5, - 0xff, 0x08, 0x1f, 0xba, 0x00, 0x6e, 0x1d, 0x93, 0x60, 0x90, 0xed, 0xdb, 0xb0, 0x36, 0xf3, 0x18, - 0xf5, 0x00, 0x32, 0xa3, 0xd4, 0xed, 0x34, 0x90, 0xb7, 0xfd, 0x8b, 0x0b, 0x37, 0x2c, 0xea, 0x79, - 0x16, 0xc5, 0x82, 0x9d, 0xa8, 0x09, 0xfa, 0x3e, 0x54, 0x64, 0x3e, 0x48, 0x6d, 0x27, 0x2f, 0x7a, - 0xe1, 0x14, 0x41, 0xe4, 0x4b, 0x68, 0xa4, 0xe1, 0xa8, 0x3f, 0x8c, 0x59, 0x12, 0xd9, 0x61, 0xbb, - 0x35, 0x93, 0x31, 0xfb, 0x03, 0x7a, 0x08, 0x3f, 0xd5, 0x78, 0x33, 0x7c, 0xeb, 0xa9, 0x35, 0xc9, - 0x43, 0x68, 0xca, 0x24, 0x3e, 0x61, 0x96, 0xcd, 0x43, 0xb6, 0x85, 0xbf, 0x0f, 0x88, 0xc5, 0xcc, - 0xcd, 0x63, 0x58, 0xb9, 0x44, 0x3a, 0x3d, 0x72, 0x1b, 0x66, 0xe4, 0x6e, 0x5d, 0x1e, 0xb9, 0x0b, - 0x69, 0xa7, 0x66, 0xef, 0x3d, 0xd8, 0x98, 0x89, 0x62, 0xb5, 0x09, 0x81, 0xca, 0x60, 0xac, 0x24, - 0xd6, 0x73, 0x99, 0xe2, 0x77, 0x7b, 0x1f, 0xc8, 0x0c, 0xf6, 0xcd, 0x8b, 0xe3, 0x42, 0x6e, 0x0d, - 0xfc, 0x27, 0x72, 0x3f, 0x6a, 0x41, 0x25, 0x0b, 0x53, 0x36, 0x33, 0xb4, 0x7e, 0xc0, 0x5b, 0x60, - 0xe4, 0xd1, 0xa7, 0x50, 0x61, 0xef, 0x55, 0x3a, 0x83, 0xf8, 0xf1, 0x6f, 0xa4, 0xd2, 0x29, 0x7f, - 0x05, 0x00, 0x00, 0xff, 0xff, 0xea, 0x06, 0x1a, 0xa9, 0x37, 0x0c, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto b/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto deleted file mode 100755 index 36eb6e8..0000000 --- a/examples/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto +++ /dev/null @@ -1,171 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -import "google/protobuf/any.proto"; -import "google/protobuf/duration.proto"; -import "google/protobuf/struct.proto"; -import "google/protobuf/timestamp.proto"; -import "google/protobuf/wrappers.proto"; - -package jsonpb; - -// Test message for holding primitive types. -message Simple { - optional bool o_bool = 1; - optional int32 o_int32 = 2; - optional int64 o_int64 = 3; - optional uint32 o_uint32 = 4; - optional uint64 o_uint64 = 5; - optional sint32 o_sint32 = 6; - optional sint64 o_sint64 = 7; - optional float o_float = 8; - optional double o_double = 9; - optional string o_string = 10; - optional bytes o_bytes = 11; -} - -// Test message for holding special non-finites primitives. -message NonFinites { - optional float f_nan = 1; - optional float f_pinf = 2; - optional float f_ninf = 3; - optional double d_nan = 4; - optional double d_pinf = 5; - optional double d_ninf = 6; -} - -// Test message for holding repeated primitives. -message Repeats { - repeated bool r_bool = 1; - repeated int32 r_int32 = 2; - repeated int64 r_int64 = 3; - repeated uint32 r_uint32 = 4; - repeated uint64 r_uint64 = 5; - repeated sint32 r_sint32 = 6; - repeated sint64 r_sint64 = 7; - repeated float r_float = 8; - repeated double r_double = 9; - repeated string r_string = 10; - repeated bytes r_bytes = 11; -} - -// Test message for holding enums and nested messages. -message Widget { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color color = 1; - repeated Color r_color = 2; - - optional Simple simple = 10; - repeated Simple r_simple = 11; - - optional Repeats repeats = 20; - repeated Repeats r_repeats = 21; -} - -message Maps { - map m_int64_str = 1; - map m_bool_simple = 2; -} - -message MsgWithOneof { - oneof union { - string title = 1; - int64 salary = 2; - string Country = 3; - string home_address = 4; - MsgWithRequired msg_with_required = 5; - } -} - -message Real { - optional double value = 1; - extensions 100 to max; -} - -extend Real { - optional string name = 124; -} - -message Complex { - extend Real { - optional Complex real_extension = 123; - } - optional double imaginary = 1; - extensions 100 to max; -} - -message KnownTypes { - optional google.protobuf.Any an = 14; - optional google.protobuf.Duration dur = 1; - optional google.protobuf.Struct st = 12; - optional google.protobuf.Timestamp ts = 2; - optional google.protobuf.ListValue lv = 15; - optional google.protobuf.Value val = 16; - - optional google.protobuf.DoubleValue dbl = 3; - optional google.protobuf.FloatValue flt = 4; - optional google.protobuf.Int64Value i64 = 5; - optional google.protobuf.UInt64Value u64 = 6; - optional google.protobuf.Int32Value i32 = 7; - optional google.protobuf.UInt32Value u32 = 8; - optional google.protobuf.BoolValue bool = 9; - optional google.protobuf.StringValue str = 10; - optional google.protobuf.BytesValue bytes = 11; -} - -// Test messages for marshaling/unmarshaling required fields. -message MsgWithRequired { - required string str = 1; -} - -message MsgWithIndirectRequired { - optional MsgWithRequired subm = 1; - map map_field = 2; - repeated MsgWithRequired slice_field = 3; -} - -message MsgWithRequiredBytes { - required bytes byts = 1; -} - -message MsgWithRequiredWKT { - required google.protobuf.StringValue str = 1; -} - -extend Real { - optional MsgWithRequired extm = 125; -} diff --git a/examples/github.com/golang/protobuf/proto/all_test.go b/examples/github.com/golang/protobuf/proto/all_test.go deleted file mode 100755 index 361f72f..0000000 --- a/examples/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2410 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "sync" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/test_proto" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - pb.F_Sfixed32Defaulted = Int32(Default_GoTest_F_Sfixed32Defaulted) - pb.F_Sfixed64Defaulted = Int64(Default_GoTest_F_Sfixed64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.F_Sfixed32Required = Int32(-32) - pb.F_Sfixed64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Ensure that Buffer.Marshal uses O(N) memory for N messages -func TestBufferMarshalAllocs(t *testing.T) { - value := &OtherMessage{Key: Int64(1)} - msg := &MyMessage{Count: Int32(1), Others: []*OtherMessage{value}} - - reallocSize := func(t *testing.T, items int, prealloc int) (int64, int64) { - var b Buffer - b.SetBuf(make([]byte, 0, prealloc)) - - var allocSpace int64 - prevCap := cap(b.Bytes()) - for i := 0; i < items; i++ { - err := b.Marshal(msg) - if err != nil { - t.Errorf("Marshal err = %q", err) - break - } - if c := cap(b.Bytes()); prevCap != c { - allocSpace += int64(c) - prevCap = c - } - } - needSpace := int64(len(b.Bytes())) - return allocSpace, needSpace - } - - for _, prealloc := range []int{0, 100, 10000} { - for _, items := range []int{1, 2, 5, 10, 20, 50, 100, 200, 500, 1000} { - runtimeSpace, need := reallocSize(t, items, prealloc) - totalSpace := int64(prealloc) + runtimeSpace - - runtimeRatio := float64(runtimeSpace) / float64(need) - totalRatio := float64(totalSpace) / float64(need) - - if totalRatio < 1 || runtimeRatio > 4 { - t.Errorf("needed %dB, allocated %dB total (ratio %.1f), allocated %dB at runtime (ratio %.1f)", - need, totalSpace, totalRatio, runtimeSpace, runtimeRatio) - } - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if !strings.Contains(err.Error(), "Kind") { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff") // field 105, encoding 1, -64 fixed64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f"+ // field 403, encoding 0, value 127 - "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32 - "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - pb.F_Sfixed32Defaulted = Int32(-32) - pb.F_Sfixed64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f"+ // field 403, encoding 0, value 127 - "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32 - "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.F_Sfixed32Optional = Int32(-32) - pb.F_Sfixed64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8513e0ffffff"+ // field 304, encoding 5, -32 fixed32 - "8913c0ffffffffffffff"+ // field 305, encoding 1, -64 fixed64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f"+ // field 403, encoding 0, value 127 - "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32 - "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.F_Sfixed32Repeated = []int32{32, -32} - pb.F_Sfixed64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "e50c20000000"+ // field 204, encoding 5, 32 fixed32 - "e50ce0ffffff"+ // field 204, encoding 5, -32 fixed32 - "e90c4000000000000000"+ // field 205, encoding 1, 64 fixed64 - "e90cc0ffffffffffffff"+ // field 205, encoding 1, -64 fixed64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f"+ // field 403, encoding 0, value 127 - "a519e0ffffff"+ // field 404, encoding 5, -32 fixed32 - "a919c0ffffffffffffff") // field 405, encoding 1, -64 fixed64 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - pb.F_Sfixed32RepeatedPacked = []int32{32, -32} - pb.F_Sfixed64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff"+ // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff"+ // field 105, encoding 1, -64 fixed64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f"+ // value 64, value -64 - "c21f08"+ // field 504, encoding 2, 8 bytes - "20000000e0ffffff"+ // value 32, value -32 - "ca1f10"+ // field 505, encoding 2, 16 bytes - "4000000000000000c0ffffffffffffff") // value 64, value -64 - -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - if x := uint64(pbd.F_Sint64Repeated[i]); x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - if x := uint64(pbd.F_Sint32Repeated[i]); x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - if x := uint64(pbd.F_DoubleRepeated[i]); x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - if x := uint64(pbd.F_FloatRepeated[i]); x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - if x := pbd.F_Uint64Repeated[i]; x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - if x := uint64(pbd.F_Uint32Repeated[i]); x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - if x := pbd.F_Fixed64Repeated[i]; x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - if x := uint64(pbd.F_Fixed32Repeated[i]); x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - if x := uint64(pbd.F_Int64Repeated[i]); x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - if x := uint64(pbd.F_Int32Repeated[i]); x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if x := pbd.F_BoolRepeated[i]; x != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -func TestBadWireTypeUnknown(t *testing.T) { - var b []byte - fmt.Sscanf("0a01780d00000000080b101612036161611521000000202c220362626225370000002203636363214200000000000000584d5a036464645900000000000056405d63000000", "%x", &b) - - m := new(MyMessage) - if err := Unmarshal(b, m); err != nil { - t.Errorf("unexpected Unmarshal error: %v", err) - } - - var unknown []byte - fmt.Sscanf("0a01780d0000000010161521000000202c2537000000214200000000000000584d5a036464645d63000000", "%x", &unknown) - if !bytes.Equal(m.XXX_unrecognized, unknown) { - t.Errorf("unknown bytes mismatch:\ngot %x\nwant %x", m.XXX_unrecognized, unknown) - } - DiscardUnknown(m) - - want := &MyMessage{Count: Int32(11), Name: String("aaa"), Pet: []string{"bbb", "ccc"}, Bigfloat: Float64(88)} - if !Equal(m, want) { - t.Errorf("message mismatch:\ngot %v\nwant %v", m, want) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Type") && !strings.Contains(err.Error(), "{Unknown}") { - // TODO: remove unknown cases once we commit to the new unmarshaler. - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") && !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -type NMMessage struct{} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestBytesWithInvalidLengthInGroup(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{0xbb, 0x30, 0xb2, 0x30, 0xb0, 0xb2, 0x83, 0xf1, 0xb0, 0xb2, 0xef, 0xbf, 0xbd, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -func TestExtensionMapFieldMarshalDeterministic(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{MapField: map[int32]int32{1: 1, 2: 2, 3: 3, 4: 4}}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - marshal := func(m Message) []byte { - var b Buffer - b.SetDeterministic(true) - if err := b.Marshal(m); err != nil { - t.Fatalf("Marshal failed: %v", err) - } - return b.Bytes() - } - - want := marshal(m) - for i := 0; i < 100; i++ { - if got := marshal(m); !bytes.Equal(got, want) { - t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestUnmarshalMergesGroups(t *testing.T) { - // If a nested group occurs twice in the input, - // the fields should be merged when decoding. - a := &GroupNew{ - G: &GroupNew_G{ - X: Int32(7), - Y: Int32(8), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &GroupNew{ - G: &GroupNew_G{ - X: Int32(9), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &GroupNew{ - G: &GroupNew_G{ - X: Int32(9), - Y: Int32(8), - }, - } - got := new(GroupNew) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" + // field 103, encoding 0, 0x7f zigzag64 - "c506e0ffffff" + // field 104, encoding 5, -32 fixed32 - "c906c0ffffffffffffff" // field 105, encoding 1, -64 fixed64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if !strings.Contains(err.Error(), "RequiredField.Label") { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if !strings.Contains(err.Error(), "RequiredField.Label") && !strings.Contains(err.Error(), "RequiredField.{Unknown}") { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if !strings.Contains(err.Error(), "RequiredField.Label") { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func TestRequiredNotSetErrorWithBadWireTypes(t *testing.T) { - // Required field expects a varint, and properly found a varint. - if err := Unmarshal([]byte{0x08, 0x00}, new(GoEnum)); err != nil { - t.Errorf("Unmarshal = %v, want nil", err) - } - // Required field expects a varint, but found a fixed32 instead. - if err := Unmarshal([]byte{0x0d, 0x00, 0x00, 0x00, 0x00}, new(GoEnum)); err == nil { - t.Errorf("Unmarshal = nil, want RequiredNotSetError") - } - // Required field expects a varint, and found both a varint and fixed32 (ignored). - m := new(GoEnum) - if err := Unmarshal([]byte{0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00}, m); err != nil { - t.Errorf("Unmarshal = %v, want nil", err) - } - if !bytes.Equal(m.XXX_unrecognized, []byte{0x0d, 0x00, 0x00, 0x00, 0x00}) { - t.Errorf("expected fixed32 to appear as unknown bytes: %x", m.XXX_unrecognized) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldDeterministicMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - - marshal := func(m Message) []byte { - var b Buffer - b.SetDeterministic(true) - if err := b.Marshal(m); err != nil { - t.Fatalf("Marshal failed: %v", err) - } - return b.Bytes() - } - - want := marshal(m) - for i := 0; i < 10; i++ { - if got := marshal(m); !bytes.Equal(got, want) { - t.Errorf("Marshal produced inconsistent output with determinism enabled (pass %d).\n got %v\nwant %v", i, got, want) - } - } -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(m, m2) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", m, m2) - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: {}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestOneofNilBytes(t *testing.T) { - // A oneof with nil byte slice should marshal to tag + 0 (size), with no error. - m := &Communique{Union: &Communique_Data{Data: nil}} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal failed: %v", err) - } - want := []byte{ - 7<<3 | 2, // tag 7, wire type 2 - 0, // size - } - if !bytes.Equal(b, want) { - t.Errorf("Wrong result of Marshal: got %x, want %x", b, want) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Make sure pure-reflect-based implementation handles -// []int32-[]enum conversion correctly. -func TestRepeatedEnum2(t *testing.T) { - pb := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - b, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal failed: %v", err) - } - x := new(RepeatedEnum) - err = Unmarshal(b, x) - if err != nil { - t.Fatalf("Unmarshal failed: %v", err) - } - if !Equal(pb, x) { - t.Errorf("Incorrect result: want: %v got: %v", pb, x) - } -} - -// TestConcurrentMarshal makes sure that it is safe to marshal -// same message in multiple goroutines concurrently. -func TestConcurrentMarshal(t *testing.T) { - pb := initGoTest(true) - const N = 100 - b := make([][]byte, N) - - var wg sync.WaitGroup - for i := 0; i < N; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - var err error - b[i], err = Marshal(pb) - if err != nil { - t.Errorf("marshal error: %v", err) - } - }(i) - } - - wg.Wait() - for i := 1; i < N; i++ { - if !bytes.Equal(b[0], b[i]) { - t.Errorf("concurrent marshal result not same: b[0] = %v, b[%d] = %v", b[0], i, b[i]) - } - } -} - -func TestInvalidUTF8(t *testing.T) { - const wire = "\x12\x04\xde\xea\xca\xfe" - - var m GoTest - if err := Unmarshal([]byte(wire), &m); err == nil { - t.Errorf("Unmarshal error: got nil, want non-nil") - } - - m.Reset() - m.Table = String(wire[2:]) - if _, err := Marshal(&m); err == nil { - t.Errorf("Marshal error: got nil, want non-nil") - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/examples/github.com/golang/protobuf/proto/any_test.go b/examples/github.com/golang/protobuf/proto/any_test.go deleted file mode 100755 index 56fc97c..0000000 --- a/examples/github.com/golang/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/proto/proto3_proto" - testpb "github.com/golang/protobuf/proto/test_proto" - anypb "github.com/golang/protobuf/ptypes/any" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*anypb.Any{ - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/test_proto.MyMessage]: < - count: 47 - name: "David" - [test_proto.Ext.more]: < - data: "foo" - > - [test_proto.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/test_proto.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [test_proto.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/test_proto.MyMessage]: < - count: 47 - name: "David" - [test_proto.Ext.more]: < - data: "foo" - > - [test_proto.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &anypb.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/examples/github.com/golang/protobuf/proto/clone.go b/examples/github.com/golang/protobuf/proto/clone.go deleted file mode 100755 index 3cd3249..0000000 --- a/examples/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,253 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // Required and optional fields that are set in src will be set to that value in dst. - // Elements of repeated fields will be appended. - // - // Merge may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/examples/github.com/golang/protobuf/proto/clone_test.go b/examples/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100755 index 0d3b127..0000000 --- a/examples/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,390 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/test_proto" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Fatalf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - { // Oneof fields should merge by assignment. - src: &pb.Communique{Union: &pb.Communique_Number{41}}, - dst: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}}, - want: &pb.Communique{Union: &pb.Communique_Number{41}}, - }, - { // Oneof nil is the same as not set. - src: &pb.Communique{}, - dst: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}}, - want: &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Number{1337}}, - dst: &pb.Communique{}, - want: &pb.Communique{Union: &pb.Communique_Number{1337}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Col{pb.MyMessage_RED}}, - dst: &pb.Communique{}, - want: &pb.Communique{Union: &pb.Communique_Col{pb.MyMessage_RED}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Data{[]byte("hello")}}, - dst: &pb.Communique{}, - want: &pb.Communique{Union: &pb.Communique_Data{[]byte("hello")}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}}, - dst: &pb.Communique{}, - want: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Msg{}}, - dst: &pb.Communique{}, - want: &pb.Communique{Union: &pb.Communique_Msg{}}, - }, - { - src: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{StringField: proto.String("123")}}}, - dst: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{BytesField: []byte{1, 2, 3}}}}, - want: &pb.Communique{Union: &pb.Communique_Msg{&pb.Strings{StringField: proto.String("123"), BytesField: []byte{1, 2, 3}}}}, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, // replace - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, - }, - }, - }, - { - src: &pb.GoTest{ - F_BoolRepeated: []bool{}, - F_Int32Repeated: []int32{}, - F_Int64Repeated: []int64{}, - F_Uint32Repeated: []uint32{}, - F_Uint64Repeated: []uint64{}, - F_FloatRepeated: []float32{}, - F_DoubleRepeated: []float64{}, - F_StringRepeated: []string{}, - F_BytesRepeated: [][]byte{}, - }, - dst: &pb.GoTest{}, - want: &pb.GoTest{ - F_BoolRepeated: []bool{}, - F_Int32Repeated: []int32{}, - F_Int64Repeated: []int64{}, - F_Uint32Repeated: []uint32{}, - F_Uint64Repeated: []uint64{}, - F_FloatRepeated: []float32{}, - F_DoubleRepeated: []float64{}, - F_StringRepeated: []string{}, - F_BytesRepeated: [][]byte{}, - }, - }, - { - src: &pb.GoTest{}, - dst: &pb.GoTest{ - F_BoolRepeated: []bool{}, - F_Int32Repeated: []int32{}, - F_Int64Repeated: []int64{}, - F_Uint32Repeated: []uint32{}, - F_Uint64Repeated: []uint64{}, - F_FloatRepeated: []float32{}, - F_DoubleRepeated: []float64{}, - F_StringRepeated: []string{}, - F_BytesRepeated: [][]byte{}, - }, - want: &pb.GoTest{ - F_BoolRepeated: []bool{}, - F_Int32Repeated: []int32{}, - F_Int64Repeated: []int64{}, - F_Uint32Repeated: []uint32{}, - F_Uint64Repeated: []uint64{}, - F_FloatRepeated: []float32{}, - F_DoubleRepeated: []float64{}, - F_StringRepeated: []string{}, - F_BytesRepeated: [][]byte{}, - }, - }, - { - src: &pb.GoTest{ - F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}}, - }, - dst: &pb.GoTest{}, - want: &pb.GoTest{ - F_BytesRepeated: [][]byte{nil, []byte{}, []byte{0}}, - }, - }, - { - src: &pb.MyMessage{ - Others: []*pb.OtherMessage{}, - }, - dst: &pb.MyMessage{}, - want: &pb.MyMessage{ - Others: []*pb.OtherMessage{}, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - if !proto.Equal(got, m.dst) { - t.Errorf("Clone()\ngot %v\nwant %v", got, m.dst) - continue - } - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\ngot %v\nwant %v", m.dst, m.src, got, m.want) - } - } -} diff --git a/examples/github.com/golang/protobuf/proto/decode.go b/examples/github.com/golang/protobuf/proto/decode.go deleted file mode 100755 index d9aa3c4..0000000 --- a/examples/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,428 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - // x -= 0x80 << 63 // Always zero. - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/examples/github.com/golang/protobuf/proto/decode_test.go b/examples/github.com/golang/protobuf/proto/decode_test.go deleted file mode 100755 index 949be3a..0000000 --- a/examples/github.com/golang/protobuf/proto/decode_test.go +++ /dev/null @@ -1,255 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.7 - -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" -) - -var msgBlackhole = new(tpb.Message) - -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -func BenchmarkVarint32ArraySmall(b *testing.B) { - for i := uint(1); i <= 10; i++ { - dist := genInt32Dist([7]int{0, 3, 1}, 1<2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} diff --git a/examples/github.com/golang/protobuf/proto/encode_test.go b/examples/github.com/golang/protobuf/proto/encode_test.go deleted file mode 100755 index a720947..0000000 --- a/examples/github.com/golang/protobuf/proto/encode_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.7 - -package proto_test - -import ( - "strconv" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" - "github.com/golang/protobuf/ptypes" -) - -var ( - blackhole []byte -) - -// BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the -// same. -func BenchmarkAny(b *testing.B) { - data := make([]byte, 1<<20) - quantum := 1 << 10 - for i := uint(0); i <= 10; i++ { - b.Run(strconv.Itoa(quantum<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if len(ext) != len(test.ext) { - t.Errorf("[%s] Wrong length of ComplexExtension: got: %v want: %v\n", test.name, len(ext), len(test.ext)) - } - for i := range test.ext { - if !proto.Equal(ext[i], test.ext[i]) { - t.Errorf("[%s] Wrong value for ComplexExtension[%d]: got: %v want: %v\n", test.name, i, ext[i], test.ext[i]) - } - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !proto.Equal(ext, &want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, &want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - ext := &pb.Ext{} - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, pb.E_Ext_More, ext); err != nil { - t.Fatalf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("Could not marshal message: %v", err) - } - if err := proto.Unmarshal(b, m); err != nil { - t.Fatalf("Could not unmarshal message: %v", err) - } - // after Unmarshal, the extension is in undecoded form. - // GetExtension will decode it lazily. Make sure this does - // not race against Marshal. - - var g errgroup.Group - for n := 3; n > 0; n-- { - g.Go(func() error { - _, err := proto.Marshal(m) - return err - }) - g.Go(func() error { - _, err := proto.GetExtension(m, pb.E_Ext_More) - return err - }) - } - if err := g.Wait(); err != nil { - t.Fatal(err) - } -} diff --git a/examples/github.com/golang/protobuf/proto/lib.go b/examples/github.com/golang/protobuf/proto/lib.go deleted file mode 100755 index 0e2191b..0000000 --- a/examples/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,921 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "errors" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string") - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -// ProtoPackageIsVersion2 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion2 = true - -// ProtoPackageIsVersion1 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion1 = true - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/examples/github.com/golang/protobuf/proto/map_test.go b/examples/github.com/golang/protobuf/proto/map_test.go deleted file mode 100755 index b1e1529..0000000 --- a/examples/github.com/golang/protobuf/proto/map_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package proto_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - ppb "github.com/golang/protobuf/proto/proto3_proto" -) - -func TestMap(t *testing.T) { - var b []byte - fmt.Sscanf("a2010c0a044b657931120456616c31a201130a044b657932120556616c3261120456616c32a201240a044b6579330d05000000120556616c33621a0556616c3361120456616c331505000000a20100a201260a044b657934130a07536f6d6555524c1209536f6d655469746c651a08536e69707065743114", "%x", &b) - - var m ppb.Message - if err := proto.Unmarshal(b, &m); err != nil { - t.Fatalf("proto.Unmarshal error: %v", err) - } - - got := m.StringMap - want := map[string]string{ - "": "", - "Key1": "Val1", - "Key2": "Val2", - "Key3": "Val3", - "Key4": "", - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("maps differ:\ngot %#v\nwant %#v", got, want) - } -} - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/examples/github.com/golang/protobuf/proto/message_set.go b/examples/github.com/golang/protobuf/proto/message_set.go deleted file mode 100755 index 3b6ca41..0000000 --- a/examples/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,314 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "sync" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - return marshalMessageSet(exts, false) -} - -// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. -func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var u marshalInfo - siz := u.sizeMessageSet(exts) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, exts, deterministic) - - case map[int32]Extension: - // This is an old-style extension map. - // Wrap it in a new-style XXX_InternalExtensions. - ie := XXX_InternalExtensions{ - p: &struct { - mu sync.Mutex - extensionMap map[int32]Extension - }{ - extensionMap: exts, - }, - } - - var u marshalInfo - siz := u.sizeMessageSet(&ie) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, &ie, deterministic) - - default: - return nil, errors.New("proto: not an extension map") - } -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var mu sync.Locker - m, mu = exts.extensionsRead() - if m != nil { - // Keep the extensions map locked until we're done marshaling to prevent - // races between marshaling and unmarshaling the lazily-{en,de}coded - // values. - mu.Lock() - defer mu.Unlock() - } - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - - if i > 0 && b.Len() > 1 { - b.WriteByte(',') - } - - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/examples/github.com/golang/protobuf/proto/message_set_test.go b/examples/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100755 index 2c170c5..0000000 --- a/examples/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} - -func TestMarshalMessageSetJSON_UnknownType(t *testing.T) { - extMap := map[int32]Extension{12345: Extension{}} - got, err := MarshalMessageSetJSON(extMap) - if err != nil { - t.Fatalf("MarshalMessageSetJSON: %v", err) - } - if want := []byte("{}"); !bytes.Equal(got, want) { - t.Errorf("MarshalMessageSetJSON(%v) = %q, want %q", extMap, got, want) - } -} diff --git a/examples/github.com/golang/protobuf/proto/pointer_reflect.go b/examples/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100755 index b6cad90..0000000 --- a/examples/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,357 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/examples/github.com/golang/protobuf/proto/pointer_unsafe.go b/examples/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100755 index d55a335..0000000 --- a/examples/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,308 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } - // The interface is not of pointer type. The data word is the pointer - // to the data. - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/examples/github.com/golang/protobuf/proto/properties.go b/examples/github.com/golang/protobuf/proto/properties.go deleted file mode 100755 index f710ada..0000000 --- a/examples/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,544 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field; set for []byte only - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - - mtype reflect.Type // set for map types only - mkeyprop *Properties // set for map types only - mvalprop *Properties // set for map types only -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.mkeyprop = &Properties{} - p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.mvalprop = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - p.setFieldProps(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - if collectStats { - stats.Chit++ - } - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } - return prop - } - if collectStats { - stats.Cmiss++ - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - var oots []interface{} - _, _, _, oots = om.XXX_OneofFuncs() - - // Interpret oneof metadata. - prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T - Prop: new(Properties), - } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue - } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break - } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go deleted file mode 100755 index a80f089..0000000 --- a/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go +++ /dev/null @@ -1,461 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto3_proto/proto3.proto - -package proto3_proto - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import test_proto "github.com/golang/protobuf/proto/test_proto" -import any "github.com/golang/protobuf/ptypes/any" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Message_Humour int32 - -const ( - Message_UNKNOWN Message_Humour = 0 - Message_PUNS Message_Humour = 1 - Message_SLAPSTICK Message_Humour = 2 - Message_BILL_BAILEY Message_Humour = 3 -) - -var Message_Humour_name = map[int32]string{ - 0: "UNKNOWN", - 1: "PUNS", - 2: "SLAPSTICK", - 3: "BILL_BAILEY", -} -var Message_Humour_value = map[string]int32{ - "UNKNOWN": 0, - "PUNS": 1, - "SLAPSTICK": 2, - "BILL_BAILEY": 3, -} - -func (x Message_Humour) String() string { - return proto.EnumName(Message_Humour_name, int32(x)) -} -func (Message_Humour) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{0, 0} -} - -type Message struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` - HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"` - Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` - ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"` - TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"` - Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` - Key []uint64 `protobuf:"varint,5,rep,packed,name=key" json:"key,omitempty"` - ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey" json:"short_key,omitempty"` - Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` - RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"` - Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Proto2Field *test_proto.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"` - Proto2Value map[string]*test_proto.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Anything *any.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"` - ManyThings []*any.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"` - Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"` - Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"` - StringMap map[string]string `protobuf:"bytes,20,rep,name=string_map,json=stringMap" json:"string_map,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Message.Unmarshal(m, b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) -} -func (dst *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(dst, src) -} -func (m *Message) XXX_Size() int { - return xxx_messageInfo_Message.Size(m) -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -func (m *Message) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Message) GetHilarity() Message_Humour { - if m != nil { - return m.Hilarity - } - return Message_UNKNOWN -} - -func (m *Message) GetHeightInCm() uint32 { - if m != nil { - return m.HeightInCm - } - return 0 -} - -func (m *Message) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *Message) GetResultCount() int64 { - if m != nil { - return m.ResultCount - } - return 0 -} - -func (m *Message) GetTrueScotsman() bool { - if m != nil { - return m.TrueScotsman - } - return false -} - -func (m *Message) GetScore() float32 { - if m != nil { - return m.Score - } - return 0 -} - -func (m *Message) GetKey() []uint64 { - if m != nil { - return m.Key - } - return nil -} - -func (m *Message) GetShortKey() []int32 { - if m != nil { - return m.ShortKey - } - return nil -} - -func (m *Message) GetNested() *Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *Message) GetRFunny() []Message_Humour { - if m != nil { - return m.RFunny - } - return nil -} - -func (m *Message) GetTerrain() map[string]*Nested { - if m != nil { - return m.Terrain - } - return nil -} - -func (m *Message) GetProto2Field() *test_proto.SubDefaults { - if m != nil { - return m.Proto2Field - } - return nil -} - -func (m *Message) GetProto2Value() map[string]*test_proto.SubDefaults { - if m != nil { - return m.Proto2Value - } - return nil -} - -func (m *Message) GetAnything() *any.Any { - if m != nil { - return m.Anything - } - return nil -} - -func (m *Message) GetManyThings() []*any.Any { - if m != nil { - return m.ManyThings - } - return nil -} - -func (m *Message) GetSubmessage() *Message { - if m != nil { - return m.Submessage - } - return nil -} - -func (m *Message) GetChildren() []*Message { - if m != nil { - return m.Children - } - return nil -} - -func (m *Message) GetStringMap() map[string]string { - if m != nil { - return m.StringMap - } - return nil -} - -type Nested struct { - Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` - Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Nested) Reset() { *m = Nested{} } -func (m *Nested) String() string { return proto.CompactTextString(m) } -func (*Nested) ProtoMessage() {} -func (*Nested) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{1} -} -func (m *Nested) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Nested.Unmarshal(m, b) -} -func (m *Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Nested.Marshal(b, m, deterministic) -} -func (dst *Nested) XXX_Merge(src proto.Message) { - xxx_messageInfo_Nested.Merge(dst, src) -} -func (m *Nested) XXX_Size() int { - return xxx_messageInfo_Nested.Size(m) -} -func (m *Nested) XXX_DiscardUnknown() { - xxx_messageInfo_Nested.DiscardUnknown(m) -} - -var xxx_messageInfo_Nested proto.InternalMessageInfo - -func (m *Nested) GetBunny() string { - if m != nil { - return m.Bunny - } - return "" -} - -func (m *Nested) GetCute() bool { - if m != nil { - return m.Cute - } - return false -} - -type MessageWithMap struct { - ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} -func (*MessageWithMap) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{2} -} -func (m *MessageWithMap) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageWithMap.Unmarshal(m, b) -} -func (m *MessageWithMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageWithMap.Marshal(b, m, deterministic) -} -func (dst *MessageWithMap) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageWithMap.Merge(dst, src) -} -func (m *MessageWithMap) XXX_Size() int { - return xxx_messageInfo_MessageWithMap.Size(m) -} -func (m *MessageWithMap) XXX_DiscardUnknown() { - xxx_messageInfo_MessageWithMap.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageWithMap proto.InternalMessageInfo - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -type IntMap struct { - Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *IntMap) Reset() { *m = IntMap{} } -func (m *IntMap) String() string { return proto.CompactTextString(m) } -func (*IntMap) ProtoMessage() {} -func (*IntMap) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{3} -} -func (m *IntMap) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_IntMap.Unmarshal(m, b) -} -func (m *IntMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_IntMap.Marshal(b, m, deterministic) -} -func (dst *IntMap) XXX_Merge(src proto.Message) { - xxx_messageInfo_IntMap.Merge(dst, src) -} -func (m *IntMap) XXX_Size() int { - return xxx_messageInfo_IntMap.Size(m) -} -func (m *IntMap) XXX_DiscardUnknown() { - xxx_messageInfo_IntMap.DiscardUnknown(m) -} - -var xxx_messageInfo_IntMap proto.InternalMessageInfo - -func (m *IntMap) GetRtt() map[int32]int32 { - if m != nil { - return m.Rtt - } - return nil -} - -type IntMaps struct { - Maps []*IntMap `protobuf:"bytes,1,rep,name=maps" json:"maps,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *IntMaps) Reset() { *m = IntMaps{} } -func (m *IntMaps) String() string { return proto.CompactTextString(m) } -func (*IntMaps) ProtoMessage() {} -func (*IntMaps) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_e706e4ff19a5dbea, []int{4} -} -func (m *IntMaps) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_IntMaps.Unmarshal(m, b) -} -func (m *IntMaps) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_IntMaps.Marshal(b, m, deterministic) -} -func (dst *IntMaps) XXX_Merge(src proto.Message) { - xxx_messageInfo_IntMaps.Merge(dst, src) -} -func (m *IntMaps) XXX_Size() int { - return xxx_messageInfo_IntMaps.Size(m) -} -func (m *IntMaps) XXX_DiscardUnknown() { - xxx_messageInfo_IntMaps.DiscardUnknown(m) -} - -var xxx_messageInfo_IntMaps proto.InternalMessageInfo - -func (m *IntMaps) GetMaps() []*IntMap { - if m != nil { - return m.Maps - } - return nil -} - -func init() { - proto.RegisterType((*Message)(nil), "proto3_proto.Message") - proto.RegisterMapType((map[string]*test_proto.SubDefaults)(nil), "proto3_proto.Message.Proto2ValueEntry") - proto.RegisterMapType((map[string]string)(nil), "proto3_proto.Message.StringMapEntry") - proto.RegisterMapType((map[string]*Nested)(nil), "proto3_proto.Message.TerrainEntry") - proto.RegisterType((*Nested)(nil), "proto3_proto.Nested") - proto.RegisterType((*MessageWithMap)(nil), "proto3_proto.MessageWithMap") - proto.RegisterMapType((map[bool][]byte)(nil), "proto3_proto.MessageWithMap.ByteMappingEntry") - proto.RegisterType((*IntMap)(nil), "proto3_proto.IntMap") - proto.RegisterMapType((map[int32]int32)(nil), "proto3_proto.IntMap.RttEntry") - proto.RegisterType((*IntMaps)(nil), "proto3_proto.IntMaps") - proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) -} - -func init() { proto.RegisterFile("proto3_proto/proto3.proto", fileDescriptor_proto3_e706e4ff19a5dbea) } - -var fileDescriptor_proto3_e706e4ff19a5dbea = []byte{ - // 774 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x94, 0x6f, 0x8f, 0xdb, 0x44, - 0x10, 0xc6, 0x71, 0x9c, 0x3f, 0xce, 0xd8, 0x77, 0x35, 0x4b, 0x2a, 0xb6, 0x01, 0x24, 0x13, 0x10, - 0xb2, 0x10, 0xf5, 0x41, 0xaa, 0x43, 0x55, 0x55, 0x81, 0xee, 0x8e, 0x56, 0x44, 0x77, 0x17, 0xa2, - 0xcd, 0x95, 0x13, 0xaf, 0xac, 0x4d, 0x6e, 0x93, 0x58, 0xc4, 0xeb, 0xe0, 0x5d, 0x23, 0xf9, 0x0b, - 0xf0, 0x41, 0xf8, 0xa4, 0x68, 0x77, 0x9d, 0xd4, 0xa9, 0x5c, 0xfa, 0x2a, 0xbb, 0x8f, 0x7f, 0x33, - 0xcf, 0x78, 0x66, 0x1c, 0x78, 0xb2, 0xcb, 0x33, 0x99, 0x3d, 0x8b, 0xf5, 0xcf, 0x99, 0xb9, 0x44, - 0xfa, 0x07, 0x79, 0xf5, 0x47, 0xc3, 0x27, 0xeb, 0x2c, 0x5b, 0x6f, 0x99, 0x41, 0x16, 0xc5, 0xea, - 0x8c, 0xf2, 0xd2, 0x80, 0xc3, 0xc7, 0x92, 0x09, 0x59, 0x65, 0x50, 0x47, 0x23, 0x8f, 0xfe, 0xe9, - 0x43, 0xef, 0x96, 0x09, 0x41, 0xd7, 0x0c, 0x21, 0x68, 0x73, 0x9a, 0x32, 0x6c, 0x05, 0x56, 0xd8, - 0x27, 0xfa, 0x8c, 0x9e, 0x83, 0xb3, 0x49, 0xb6, 0x34, 0x4f, 0x64, 0x89, 0x5b, 0x81, 0x15, 0x9e, - 0x8e, 0x3f, 0x8f, 0xea, 0x96, 0x51, 0x15, 0x1c, 0xfd, 0x5a, 0xa4, 0x59, 0x91, 0x93, 0x03, 0x8d, - 0x02, 0xf0, 0x36, 0x2c, 0x59, 0x6f, 0x64, 0x9c, 0xf0, 0x78, 0x99, 0x62, 0x3b, 0xb0, 0xc2, 0x13, - 0x02, 0x46, 0x9b, 0xf0, 0xab, 0x54, 0xf9, 0x3d, 0x50, 0x49, 0x71, 0x3b, 0xb0, 0x42, 0x8f, 0xe8, - 0x33, 0xfa, 0x12, 0xbc, 0x9c, 0x89, 0x62, 0x2b, 0xe3, 0x65, 0x56, 0x70, 0x89, 0x7b, 0x81, 0x15, - 0xda, 0xc4, 0x35, 0xda, 0x95, 0x92, 0xd0, 0x57, 0x70, 0x22, 0xf3, 0x82, 0xc5, 0x62, 0x99, 0x49, - 0x91, 0x52, 0x8e, 0x9d, 0xc0, 0x0a, 0x1d, 0xe2, 0x29, 0x71, 0x5e, 0x69, 0x68, 0x00, 0x1d, 0xb1, - 0xcc, 0x72, 0x86, 0xfb, 0x81, 0x15, 0xb6, 0x88, 0xb9, 0x20, 0x1f, 0xec, 0x3f, 0x59, 0x89, 0x3b, - 0x81, 0x1d, 0xb6, 0x89, 0x3a, 0xa2, 0xcf, 0xa0, 0x2f, 0x36, 0x59, 0x2e, 0x63, 0xa5, 0x7f, 0x12, - 0xd8, 0x61, 0x87, 0x38, 0x5a, 0xb8, 0x66, 0x25, 0xfa, 0x0e, 0xba, 0x9c, 0x09, 0xc9, 0x1e, 0x70, - 0x37, 0xb0, 0x42, 0x77, 0x3c, 0x38, 0x7e, 0xf5, 0xa9, 0x7e, 0x46, 0x2a, 0x06, 0x9d, 0x43, 0x2f, - 0x8f, 0x57, 0x05, 0xe7, 0x25, 0xf6, 0x03, 0xfb, 0x83, 0x9d, 0xea, 0xe6, 0xaf, 0x15, 0x8b, 0x5e, - 0x42, 0x4f, 0xb2, 0x3c, 0xa7, 0x09, 0xc7, 0x10, 0xd8, 0xa1, 0x3b, 0x1e, 0x35, 0x87, 0xdd, 0x19, - 0xe8, 0x15, 0x97, 0x79, 0x49, 0xf6, 0x21, 0xe8, 0x05, 0x98, 0x0d, 0x18, 0xc7, 0xab, 0x84, 0x6d, - 0x1f, 0xb0, 0xab, 0x0b, 0xfd, 0x34, 0x7a, 0x3b, 0xed, 0x68, 0x5e, 0x2c, 0x7e, 0x61, 0x2b, 0x5a, - 0x6c, 0xa5, 0x20, 0xae, 0x81, 0x5f, 0x2b, 0x16, 0x4d, 0x0e, 0xb1, 0x7f, 0xd3, 0x6d, 0xc1, 0xf0, - 0x89, 0xb6, 0xff, 0xa6, 0xd9, 0x7e, 0xa6, 0xc9, 0xdf, 0x15, 0x68, 0x4a, 0xa8, 0x52, 0x69, 0x05, - 0x7d, 0x0f, 0x0e, 0xe5, 0xa5, 0xdc, 0x24, 0x7c, 0x8d, 0x4f, 0xab, 0x5e, 0x99, 0x5d, 0x8c, 0xf6, - 0xbb, 0x18, 0x5d, 0xf0, 0x92, 0x1c, 0x28, 0x74, 0x0e, 0x6e, 0x4a, 0x79, 0x19, 0xeb, 0x9b, 0xc0, - 0x8f, 0xb4, 0x77, 0x73, 0x10, 0x28, 0xf0, 0x4e, 0x73, 0xe8, 0x1c, 0x40, 0x14, 0x8b, 0xd4, 0x14, - 0x85, 0x3f, 0xd6, 0x56, 0x8f, 0x1b, 0x2b, 0x26, 0x35, 0x10, 0xfd, 0x00, 0xce, 0x72, 0x93, 0x6c, - 0x1f, 0x72, 0xc6, 0x31, 0xd2, 0x56, 0xef, 0x09, 0x3a, 0x60, 0xe8, 0x0a, 0x40, 0xc8, 0x3c, 0xe1, - 0xeb, 0x38, 0xa5, 0x3b, 0x3c, 0xd0, 0x41, 0x5f, 0x37, 0xf7, 0x66, 0xae, 0xb9, 0x5b, 0xba, 0x33, - 0x9d, 0xe9, 0x8b, 0xfd, 0x7d, 0x38, 0x03, 0xaf, 0x3e, 0xb7, 0xfd, 0x02, 0x9a, 0x2f, 0x4c, 0x2f, - 0xe0, 0xb7, 0xd0, 0x31, 0xdd, 0x6f, 0xfd, 0xcf, 0x8a, 0x19, 0xe4, 0x45, 0xeb, 0xb9, 0x35, 0xbc, - 0x07, 0xff, 0xdd, 0x51, 0x34, 0x64, 0x7d, 0x7a, 0x9c, 0xf5, 0xbd, 0xfb, 0x50, 0x4b, 0xfc, 0x12, - 0x4e, 0x8f, 0xdf, 0xa3, 0x21, 0xed, 0xa0, 0x9e, 0xb6, 0x5f, 0x8b, 0x1e, 0xfd, 0x0c, 0x5d, 0xb3, - 0xd7, 0xc8, 0x85, 0xde, 0x9b, 0xe9, 0xf5, 0xf4, 0xb7, 0xfb, 0xa9, 0xff, 0x11, 0x72, 0xa0, 0x3d, - 0x7b, 0x33, 0x9d, 0xfb, 0x16, 0x3a, 0x81, 0xfe, 0xfc, 0xe6, 0x62, 0x36, 0xbf, 0x9b, 0x5c, 0x5d, - 0xfb, 0x2d, 0xf4, 0x08, 0xdc, 0xcb, 0xc9, 0xcd, 0x4d, 0x7c, 0x79, 0x31, 0xb9, 0x79, 0xf5, 0x87, - 0x6f, 0x8f, 0xc6, 0xd0, 0x35, 0x2f, 0xab, 0x4c, 0x16, 0xfa, 0x2b, 0x32, 0xc6, 0xe6, 0xa2, 0xfe, - 0x2c, 0x96, 0x85, 0x34, 0xce, 0x0e, 0xd1, 0xe7, 0xd1, 0xbf, 0x16, 0x9c, 0x56, 0x33, 0xb8, 0x4f, - 0xe4, 0xe6, 0x96, 0xee, 0xd0, 0x0c, 0xbc, 0x45, 0x29, 0x99, 0x9a, 0xd9, 0x4e, 0x2d, 0xa3, 0xa5, - 0xe7, 0xf6, 0xb4, 0x71, 0x6e, 0x55, 0x4c, 0x74, 0x59, 0x4a, 0x76, 0x6b, 0xf8, 0x6a, 0xb5, 0x17, - 0x6f, 0x95, 0xe1, 0x4f, 0xe0, 0xbf, 0x0b, 0xd4, 0x3b, 0xe3, 0x34, 0x74, 0xc6, 0xab, 0x77, 0xe6, - 0x2f, 0xe8, 0x4e, 0xb8, 0x54, 0xb5, 0x9d, 0x81, 0x9d, 0x4b, 0x59, 0x95, 0xf4, 0xc5, 0x71, 0x49, - 0x06, 0x89, 0x88, 0x94, 0xa6, 0x04, 0x45, 0x0e, 0x7f, 0x04, 0x67, 0x2f, 0xd4, 0x2d, 0x3b, 0x0d, - 0x96, 0x9d, 0xba, 0xe5, 0x33, 0xe8, 0x99, 0x7c, 0x02, 0x85, 0xd0, 0x4e, 0xe9, 0x4e, 0x54, 0xa6, - 0x83, 0x26, 0x53, 0xa2, 0x89, 0x45, 0xd7, 0x3c, 0xfa, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x99, 0x24, - 0x6b, 0x12, 0x6d, 0x06, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.proto deleted file mode 100755 index c81fe1e..0000000 --- a/examples/github.com/golang/protobuf/proto/proto3_proto/proto3.proto +++ /dev/null @@ -1,89 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -import "google/protobuf/any.proto"; -import "test_proto/test.proto"; - -package proto3_proto; - -message Message { - enum Humour { - UNKNOWN = 0; - PUNS = 1; - SLAPSTICK = 2; - BILL_BAILEY = 3; - } - - string name = 1; - Humour hilarity = 2; - uint32 height_in_cm = 3; - bytes data = 4; - int64 result_count = 7; - bool true_scotsman = 8; - float score = 9; - - repeated uint64 key = 5; - repeated int32 short_key = 19; - Nested nested = 6; - repeated Humour r_funny = 16; - - map terrain = 10; - test_proto.SubDefaults proto2_field = 11; - map proto2_value = 13; - - google.protobuf.Any anything = 14; - repeated google.protobuf.Any many_things = 15; - - Message submessage = 17; - repeated Message children = 18; - - map string_map = 20; -} - -message Nested { - string bunny = 1; - bool cute = 2; -} - -message MessageWithMap { - map byte_mapping = 1; -} - - -message IntMap { - map rtt = 1; -} - -message IntMaps { - repeated IntMap maps = 1; -} diff --git a/examples/github.com/golang/protobuf/proto/proto3_test.go b/examples/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100755 index 73eed6c..0000000 --- a/examples/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,151 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/test_proto" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} - -func TestUnknownFieldPreservation(t *testing.T) { - b1 := "\x0a\x05David" // Known tag 1 - b2 := "\xc2\x0c\x06Google" // Unknown tag 200 - b := []byte(b1 + b2) - - m := new(pb.Message) - if err := proto.Unmarshal(b, m); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - - if !bytes.Equal(m.XXX_unrecognized, []byte(b2)) { - t.Fatalf("mismatching unknown fields:\ngot %q\nwant %q", m.XXX_unrecognized, b2) - } -} diff --git a/examples/github.com/golang/protobuf/proto/size2_test.go b/examples/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100755 index 7846b06..0000000 --- a/examples/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := SizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/examples/github.com/golang/protobuf/proto/size_test.go b/examples/github.com/golang/protobuf/proto/size_test.go deleted file mode 100755 index 3abac41..0000000 --- a/examples/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/test_proto" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -// non-pointer custom message -type nonptrMessage struct{} - -func (m nonptrMessage) ProtoMessage() {} -func (m nonptrMessage) Reset() {} -func (m nonptrMessage) String() string { return "" } - -func (m nonptrMessage) Marshal() ([]byte, error) { - return []byte{42}, nil -} - -// custom message embedding a proto.Message -type messageWithEmbedding struct { - *pb.OtherMessage -} - -func (m *messageWithEmbedding) ProtoMessage() {} -func (m *messageWithEmbedding) Reset() {} -func (m *messageWithEmbedding) String() string { return "" } - -func (m *messageWithEmbedding) Marshal() ([]byte, error) { - return []byte{42}, nil -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, - - {"non-pointer message", nonptrMessage{}}, - {"custom message with embedding", &messageWithEmbedding{&pb.OtherMessage{}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/examples/github.com/golang/protobuf/proto/table_marshal.go b/examples/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100755 index 0f212b3..0000000 --- a/examples/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2681 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errreq error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required && errreq == nil { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - errreq = &RequiredNotSetError{f.name} - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errreq -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(t, tags, false, false) - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if err != nil { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != nil && err != ErrNil { // allow nil value in map - return b, err - } - } - return b, nil - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if err != nil { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if err != nil { - return b, err - } - } - return b, nil -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/examples/github.com/golang/protobuf/proto/table_merge.go b/examples/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100755 index 5525def..0000000 --- a/examples/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/examples/github.com/golang/protobuf/proto/table_unmarshal.go b/examples/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100755 index 55f0340..0000000 --- a/examples/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,1967 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - rnse = r - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if rnse != nil { - // A required field of a submessage/group is missing. Return that error. - return rnse - } - if reqMask != u.reqMask { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - return &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return nil -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask) - } - - // Find any types associated with oneof fields. - // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") - if fn.IsValid() { - res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} - for i := res.Len() - 1; i >= 0; i-- { - v := res.Index(i) // interface{} - tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tagstr := strings.Split(f.Tag.Get("protobuf"), ",")[1] - tag, err := strconv.Atoi(tagstr) - if err != nil { - panic("protobuf tag field not an integer: " + tagstr) - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(tag, of.field, unmarshal, 0) - } - } - } - } - - // Get extension ranges, if any. - fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0) - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if err == nil { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nil - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if err != nil { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nil - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) <= 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/examples/github.com/golang/protobuf/proto/test_proto/test.pb.go b/examples/github.com/golang/protobuf/proto/test_proto/test.pb.go deleted file mode 100755 index 049b5dd..0000000 --- a/examples/github.com/golang/protobuf/proto/test_proto/test.pb.go +++ /dev/null @@ -1,5118 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: test_proto/test.proto - -package test_proto // import "github.com/golang/protobuf/proto/test_proto" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type FOO int32 - -const ( - FOO_FOO1 FOO = 1 -) - -var FOO_name = map[int32]string{ - 1: "FOO1", -} -var FOO_value = map[string]int32{ - "FOO1": 1, -} - -func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p -} -func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) -} -func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") - if err != nil { - return err - } - *x = FOO(value) - return nil -} -func (FOO) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{0} -} - -// An enum, for completeness. -type GoTest_KIND int32 - -const ( - GoTest_VOID GoTest_KIND = 0 - // Basic types - GoTest_BOOL GoTest_KIND = 1 - GoTest_BYTES GoTest_KIND = 2 - GoTest_FINGERPRINT GoTest_KIND = 3 - GoTest_FLOAT GoTest_KIND = 4 - GoTest_INT GoTest_KIND = 5 - GoTest_STRING GoTest_KIND = 6 - GoTest_TIME GoTest_KIND = 7 - // Groupings - GoTest_TUPLE GoTest_KIND = 8 - GoTest_ARRAY GoTest_KIND = 9 - GoTest_MAP GoTest_KIND = 10 - // Table types - GoTest_TABLE GoTest_KIND = 11 - // Functions - GoTest_FUNCTION GoTest_KIND = 12 -) - -var GoTest_KIND_name = map[int32]string{ - 0: "VOID", - 1: "BOOL", - 2: "BYTES", - 3: "FINGERPRINT", - 4: "FLOAT", - 5: "INT", - 6: "STRING", - 7: "TIME", - 8: "TUPLE", - 9: "ARRAY", - 10: "MAP", - 11: "TABLE", - 12: "FUNCTION", -} -var GoTest_KIND_value = map[string]int32{ - "VOID": 0, - "BOOL": 1, - "BYTES": 2, - "FINGERPRINT": 3, - "FLOAT": 4, - "INT": 5, - "STRING": 6, - "TIME": 7, - "TUPLE": 8, - "ARRAY": 9, - "MAP": 10, - "TABLE": 11, - "FUNCTION": 12, -} - -func (x GoTest_KIND) Enum() *GoTest_KIND { - p := new(GoTest_KIND) - *p = x - return p -} -func (x GoTest_KIND) String() string { - return proto.EnumName(GoTest_KIND_name, int32(x)) -} -func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") - if err != nil { - return err - } - *x = GoTest_KIND(value) - return nil -} -func (GoTest_KIND) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{2, 0} -} - -type MyMessage_Color int32 - -const ( - MyMessage_RED MyMessage_Color = 0 - MyMessage_GREEN MyMessage_Color = 1 - MyMessage_BLUE MyMessage_Color = 2 -) - -var MyMessage_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var MyMessage_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x MyMessage_Color) Enum() *MyMessage_Color { - p := new(MyMessage_Color) - *p = x - return p -} -func (x MyMessage_Color) String() string { - return proto.EnumName(MyMessage_Color_name, int32(x)) -} -func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") - if err != nil { - return err - } - *x = MyMessage_Color(value) - return nil -} -func (MyMessage_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{13, 0} -} - -type DefaultsMessage_DefaultsEnum int32 - -const ( - DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 - DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 - DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 -) - -var DefaultsMessage_DefaultsEnum_name = map[int32]string{ - 0: "ZERO", - 1: "ONE", - 2: "TWO", -} -var DefaultsMessage_DefaultsEnum_value = map[string]int32{ - "ZERO": 0, - "ONE": 1, - "TWO": 2, -} - -func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { - p := new(DefaultsMessage_DefaultsEnum) - *p = x - return p -} -func (x DefaultsMessage_DefaultsEnum) String() string { - return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) -} -func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") - if err != nil { - return err - } - *x = DefaultsMessage_DefaultsEnum(value) - return nil -} -func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{16, 0} -} - -type Defaults_Color int32 - -const ( - Defaults_RED Defaults_Color = 0 - Defaults_GREEN Defaults_Color = 1 - Defaults_BLUE Defaults_Color = 2 -) - -var Defaults_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Defaults_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Defaults_Color) Enum() *Defaults_Color { - p := new(Defaults_Color) - *p = x - return p -} -func (x Defaults_Color) String() string { - return proto.EnumName(Defaults_Color_name, int32(x)) -} -func (x *Defaults_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") - if err != nil { - return err - } - *x = Defaults_Color(value) - return nil -} -func (Defaults_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{21, 0} -} - -type RepeatedEnum_Color int32 - -const ( - RepeatedEnum_RED RepeatedEnum_Color = 1 -) - -var RepeatedEnum_Color_name = map[int32]string{ - 1: "RED", -} -var RepeatedEnum_Color_value = map[string]int32{ - "RED": 1, -} - -func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { - p := new(RepeatedEnum_Color) - *p = x - return p -} -func (x RepeatedEnum_Color) String() string { - return proto.EnumName(RepeatedEnum_Color_name, int32(x)) -} -func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") - if err != nil { - return err - } - *x = RepeatedEnum_Color(value) - return nil -} -func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{23, 0} -} - -type GoEnum struct { - Foo *FOO `protobuf:"varint,1,req,name=foo,enum=test_proto.FOO" json:"foo,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoEnum) Reset() { *m = GoEnum{} } -func (m *GoEnum) String() string { return proto.CompactTextString(m) } -func (*GoEnum) ProtoMessage() {} -func (*GoEnum) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{0} -} -func (m *GoEnum) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoEnum.Unmarshal(m, b) -} -func (m *GoEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoEnum.Marshal(b, m, deterministic) -} -func (dst *GoEnum) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoEnum.Merge(dst, src) -} -func (m *GoEnum) XXX_Size() int { - return xxx_messageInfo_GoEnum.Size(m) -} -func (m *GoEnum) XXX_DiscardUnknown() { - xxx_messageInfo_GoEnum.DiscardUnknown(m) -} - -var xxx_messageInfo_GoEnum proto.InternalMessageInfo - -func (m *GoEnum) GetFoo() FOO { - if m != nil && m.Foo != nil { - return *m.Foo - } - return FOO_FOO1 -} - -type GoTestField struct { - Label *string `protobuf:"bytes,1,req,name=Label" json:"Label,omitempty"` - Type *string `protobuf:"bytes,2,req,name=Type" json:"Type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTestField) Reset() { *m = GoTestField{} } -func (m *GoTestField) String() string { return proto.CompactTextString(m) } -func (*GoTestField) ProtoMessage() {} -func (*GoTestField) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{1} -} -func (m *GoTestField) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTestField.Unmarshal(m, b) -} -func (m *GoTestField) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTestField.Marshal(b, m, deterministic) -} -func (dst *GoTestField) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTestField.Merge(dst, src) -} -func (m *GoTestField) XXX_Size() int { - return xxx_messageInfo_GoTestField.Size(m) -} -func (m *GoTestField) XXX_DiscardUnknown() { - xxx_messageInfo_GoTestField.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTestField proto.InternalMessageInfo - -func (m *GoTestField) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" -} - -func (m *GoTestField) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -type GoTest struct { - // Some typical parameters - Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=test_proto.GoTest_KIND" json:"Kind,omitempty"` - Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"` - Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"` - // Required, repeated and optional foreign fields. - RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField" json:"RequiredField,omitempty"` - RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField" json:"RepeatedField,omitempty"` - OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField" json:"OptionalField,omitempty"` - // Required fields of all basic types - F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=FBoolRequired" json:"F_Bool_required,omitempty"` - F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=FInt32Required" json:"F_Int32_required,omitempty"` - F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=FInt64Required" json:"F_Int64_required,omitempty"` - F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=FFixed32Required" json:"F_Fixed32_required,omitempty"` - F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=FFixed64Required" json:"F_Fixed64_required,omitempty"` - F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=FUint32Required" json:"F_Uint32_required,omitempty"` - F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=FUint64Required" json:"F_Uint64_required,omitempty"` - F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=FFloatRequired" json:"F_Float_required,omitempty"` - F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=FDoubleRequired" json:"F_Double_required,omitempty"` - F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=FStringRequired" json:"F_String_required,omitempty"` - F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=FBytesRequired" json:"F_Bytes_required,omitempty"` - F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=FSint32Required" json:"F_Sint32_required,omitempty"` - F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=FSint64Required" json:"F_Sint64_required,omitempty"` - F_Sfixed32Required *int32 `protobuf:"fixed32,104,req,name=F_Sfixed32_required,json=FSfixed32Required" json:"F_Sfixed32_required,omitempty"` - F_Sfixed64Required *int64 `protobuf:"fixed64,105,req,name=F_Sfixed64_required,json=FSfixed64Required" json:"F_Sfixed64_required,omitempty"` - // Repeated fields of all basic types - F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=FBoolRepeated" json:"F_Bool_repeated,omitempty"` - F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=FInt32Repeated" json:"F_Int32_repeated,omitempty"` - F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=FInt64Repeated" json:"F_Int64_repeated,omitempty"` - F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=FFixed32Repeated" json:"F_Fixed32_repeated,omitempty"` - F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=FFixed64Repeated" json:"F_Fixed64_repeated,omitempty"` - F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=FUint32Repeated" json:"F_Uint32_repeated,omitempty"` - F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=FUint64Repeated" json:"F_Uint64_repeated,omitempty"` - F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=FFloatRepeated" json:"F_Float_repeated,omitempty"` - F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=FDoubleRepeated" json:"F_Double_repeated,omitempty"` - F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=FStringRepeated" json:"F_String_repeated,omitempty"` - F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=FBytesRepeated" json:"F_Bytes_repeated,omitempty"` - F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=FSint32Repeated" json:"F_Sint32_repeated,omitempty"` - F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=FSint64Repeated" json:"F_Sint64_repeated,omitempty"` - F_Sfixed32Repeated []int32 `protobuf:"fixed32,204,rep,name=F_Sfixed32_repeated,json=FSfixed32Repeated" json:"F_Sfixed32_repeated,omitempty"` - F_Sfixed64Repeated []int64 `protobuf:"fixed64,205,rep,name=F_Sfixed64_repeated,json=FSfixed64Repeated" json:"F_Sfixed64_repeated,omitempty"` - // Optional fields of all basic types - F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=FBoolOptional" json:"F_Bool_optional,omitempty"` - F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=FInt32Optional" json:"F_Int32_optional,omitempty"` - F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=FInt64Optional" json:"F_Int64_optional,omitempty"` - F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=FFixed32Optional" json:"F_Fixed32_optional,omitempty"` - F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=FFixed64Optional" json:"F_Fixed64_optional,omitempty"` - F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=FUint32Optional" json:"F_Uint32_optional,omitempty"` - F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=FUint64Optional" json:"F_Uint64_optional,omitempty"` - F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=FFloatOptional" json:"F_Float_optional,omitempty"` - F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=FDoubleOptional" json:"F_Double_optional,omitempty"` - F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=FStringOptional" json:"F_String_optional,omitempty"` - F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=FBytesOptional" json:"F_Bytes_optional,omitempty"` - F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=FSint32Optional" json:"F_Sint32_optional,omitempty"` - F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=FSint64Optional" json:"F_Sint64_optional,omitempty"` - F_Sfixed32Optional *int32 `protobuf:"fixed32,304,opt,name=F_Sfixed32_optional,json=FSfixed32Optional" json:"F_Sfixed32_optional,omitempty"` - F_Sfixed64Optional *int64 `protobuf:"fixed64,305,opt,name=F_Sfixed64_optional,json=FSfixed64Optional" json:"F_Sfixed64_optional,omitempty"` - // Default-valued fields of all basic types - F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=FBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"` - F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=FInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"` - F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=FInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"` - F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=FFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` - F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=FFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` - F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=FUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` - F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=FUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` - F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=FFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"` - F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=FDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"` - F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=FStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` - F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=FBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` - F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=FSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` - F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=FSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` - F_Sfixed32Defaulted *int32 `protobuf:"fixed32,404,opt,name=F_Sfixed32_defaulted,json=FSfixed32Defaulted,def=-32" json:"F_Sfixed32_defaulted,omitempty"` - F_Sfixed64Defaulted *int64 `protobuf:"fixed64,405,opt,name=F_Sfixed64_defaulted,json=FSfixed64Defaulted,def=-64" json:"F_Sfixed64_defaulted,omitempty"` - // Packed repeated fields (no string or bytes). - F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=FBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"` - F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=FInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"` - F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=FInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"` - F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=FFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"` - F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=FFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"` - F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=FUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"` - F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=FUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"` - F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=FFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"` - F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=FDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"` - F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=FSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"` - F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=FSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"` - F_Sfixed32RepeatedPacked []int32 `protobuf:"fixed32,504,rep,packed,name=F_Sfixed32_repeated_packed,json=FSfixed32RepeatedPacked" json:"F_Sfixed32_repeated_packed,omitempty"` - F_Sfixed64RepeatedPacked []int64 `protobuf:"fixed64,505,rep,packed,name=F_Sfixed64_repeated_packed,json=FSfixed64RepeatedPacked" json:"F_Sfixed64_repeated_packed,omitempty"` - Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"` - Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"` - Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTest) Reset() { *m = GoTest{} } -func (m *GoTest) String() string { return proto.CompactTextString(m) } -func (*GoTest) ProtoMessage() {} -func (*GoTest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{2} -} -func (m *GoTest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTest.Unmarshal(m, b) -} -func (m *GoTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTest.Marshal(b, m, deterministic) -} -func (dst *GoTest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTest.Merge(dst, src) -} -func (m *GoTest) XXX_Size() int { - return xxx_messageInfo_GoTest.Size(m) -} -func (m *GoTest) XXX_DiscardUnknown() { - xxx_messageInfo_GoTest.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTest proto.InternalMessageInfo - -const Default_GoTest_F_BoolDefaulted bool = true -const Default_GoTest_F_Int32Defaulted int32 = 32 -const Default_GoTest_F_Int64Defaulted int64 = 64 -const Default_GoTest_F_Fixed32Defaulted uint32 = 320 -const Default_GoTest_F_Fixed64Defaulted uint64 = 640 -const Default_GoTest_F_Uint32Defaulted uint32 = 3200 -const Default_GoTest_F_Uint64Defaulted uint64 = 6400 -const Default_GoTest_F_FloatDefaulted float32 = 314159 -const Default_GoTest_F_DoubleDefaulted float64 = 271828 -const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" - -var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") - -const Default_GoTest_F_Sint32Defaulted int32 = -32 -const Default_GoTest_F_Sint64Defaulted int64 = -64 -const Default_GoTest_F_Sfixed32Defaulted int32 = -32 -const Default_GoTest_F_Sfixed64Defaulted int64 = -64 - -func (m *GoTest) GetKind() GoTest_KIND { - if m != nil && m.Kind != nil { - return *m.Kind - } - return GoTest_VOID -} - -func (m *GoTest) GetTable() string { - if m != nil && m.Table != nil { - return *m.Table - } - return "" -} - -func (m *GoTest) GetParam() int32 { - if m != nil && m.Param != nil { - return *m.Param - } - return 0 -} - -func (m *GoTest) GetRequiredField() *GoTestField { - if m != nil { - return m.RequiredField - } - return nil -} - -func (m *GoTest) GetRepeatedField() []*GoTestField { - if m != nil { - return m.RepeatedField - } - return nil -} - -func (m *GoTest) GetOptionalField() *GoTestField { - if m != nil { - return m.OptionalField - } - return nil -} - -func (m *GoTest) GetF_BoolRequired() bool { - if m != nil && m.F_BoolRequired != nil { - return *m.F_BoolRequired - } - return false -} - -func (m *GoTest) GetF_Int32Required() int32 { - if m != nil && m.F_Int32Required != nil { - return *m.F_Int32Required - } - return 0 -} - -func (m *GoTest) GetF_Int64Required() int64 { - if m != nil && m.F_Int64Required != nil { - return *m.F_Int64Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Required() uint32 { - if m != nil && m.F_Fixed32Required != nil { - return *m.F_Fixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Required() uint64 { - if m != nil && m.F_Fixed64Required != nil { - return *m.F_Fixed64Required - } - return 0 -} - -func (m *GoTest) GetF_Uint32Required() uint32 { - if m != nil && m.F_Uint32Required != nil { - return *m.F_Uint32Required - } - return 0 -} - -func (m *GoTest) GetF_Uint64Required() uint64 { - if m != nil && m.F_Uint64Required != nil { - return *m.F_Uint64Required - } - return 0 -} - -func (m *GoTest) GetF_FloatRequired() float32 { - if m != nil && m.F_FloatRequired != nil { - return *m.F_FloatRequired - } - return 0 -} - -func (m *GoTest) GetF_DoubleRequired() float64 { - if m != nil && m.F_DoubleRequired != nil { - return *m.F_DoubleRequired - } - return 0 -} - -func (m *GoTest) GetF_StringRequired() string { - if m != nil && m.F_StringRequired != nil { - return *m.F_StringRequired - } - return "" -} - -func (m *GoTest) GetF_BytesRequired() []byte { - if m != nil { - return m.F_BytesRequired - } - return nil -} - -func (m *GoTest) GetF_Sint32Required() int32 { - if m != nil && m.F_Sint32Required != nil { - return *m.F_Sint32Required - } - return 0 -} - -func (m *GoTest) GetF_Sint64Required() int64 { - if m != nil && m.F_Sint64Required != nil { - return *m.F_Sint64Required - } - return 0 -} - -func (m *GoTest) GetF_Sfixed32Required() int32 { - if m != nil && m.F_Sfixed32Required != nil { - return *m.F_Sfixed32Required - } - return 0 -} - -func (m *GoTest) GetF_Sfixed64Required() int64 { - if m != nil && m.F_Sfixed64Required != nil { - return *m.F_Sfixed64Required - } - return 0 -} - -func (m *GoTest) GetF_BoolRepeated() []bool { - if m != nil { - return m.F_BoolRepeated - } - return nil -} - -func (m *GoTest) GetF_Int32Repeated() []int32 { - if m != nil { - return m.F_Int32Repeated - } - return nil -} - -func (m *GoTest) GetF_Int64Repeated() []int64 { - if m != nil { - return m.F_Int64Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed32Repeated() []uint32 { - if m != nil { - return m.F_Fixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Fixed64Repeated() []uint64 { - if m != nil { - return m.F_Fixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint32Repeated() []uint32 { - if m != nil { - return m.F_Uint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Uint64Repeated() []uint64 { - if m != nil { - return m.F_Uint64Repeated - } - return nil -} - -func (m *GoTest) GetF_FloatRepeated() []float32 { - if m != nil { - return m.F_FloatRepeated - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeated() []float64 { - if m != nil { - return m.F_DoubleRepeated - } - return nil -} - -func (m *GoTest) GetF_StringRepeated() []string { - if m != nil { - return m.F_StringRepeated - } - return nil -} - -func (m *GoTest) GetF_BytesRepeated() [][]byte { - if m != nil { - return m.F_BytesRepeated - } - return nil -} - -func (m *GoTest) GetF_Sint32Repeated() []int32 { - if m != nil { - return m.F_Sint32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sint64Repeated() []int64 { - if m != nil { - return m.F_Sint64Repeated - } - return nil -} - -func (m *GoTest) GetF_Sfixed32Repeated() []int32 { - if m != nil { - return m.F_Sfixed32Repeated - } - return nil -} - -func (m *GoTest) GetF_Sfixed64Repeated() []int64 { - if m != nil { - return m.F_Sfixed64Repeated - } - return nil -} - -func (m *GoTest) GetF_BoolOptional() bool { - if m != nil && m.F_BoolOptional != nil { - return *m.F_BoolOptional - } - return false -} - -func (m *GoTest) GetF_Int32Optional() int32 { - if m != nil && m.F_Int32Optional != nil { - return *m.F_Int32Optional - } - return 0 -} - -func (m *GoTest) GetF_Int64Optional() int64 { - if m != nil && m.F_Int64Optional != nil { - return *m.F_Int64Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed32Optional() uint32 { - if m != nil && m.F_Fixed32Optional != nil { - return *m.F_Fixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Fixed64Optional() uint64 { - if m != nil && m.F_Fixed64Optional != nil { - return *m.F_Fixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint32Optional() uint32 { - if m != nil && m.F_Uint32Optional != nil { - return *m.F_Uint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Uint64Optional() uint64 { - if m != nil && m.F_Uint64Optional != nil { - return *m.F_Uint64Optional - } - return 0 -} - -func (m *GoTest) GetF_FloatOptional() float32 { - if m != nil && m.F_FloatOptional != nil { - return *m.F_FloatOptional - } - return 0 -} - -func (m *GoTest) GetF_DoubleOptional() float64 { - if m != nil && m.F_DoubleOptional != nil { - return *m.F_DoubleOptional - } - return 0 -} - -func (m *GoTest) GetF_StringOptional() string { - if m != nil && m.F_StringOptional != nil { - return *m.F_StringOptional - } - return "" -} - -func (m *GoTest) GetF_BytesOptional() []byte { - if m != nil { - return m.F_BytesOptional - } - return nil -} - -func (m *GoTest) GetF_Sint32Optional() int32 { - if m != nil && m.F_Sint32Optional != nil { - return *m.F_Sint32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sint64Optional() int64 { - if m != nil && m.F_Sint64Optional != nil { - return *m.F_Sint64Optional - } - return 0 -} - -func (m *GoTest) GetF_Sfixed32Optional() int32 { - if m != nil && m.F_Sfixed32Optional != nil { - return *m.F_Sfixed32Optional - } - return 0 -} - -func (m *GoTest) GetF_Sfixed64Optional() int64 { - if m != nil && m.F_Sfixed64Optional != nil { - return *m.F_Sfixed64Optional - } - return 0 -} - -func (m *GoTest) GetF_BoolDefaulted() bool { - if m != nil && m.F_BoolDefaulted != nil { - return *m.F_BoolDefaulted - } - return Default_GoTest_F_BoolDefaulted -} - -func (m *GoTest) GetF_Int32Defaulted() int32 { - if m != nil && m.F_Int32Defaulted != nil { - return *m.F_Int32Defaulted - } - return Default_GoTest_F_Int32Defaulted -} - -func (m *GoTest) GetF_Int64Defaulted() int64 { - if m != nil && m.F_Int64Defaulted != nil { - return *m.F_Int64Defaulted - } - return Default_GoTest_F_Int64Defaulted -} - -func (m *GoTest) GetF_Fixed32Defaulted() uint32 { - if m != nil && m.F_Fixed32Defaulted != nil { - return *m.F_Fixed32Defaulted - } - return Default_GoTest_F_Fixed32Defaulted -} - -func (m *GoTest) GetF_Fixed64Defaulted() uint64 { - if m != nil && m.F_Fixed64Defaulted != nil { - return *m.F_Fixed64Defaulted - } - return Default_GoTest_F_Fixed64Defaulted -} - -func (m *GoTest) GetF_Uint32Defaulted() uint32 { - if m != nil && m.F_Uint32Defaulted != nil { - return *m.F_Uint32Defaulted - } - return Default_GoTest_F_Uint32Defaulted -} - -func (m *GoTest) GetF_Uint64Defaulted() uint64 { - if m != nil && m.F_Uint64Defaulted != nil { - return *m.F_Uint64Defaulted - } - return Default_GoTest_F_Uint64Defaulted -} - -func (m *GoTest) GetF_FloatDefaulted() float32 { - if m != nil && m.F_FloatDefaulted != nil { - return *m.F_FloatDefaulted - } - return Default_GoTest_F_FloatDefaulted -} - -func (m *GoTest) GetF_DoubleDefaulted() float64 { - if m != nil && m.F_DoubleDefaulted != nil { - return *m.F_DoubleDefaulted - } - return Default_GoTest_F_DoubleDefaulted -} - -func (m *GoTest) GetF_StringDefaulted() string { - if m != nil && m.F_StringDefaulted != nil { - return *m.F_StringDefaulted - } - return Default_GoTest_F_StringDefaulted -} - -func (m *GoTest) GetF_BytesDefaulted() []byte { - if m != nil && m.F_BytesDefaulted != nil { - return m.F_BytesDefaulted - } - return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) -} - -func (m *GoTest) GetF_Sint32Defaulted() int32 { - if m != nil && m.F_Sint32Defaulted != nil { - return *m.F_Sint32Defaulted - } - return Default_GoTest_F_Sint32Defaulted -} - -func (m *GoTest) GetF_Sint64Defaulted() int64 { - if m != nil && m.F_Sint64Defaulted != nil { - return *m.F_Sint64Defaulted - } - return Default_GoTest_F_Sint64Defaulted -} - -func (m *GoTest) GetF_Sfixed32Defaulted() int32 { - if m != nil && m.F_Sfixed32Defaulted != nil { - return *m.F_Sfixed32Defaulted - } - return Default_GoTest_F_Sfixed32Defaulted -} - -func (m *GoTest) GetF_Sfixed64Defaulted() int64 { - if m != nil && m.F_Sfixed64Defaulted != nil { - return *m.F_Sfixed64Defaulted - } - return Default_GoTest_F_Sfixed64Defaulted -} - -func (m *GoTest) GetF_BoolRepeatedPacked() []bool { - if m != nil { - return m.F_BoolRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { - if m != nil { - return m.F_Int32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { - if m != nil { - return m.F_Int64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Fixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Fixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { - if m != nil { - return m.F_Uint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { - if m != nil { - return m.F_Uint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { - if m != nil { - return m.F_FloatRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { - if m != nil { - return m.F_DoubleRepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sint32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sint64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sfixed32RepeatedPacked() []int32 { - if m != nil { - return m.F_Sfixed32RepeatedPacked - } - return nil -} - -func (m *GoTest) GetF_Sfixed64RepeatedPacked() []int64 { - if m != nil { - return m.F_Sfixed64RepeatedPacked - } - return nil -} - -func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { - if m != nil { - return m.Requiredgroup - } - return nil -} - -func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { - if m != nil { - return m.Repeatedgroup - } - return nil -} - -func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil -} - -// Required, repeated, and optional groups. -type GoTest_RequiredGroup struct { - RequiredField *string `protobuf:"bytes,71,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } -func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RequiredGroup) ProtoMessage() {} -func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{2, 0} -} -func (m *GoTest_RequiredGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTest_RequiredGroup.Unmarshal(m, b) -} -func (m *GoTest_RequiredGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTest_RequiredGroup.Marshal(b, m, deterministic) -} -func (dst *GoTest_RequiredGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTest_RequiredGroup.Merge(dst, src) -} -func (m *GoTest_RequiredGroup) XXX_Size() int { - return xxx_messageInfo_GoTest_RequiredGroup.Size(m) -} -func (m *GoTest_RequiredGroup) XXX_DiscardUnknown() { - xxx_messageInfo_GoTest_RequiredGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTest_RequiredGroup proto.InternalMessageInfo - -func (m *GoTest_RequiredGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_RepeatedGroup struct { - RequiredField *string `protobuf:"bytes,81,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } -func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_RepeatedGroup) ProtoMessage() {} -func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{2, 1} -} -func (m *GoTest_RepeatedGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTest_RepeatedGroup.Unmarshal(m, b) -} -func (m *GoTest_RepeatedGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTest_RepeatedGroup.Marshal(b, m, deterministic) -} -func (dst *GoTest_RepeatedGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTest_RepeatedGroup.Merge(dst, src) -} -func (m *GoTest_RepeatedGroup) XXX_Size() int { - return xxx_messageInfo_GoTest_RepeatedGroup.Size(m) -} -func (m *GoTest_RepeatedGroup) XXX_DiscardUnknown() { - xxx_messageInfo_GoTest_RepeatedGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTest_RepeatedGroup proto.InternalMessageInfo - -func (m *GoTest_RepeatedGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -type GoTest_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,91,req,name=RequiredField" json:"RequiredField,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } -func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } -func (*GoTest_OptionalGroup) ProtoMessage() {} -func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{2, 2} -} -func (m *GoTest_OptionalGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTest_OptionalGroup.Unmarshal(m, b) -} -func (m *GoTest_OptionalGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTest_OptionalGroup.Marshal(b, m, deterministic) -} -func (dst *GoTest_OptionalGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTest_OptionalGroup.Merge(dst, src) -} -func (m *GoTest_OptionalGroup) XXX_Size() int { - return xxx_messageInfo_GoTest_OptionalGroup.Size(m) -} -func (m *GoTest_OptionalGroup) XXX_DiscardUnknown() { - xxx_messageInfo_GoTest_OptionalGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTest_OptionalGroup proto.InternalMessageInfo - -func (m *GoTest_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" -} - -// For testing a group containing a required field. -type GoTestRequiredGroupField struct { - Group *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTestRequiredGroupField) Reset() { *m = GoTestRequiredGroupField{} } -func (m *GoTestRequiredGroupField) String() string { return proto.CompactTextString(m) } -func (*GoTestRequiredGroupField) ProtoMessage() {} -func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{3} -} -func (m *GoTestRequiredGroupField) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTestRequiredGroupField.Unmarshal(m, b) -} -func (m *GoTestRequiredGroupField) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTestRequiredGroupField.Marshal(b, m, deterministic) -} -func (dst *GoTestRequiredGroupField) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTestRequiredGroupField.Merge(dst, src) -} -func (m *GoTestRequiredGroupField) XXX_Size() int { - return xxx_messageInfo_GoTestRequiredGroupField.Size(m) -} -func (m *GoTestRequiredGroupField) XXX_DiscardUnknown() { - xxx_messageInfo_GoTestRequiredGroupField.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTestRequiredGroupField proto.InternalMessageInfo - -func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group { - if m != nil { - return m.Group - } - return nil -} - -type GoTestRequiredGroupField_Group struct { - Field *int32 `protobuf:"varint,2,req,name=Field" json:"Field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoTestRequiredGroupField_Group) Reset() { *m = GoTestRequiredGroupField_Group{} } -func (m *GoTestRequiredGroupField_Group) String() string { return proto.CompactTextString(m) } -func (*GoTestRequiredGroupField_Group) ProtoMessage() {} -func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{3, 0} -} -func (m *GoTestRequiredGroupField_Group) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoTestRequiredGroupField_Group.Unmarshal(m, b) -} -func (m *GoTestRequiredGroupField_Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoTestRequiredGroupField_Group.Marshal(b, m, deterministic) -} -func (dst *GoTestRequiredGroupField_Group) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoTestRequiredGroupField_Group.Merge(dst, src) -} -func (m *GoTestRequiredGroupField_Group) XXX_Size() int { - return xxx_messageInfo_GoTestRequiredGroupField_Group.Size(m) -} -func (m *GoTestRequiredGroupField_Group) XXX_DiscardUnknown() { - xxx_messageInfo_GoTestRequiredGroupField_Group.DiscardUnknown(m) -} - -var xxx_messageInfo_GoTestRequiredGroupField_Group proto.InternalMessageInfo - -func (m *GoTestRequiredGroupField_Group) GetField() int32 { - if m != nil && m.Field != nil { - return *m.Field - } - return 0 -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -type GoSkipTest struct { - SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"` - SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"` - SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"` - SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"` - Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } -func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest) ProtoMessage() {} -func (*GoSkipTest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{4} -} -func (m *GoSkipTest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoSkipTest.Unmarshal(m, b) -} -func (m *GoSkipTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoSkipTest.Marshal(b, m, deterministic) -} -func (dst *GoSkipTest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoSkipTest.Merge(dst, src) -} -func (m *GoSkipTest) XXX_Size() int { - return xxx_messageInfo_GoSkipTest.Size(m) -} -func (m *GoSkipTest) XXX_DiscardUnknown() { - xxx_messageInfo_GoSkipTest.DiscardUnknown(m) -} - -var xxx_messageInfo_GoSkipTest proto.InternalMessageInfo - -func (m *GoSkipTest) GetSkipInt32() int32 { - if m != nil && m.SkipInt32 != nil { - return *m.SkipInt32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed32() uint32 { - if m != nil && m.SkipFixed32 != nil { - return *m.SkipFixed32 - } - return 0 -} - -func (m *GoSkipTest) GetSkipFixed64() uint64 { - if m != nil && m.SkipFixed64 != nil { - return *m.SkipFixed64 - } - return 0 -} - -func (m *GoSkipTest) GetSkipString() string { - if m != nil && m.SkipString != nil { - return *m.SkipString - } - return "" -} - -func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { - if m != nil { - return m.Skipgroup - } - return nil -} - -type GoSkipTest_SkipGroup struct { - GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"` - GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } -func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } -func (*GoSkipTest_SkipGroup) ProtoMessage() {} -func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{4, 0} -} -func (m *GoSkipTest_SkipGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GoSkipTest_SkipGroup.Unmarshal(m, b) -} -func (m *GoSkipTest_SkipGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GoSkipTest_SkipGroup.Marshal(b, m, deterministic) -} -func (dst *GoSkipTest_SkipGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_GoSkipTest_SkipGroup.Merge(dst, src) -} -func (m *GoSkipTest_SkipGroup) XXX_Size() int { - return xxx_messageInfo_GoSkipTest_SkipGroup.Size(m) -} -func (m *GoSkipTest_SkipGroup) XXX_DiscardUnknown() { - xxx_messageInfo_GoSkipTest_SkipGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_GoSkipTest_SkipGroup proto.InternalMessageInfo - -func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { - if m != nil && m.GroupInt32 != nil { - return *m.GroupInt32 - } - return 0 -} - -func (m *GoSkipTest_SkipGroup) GetGroupString() string { - if m != nil && m.GroupString != nil { - return *m.GroupString - } - return "" -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -type NonPackedTest struct { - A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } -func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } -func (*NonPackedTest) ProtoMessage() {} -func (*NonPackedTest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{5} -} -func (m *NonPackedTest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NonPackedTest.Unmarshal(m, b) -} -func (m *NonPackedTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NonPackedTest.Marshal(b, m, deterministic) -} -func (dst *NonPackedTest) XXX_Merge(src proto.Message) { - xxx_messageInfo_NonPackedTest.Merge(dst, src) -} -func (m *NonPackedTest) XXX_Size() int { - return xxx_messageInfo_NonPackedTest.Size(m) -} -func (m *NonPackedTest) XXX_DiscardUnknown() { - xxx_messageInfo_NonPackedTest.DiscardUnknown(m) -} - -var xxx_messageInfo_NonPackedTest proto.InternalMessageInfo - -func (m *NonPackedTest) GetA() []int32 { - if m != nil { - return m.A - } - return nil -} - -type PackedTest struct { - B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PackedTest) Reset() { *m = PackedTest{} } -func (m *PackedTest) String() string { return proto.CompactTextString(m) } -func (*PackedTest) ProtoMessage() {} -func (*PackedTest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{6} -} -func (m *PackedTest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PackedTest.Unmarshal(m, b) -} -func (m *PackedTest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PackedTest.Marshal(b, m, deterministic) -} -func (dst *PackedTest) XXX_Merge(src proto.Message) { - xxx_messageInfo_PackedTest.Merge(dst, src) -} -func (m *PackedTest) XXX_Size() int { - return xxx_messageInfo_PackedTest.Size(m) -} -func (m *PackedTest) XXX_DiscardUnknown() { - xxx_messageInfo_PackedTest.DiscardUnknown(m) -} - -var xxx_messageInfo_PackedTest proto.InternalMessageInfo - -func (m *PackedTest) GetB() []int32 { - if m != nil { - return m.B - } - return nil -} - -type MaxTag struct { - // Maximum possible tag number. - LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MaxTag) Reset() { *m = MaxTag{} } -func (m *MaxTag) String() string { return proto.CompactTextString(m) } -func (*MaxTag) ProtoMessage() {} -func (*MaxTag) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{7} -} -func (m *MaxTag) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MaxTag.Unmarshal(m, b) -} -func (m *MaxTag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MaxTag.Marshal(b, m, deterministic) -} -func (dst *MaxTag) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaxTag.Merge(dst, src) -} -func (m *MaxTag) XXX_Size() int { - return xxx_messageInfo_MaxTag.Size(m) -} -func (m *MaxTag) XXX_DiscardUnknown() { - xxx_messageInfo_MaxTag.DiscardUnknown(m) -} - -var xxx_messageInfo_MaxTag proto.InternalMessageInfo - -func (m *MaxTag) GetLastField() string { - if m != nil && m.LastField != nil { - return *m.LastField - } - return "" -} - -type OldMessage struct { - Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OldMessage) Reset() { *m = OldMessage{} } -func (m *OldMessage) String() string { return proto.CompactTextString(m) } -func (*OldMessage) ProtoMessage() {} -func (*OldMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{8} -} -func (m *OldMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OldMessage.Unmarshal(m, b) -} -func (m *OldMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OldMessage.Marshal(b, m, deterministic) -} -func (dst *OldMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_OldMessage.Merge(dst, src) -} -func (m *OldMessage) XXX_Size() int { - return xxx_messageInfo_OldMessage.Size(m) -} -func (m *OldMessage) XXX_DiscardUnknown() { - xxx_messageInfo_OldMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_OldMessage proto.InternalMessageInfo - -func (m *OldMessage) GetNested() *OldMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *OldMessage) GetNum() int32 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type OldMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } -func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*OldMessage_Nested) ProtoMessage() {} -func (*OldMessage_Nested) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{8, 0} -} -func (m *OldMessage_Nested) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OldMessage_Nested.Unmarshal(m, b) -} -func (m *OldMessage_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OldMessage_Nested.Marshal(b, m, deterministic) -} -func (dst *OldMessage_Nested) XXX_Merge(src proto.Message) { - xxx_messageInfo_OldMessage_Nested.Merge(dst, src) -} -func (m *OldMessage_Nested) XXX_Size() int { - return xxx_messageInfo_OldMessage_Nested.Size(m) -} -func (m *OldMessage_Nested) XXX_DiscardUnknown() { - xxx_messageInfo_OldMessage_Nested.DiscardUnknown(m) -} - -var xxx_messageInfo_OldMessage_Nested proto.InternalMessageInfo - -func (m *OldMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -type NewMessage struct { - Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` - // This is an int32 in OldMessage. - Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NewMessage) Reset() { *m = NewMessage{} } -func (m *NewMessage) String() string { return proto.CompactTextString(m) } -func (*NewMessage) ProtoMessage() {} -func (*NewMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{9} -} -func (m *NewMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NewMessage.Unmarshal(m, b) -} -func (m *NewMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NewMessage.Marshal(b, m, deterministic) -} -func (dst *NewMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_NewMessage.Merge(dst, src) -} -func (m *NewMessage) XXX_Size() int { - return xxx_messageInfo_NewMessage.Size(m) -} -func (m *NewMessage) XXX_DiscardUnknown() { - xxx_messageInfo_NewMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_NewMessage proto.InternalMessageInfo - -func (m *NewMessage) GetNested() *NewMessage_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *NewMessage) GetNum() int64 { - if m != nil && m.Num != nil { - return *m.Num - } - return 0 -} - -type NewMessage_Nested struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } -func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } -func (*NewMessage_Nested) ProtoMessage() {} -func (*NewMessage_Nested) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{9, 0} -} -func (m *NewMessage_Nested) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NewMessage_Nested.Unmarshal(m, b) -} -func (m *NewMessage_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NewMessage_Nested.Marshal(b, m, deterministic) -} -func (dst *NewMessage_Nested) XXX_Merge(src proto.Message) { - xxx_messageInfo_NewMessage_Nested.Merge(dst, src) -} -func (m *NewMessage_Nested) XXX_Size() int { - return xxx_messageInfo_NewMessage_Nested.Size(m) -} -func (m *NewMessage_Nested) XXX_DiscardUnknown() { - xxx_messageInfo_NewMessage_Nested.DiscardUnknown(m) -} - -var xxx_messageInfo_NewMessage_Nested proto.InternalMessageInfo - -func (m *NewMessage_Nested) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *NewMessage_Nested) GetFoodGroup() string { - if m != nil && m.FoodGroup != nil { - return *m.FoodGroup - } - return "" -} - -type InnerMessage struct { - Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` - Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` - Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} -func (*InnerMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{10} -} -func (m *InnerMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InnerMessage.Unmarshal(m, b) -} -func (m *InnerMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InnerMessage.Marshal(b, m, deterministic) -} -func (dst *InnerMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_InnerMessage.Merge(dst, src) -} -func (m *InnerMessage) XXX_Size() int { - return xxx_messageInfo_InnerMessage.Size(m) -} -func (m *InnerMessage) XXX_DiscardUnknown() { - xxx_messageInfo_InnerMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_InnerMessage proto.InternalMessageInfo - -const Default_InnerMessage_Port int32 = 4000 - -func (m *InnerMessage) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *InnerMessage) GetPort() int32 { - if m != nil && m.Port != nil { - return *m.Port - } - return Default_InnerMessage_Port -} - -func (m *InnerMessage) GetConnected() bool { - if m != nil && m.Connected != nil { - return *m.Connected - } - return false -} - -type OtherMessage struct { - Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` - Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OtherMessage) Reset() { *m = OtherMessage{} } -func (m *OtherMessage) String() string { return proto.CompactTextString(m) } -func (*OtherMessage) ProtoMessage() {} -func (*OtherMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{11} -} - -var extRange_OtherMessage = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OtherMessage -} -func (m *OtherMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OtherMessage.Unmarshal(m, b) -} -func (m *OtherMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OtherMessage.Marshal(b, m, deterministic) -} -func (dst *OtherMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_OtherMessage.Merge(dst, src) -} -func (m *OtherMessage) XXX_Size() int { - return xxx_messageInfo_OtherMessage.Size(m) -} -func (m *OtherMessage) XXX_DiscardUnknown() { - xxx_messageInfo_OtherMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_OtherMessage proto.InternalMessageInfo - -func (m *OtherMessage) GetKey() int64 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -func (m *OtherMessage) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func (m *OtherMessage) GetWeight() float32 { - if m != nil && m.Weight != nil { - return *m.Weight - } - return 0 -} - -func (m *OtherMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -type RequiredInnerMessage struct { - LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} } -func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) } -func (*RequiredInnerMessage) ProtoMessage() {} -func (*RequiredInnerMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{12} -} -func (m *RequiredInnerMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RequiredInnerMessage.Unmarshal(m, b) -} -func (m *RequiredInnerMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RequiredInnerMessage.Marshal(b, m, deterministic) -} -func (dst *RequiredInnerMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_RequiredInnerMessage.Merge(dst, src) -} -func (m *RequiredInnerMessage) XXX_Size() int { - return xxx_messageInfo_RequiredInnerMessage.Size(m) -} -func (m *RequiredInnerMessage) XXX_DiscardUnknown() { - xxx_messageInfo_RequiredInnerMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_RequiredInnerMessage proto.InternalMessageInfo - -func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage { - if m != nil { - return m.LeoFinallyWonAnOscar - } - return nil -} - -type MyMessage struct { - Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` - Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` - Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` - Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` - Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` - Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` - WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"` - RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"` - Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=test_proto.MyMessage_Color" json:"bikeshed,omitempty"` - Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` - // This field becomes [][]byte in the generated code. - RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"` - Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MyMessage) Reset() { *m = MyMessage{} } -func (m *MyMessage) String() string { return proto.CompactTextString(m) } -func (*MyMessage) ProtoMessage() {} -func (*MyMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{13} -} - -var extRange_MyMessage = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessage -} -func (m *MyMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MyMessage.Unmarshal(m, b) -} -func (m *MyMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MyMessage.Marshal(b, m, deterministic) -} -func (dst *MyMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_MyMessage.Merge(dst, src) -} -func (m *MyMessage) XXX_Size() int { - return xxx_messageInfo_MyMessage.Size(m) -} -func (m *MyMessage) XXX_DiscardUnknown() { - xxx_messageInfo_MyMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_MyMessage proto.InternalMessageInfo - -func (m *MyMessage) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *MyMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MyMessage) GetQuote() string { - if m != nil && m.Quote != nil { - return *m.Quote - } - return "" -} - -func (m *MyMessage) GetPet() []string { - if m != nil { - return m.Pet - } - return nil -} - -func (m *MyMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func (m *MyMessage) GetOthers() []*OtherMessage { - if m != nil { - return m.Others - } - return nil -} - -func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage { - if m != nil { - return m.WeMustGoDeeper - } - return nil -} - -func (m *MyMessage) GetRepInner() []*InnerMessage { - if m != nil { - return m.RepInner - } - return nil -} - -func (m *MyMessage) GetBikeshed() MyMessage_Color { - if m != nil && m.Bikeshed != nil { - return *m.Bikeshed - } - return MyMessage_RED -} - -func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *MyMessage) GetRepBytes() [][]byte { - if m != nil { - return m.RepBytes - } - return nil -} - -func (m *MyMessage) GetBigfloat() float64 { - if m != nil && m.Bigfloat != nil { - return *m.Bigfloat - } - return 0 -} - -type MyMessage_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } -func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*MyMessage_SomeGroup) ProtoMessage() {} -func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{13, 0} -} -func (m *MyMessage_SomeGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MyMessage_SomeGroup.Unmarshal(m, b) -} -func (m *MyMessage_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MyMessage_SomeGroup.Marshal(b, m, deterministic) -} -func (dst *MyMessage_SomeGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_MyMessage_SomeGroup.Merge(dst, src) -} -func (m *MyMessage_SomeGroup) XXX_Size() int { - return xxx_messageInfo_MyMessage_SomeGroup.Size(m) -} -func (m *MyMessage_SomeGroup) XXX_DiscardUnknown() { - xxx_messageInfo_MyMessage_SomeGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_MyMessage_SomeGroup proto.InternalMessageInfo - -func (m *MyMessage_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Ext struct { - Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` - MapField map[int32]int32 `protobuf:"bytes,2,rep,name=map_field,json=mapField" json:"map_field,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Ext) Reset() { *m = Ext{} } -func (m *Ext) String() string { return proto.CompactTextString(m) } -func (*Ext) ProtoMessage() {} -func (*Ext) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{14} -} -func (m *Ext) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Ext.Unmarshal(m, b) -} -func (m *Ext) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Ext.Marshal(b, m, deterministic) -} -func (dst *Ext) XXX_Merge(src proto.Message) { - xxx_messageInfo_Ext.Merge(dst, src) -} -func (m *Ext) XXX_Size() int { - return xxx_messageInfo_Ext.Size(m) -} -func (m *Ext) XXX_DiscardUnknown() { - xxx_messageInfo_Ext.DiscardUnknown(m) -} - -var xxx_messageInfo_Ext proto.InternalMessageInfo - -func (m *Ext) GetData() string { - if m != nil && m.Data != nil { - return *m.Data - } - return "" -} - -func (m *Ext) GetMapField() map[int32]int32 { - if m != nil { - return m.MapField - } - return nil -} - -var E_Ext_More = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*Ext)(nil), - Field: 103, - Name: "test_proto.Ext.more", - Tag: "bytes,103,opt,name=more", - Filename: "test_proto/test.proto", -} - -var E_Ext_Text = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*string)(nil), - Field: 104, - Name: "test_proto.Ext.text", - Tag: "bytes,104,opt,name=text", - Filename: "test_proto/test.proto", -} - -var E_Ext_Number = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 105, - Name: "test_proto.Ext.number", - Tag: "varint,105,opt,name=number", - Filename: "test_proto/test.proto", -} - -type ComplexExtension struct { - First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"` - Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"` - Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ComplexExtension) Reset() { *m = ComplexExtension{} } -func (m *ComplexExtension) String() string { return proto.CompactTextString(m) } -func (*ComplexExtension) ProtoMessage() {} -func (*ComplexExtension) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{15} -} -func (m *ComplexExtension) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ComplexExtension.Unmarshal(m, b) -} -func (m *ComplexExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ComplexExtension.Marshal(b, m, deterministic) -} -func (dst *ComplexExtension) XXX_Merge(src proto.Message) { - xxx_messageInfo_ComplexExtension.Merge(dst, src) -} -func (m *ComplexExtension) XXX_Size() int { - return xxx_messageInfo_ComplexExtension.Size(m) -} -func (m *ComplexExtension) XXX_DiscardUnknown() { - xxx_messageInfo_ComplexExtension.DiscardUnknown(m) -} - -var xxx_messageInfo_ComplexExtension proto.InternalMessageInfo - -func (m *ComplexExtension) GetFirst() int32 { - if m != nil && m.First != nil { - return *m.First - } - return 0 -} - -func (m *ComplexExtension) GetSecond() int32 { - if m != nil && m.Second != nil { - return *m.Second - } - return 0 -} - -func (m *ComplexExtension) GetThird() []int32 { - if m != nil { - return m.Third - } - return nil -} - -type DefaultsMessage struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } -func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } -func (*DefaultsMessage) ProtoMessage() {} -func (*DefaultsMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{16} -} - -var extRange_DefaultsMessage = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_DefaultsMessage -} -func (m *DefaultsMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DefaultsMessage.Unmarshal(m, b) -} -func (m *DefaultsMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DefaultsMessage.Marshal(b, m, deterministic) -} -func (dst *DefaultsMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_DefaultsMessage.Merge(dst, src) -} -func (m *DefaultsMessage) XXX_Size() int { - return xxx_messageInfo_DefaultsMessage.Size(m) -} -func (m *DefaultsMessage) XXX_DiscardUnknown() { - xxx_messageInfo_DefaultsMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_DefaultsMessage proto.InternalMessageInfo - -type MyMessageSet struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } -func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } -func (*MyMessageSet) ProtoMessage() {} -func (*MyMessageSet) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{17} -} - -func (m *MyMessageSet) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) -} -func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) -} - -var extRange_MyMessageSet = []proto.ExtensionRange{ - {Start: 100, End: 2147483646}, -} - -func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MyMessageSet -} -func (m *MyMessageSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MyMessageSet.Unmarshal(m, b) -} -func (m *MyMessageSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MyMessageSet.Marshal(b, m, deterministic) -} -func (dst *MyMessageSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_MyMessageSet.Merge(dst, src) -} -func (m *MyMessageSet) XXX_Size() int { - return xxx_messageInfo_MyMessageSet.Size(m) -} -func (m *MyMessageSet) XXX_DiscardUnknown() { - xxx_messageInfo_MyMessageSet.DiscardUnknown(m) -} - -var xxx_messageInfo_MyMessageSet proto.InternalMessageInfo - -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{18} -} -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -type MessageList struct { - Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageList) Reset() { *m = MessageList{} } -func (m *MessageList) String() string { return proto.CompactTextString(m) } -func (*MessageList) ProtoMessage() {} -func (*MessageList) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{19} -} -func (m *MessageList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageList.Unmarshal(m, b) -} -func (m *MessageList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageList.Marshal(b, m, deterministic) -} -func (dst *MessageList) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageList.Merge(dst, src) -} -func (m *MessageList) XXX_Size() int { - return xxx_messageInfo_MessageList.Size(m) -} -func (m *MessageList) XXX_DiscardUnknown() { - xxx_messageInfo_MessageList.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageList proto.InternalMessageInfo - -func (m *MessageList) GetMessage() []*MessageList_Message { - if m != nil { - return m.Message - } - return nil -} - -type MessageList_Message struct { - Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` - Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } -func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } -func (*MessageList_Message) ProtoMessage() {} -func (*MessageList_Message) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{19, 0} -} -func (m *MessageList_Message) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageList_Message.Unmarshal(m, b) -} -func (m *MessageList_Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageList_Message.Marshal(b, m, deterministic) -} -func (dst *MessageList_Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageList_Message.Merge(dst, src) -} -func (m *MessageList_Message) XXX_Size() int { - return xxx_messageInfo_MessageList_Message.Size(m) -} -func (m *MessageList_Message) XXX_DiscardUnknown() { - xxx_messageInfo_MessageList_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageList_Message proto.InternalMessageInfo - -func (m *MessageList_Message) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MessageList_Message) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -type Strings struct { - StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"` - BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Strings) Reset() { *m = Strings{} } -func (m *Strings) String() string { return proto.CompactTextString(m) } -func (*Strings) ProtoMessage() {} -func (*Strings) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{20} -} -func (m *Strings) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Strings.Unmarshal(m, b) -} -func (m *Strings) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Strings.Marshal(b, m, deterministic) -} -func (dst *Strings) XXX_Merge(src proto.Message) { - xxx_messageInfo_Strings.Merge(dst, src) -} -func (m *Strings) XXX_Size() int { - return xxx_messageInfo_Strings.Size(m) -} -func (m *Strings) XXX_DiscardUnknown() { - xxx_messageInfo_Strings.DiscardUnknown(m) -} - -var xxx_messageInfo_Strings proto.InternalMessageInfo - -func (m *Strings) GetStringField() string { - if m != nil && m.StringField != nil { - return *m.StringField - } - return "" -} - -func (m *Strings) GetBytesField() []byte { - if m != nil { - return m.BytesField - } - return nil -} - -type Defaults struct { - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,def=1" json:"F_Bool,omitempty"` - F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,def=32" json:"F_Int32,omitempty"` - F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,def=64" json:"F_Int64,omitempty"` - F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,def=320" json:"F_Fixed32,omitempty"` - F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,def=640" json:"F_Fixed64,omitempty"` - F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,def=3200" json:"F_Uint32,omitempty"` - F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,def=6400" json:"F_Uint64,omitempty"` - F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,def=314159" json:"F_Float,omitempty"` - F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,def=271828" json:"F_Double,omitempty"` - F_String *string `protobuf:"bytes,10,opt,name=F_String,json=FString,def=hello, \"world!\"\n" json:"F_String,omitempty"` - F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,def=Bignose" json:"F_Bytes,omitempty"` - F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,def=-32" json:"F_Sint32,omitempty"` - F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,def=-64" json:"F_Sint64,omitempty"` - F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=test_proto.Defaults_Color,def=1" json:"F_Enum,omitempty"` - // More fields with crazy defaults. - F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=FPinf,def=inf" json:"F_Pinf,omitempty"` - F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=FNinf,def=-inf" json:"F_Ninf,omitempty"` - F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=FNan,def=nan" json:"F_Nan,omitempty"` - // Sub-message. - Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` - // Redundant but explicit defaults. - StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Defaults) Reset() { *m = Defaults{} } -func (m *Defaults) String() string { return proto.CompactTextString(m) } -func (*Defaults) ProtoMessage() {} -func (*Defaults) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{21} -} -func (m *Defaults) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Defaults.Unmarshal(m, b) -} -func (m *Defaults) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Defaults.Marshal(b, m, deterministic) -} -func (dst *Defaults) XXX_Merge(src proto.Message) { - xxx_messageInfo_Defaults.Merge(dst, src) -} -func (m *Defaults) XXX_Size() int { - return xxx_messageInfo_Defaults.Size(m) -} -func (m *Defaults) XXX_DiscardUnknown() { - xxx_messageInfo_Defaults.DiscardUnknown(m) -} - -var xxx_messageInfo_Defaults proto.InternalMessageInfo - -const Default_Defaults_F_Bool bool = true -const Default_Defaults_F_Int32 int32 = 32 -const Default_Defaults_F_Int64 int64 = 64 -const Default_Defaults_F_Fixed32 uint32 = 320 -const Default_Defaults_F_Fixed64 uint64 = 640 -const Default_Defaults_F_Uint32 uint32 = 3200 -const Default_Defaults_F_Uint64 uint64 = 6400 -const Default_Defaults_F_Float float32 = 314159 -const Default_Defaults_F_Double float64 = 271828 -const Default_Defaults_F_String string = "hello, \"world!\"\n" - -var Default_Defaults_F_Bytes []byte = []byte("Bignose") - -const Default_Defaults_F_Sint32 int32 = -32 -const Default_Defaults_F_Sint64 int64 = -64 -const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN - -var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) -var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) -var Default_Defaults_F_Nan float32 = float32(math.NaN()) - -func (m *Defaults) GetF_Bool() bool { - if m != nil && m.F_Bool != nil { - return *m.F_Bool - } - return Default_Defaults_F_Bool -} - -func (m *Defaults) GetF_Int32() int32 { - if m != nil && m.F_Int32 != nil { - return *m.F_Int32 - } - return Default_Defaults_F_Int32 -} - -func (m *Defaults) GetF_Int64() int64 { - if m != nil && m.F_Int64 != nil { - return *m.F_Int64 - } - return Default_Defaults_F_Int64 -} - -func (m *Defaults) GetF_Fixed32() uint32 { - if m != nil && m.F_Fixed32 != nil { - return *m.F_Fixed32 - } - return Default_Defaults_F_Fixed32 -} - -func (m *Defaults) GetF_Fixed64() uint64 { - if m != nil && m.F_Fixed64 != nil { - return *m.F_Fixed64 - } - return Default_Defaults_F_Fixed64 -} - -func (m *Defaults) GetF_Uint32() uint32 { - if m != nil && m.F_Uint32 != nil { - return *m.F_Uint32 - } - return Default_Defaults_F_Uint32 -} - -func (m *Defaults) GetF_Uint64() uint64 { - if m != nil && m.F_Uint64 != nil { - return *m.F_Uint64 - } - return Default_Defaults_F_Uint64 -} - -func (m *Defaults) GetF_Float() float32 { - if m != nil && m.F_Float != nil { - return *m.F_Float - } - return Default_Defaults_F_Float -} - -func (m *Defaults) GetF_Double() float64 { - if m != nil && m.F_Double != nil { - return *m.F_Double - } - return Default_Defaults_F_Double -} - -func (m *Defaults) GetF_String() string { - if m != nil && m.F_String != nil { - return *m.F_String - } - return Default_Defaults_F_String -} - -func (m *Defaults) GetF_Bytes() []byte { - if m != nil && m.F_Bytes != nil { - return m.F_Bytes - } - return append([]byte(nil), Default_Defaults_F_Bytes...) -} - -func (m *Defaults) GetF_Sint32() int32 { - if m != nil && m.F_Sint32 != nil { - return *m.F_Sint32 - } - return Default_Defaults_F_Sint32 -} - -func (m *Defaults) GetF_Sint64() int64 { - if m != nil && m.F_Sint64 != nil { - return *m.F_Sint64 - } - return Default_Defaults_F_Sint64 -} - -func (m *Defaults) GetF_Enum() Defaults_Color { - if m != nil && m.F_Enum != nil { - return *m.F_Enum - } - return Default_Defaults_F_Enum -} - -func (m *Defaults) GetF_Pinf() float32 { - if m != nil && m.F_Pinf != nil { - return *m.F_Pinf - } - return Default_Defaults_F_Pinf -} - -func (m *Defaults) GetF_Ninf() float32 { - if m != nil && m.F_Ninf != nil { - return *m.F_Ninf - } - return Default_Defaults_F_Ninf -} - -func (m *Defaults) GetF_Nan() float32 { - if m != nil && m.F_Nan != nil { - return *m.F_Nan - } - return Default_Defaults_F_Nan -} - -func (m *Defaults) GetSub() *SubDefaults { - if m != nil { - return m.Sub - } - return nil -} - -func (m *Defaults) GetStrZero() string { - if m != nil && m.StrZero != nil { - return *m.StrZero - } - return "" -} - -type SubDefaults struct { - N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SubDefaults) Reset() { *m = SubDefaults{} } -func (m *SubDefaults) String() string { return proto.CompactTextString(m) } -func (*SubDefaults) ProtoMessage() {} -func (*SubDefaults) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{22} -} -func (m *SubDefaults) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SubDefaults.Unmarshal(m, b) -} -func (m *SubDefaults) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SubDefaults.Marshal(b, m, deterministic) -} -func (dst *SubDefaults) XXX_Merge(src proto.Message) { - xxx_messageInfo_SubDefaults.Merge(dst, src) -} -func (m *SubDefaults) XXX_Size() int { - return xxx_messageInfo_SubDefaults.Size(m) -} -func (m *SubDefaults) XXX_DiscardUnknown() { - xxx_messageInfo_SubDefaults.DiscardUnknown(m) -} - -var xxx_messageInfo_SubDefaults proto.InternalMessageInfo - -const Default_SubDefaults_N int64 = 7 - -func (m *SubDefaults) GetN() int64 { - if m != nil && m.N != nil { - return *m.N - } - return Default_SubDefaults_N -} - -type RepeatedEnum struct { - Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=test_proto.RepeatedEnum_Color" json:"color,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } -func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } -func (*RepeatedEnum) ProtoMessage() {} -func (*RepeatedEnum) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{23} -} -func (m *RepeatedEnum) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RepeatedEnum.Unmarshal(m, b) -} -func (m *RepeatedEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RepeatedEnum.Marshal(b, m, deterministic) -} -func (dst *RepeatedEnum) XXX_Merge(src proto.Message) { - xxx_messageInfo_RepeatedEnum.Merge(dst, src) -} -func (m *RepeatedEnum) XXX_Size() int { - return xxx_messageInfo_RepeatedEnum.Size(m) -} -func (m *RepeatedEnum) XXX_DiscardUnknown() { - xxx_messageInfo_RepeatedEnum.DiscardUnknown(m) -} - -var xxx_messageInfo_RepeatedEnum proto.InternalMessageInfo - -func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { - if m != nil { - return m.Color - } - return nil -} - -type MoreRepeated struct { - Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` - BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"` - Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` - IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"` - Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"` - Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` - Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } -func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } -func (*MoreRepeated) ProtoMessage() {} -func (*MoreRepeated) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{24} -} -func (m *MoreRepeated) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MoreRepeated.Unmarshal(m, b) -} -func (m *MoreRepeated) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MoreRepeated.Marshal(b, m, deterministic) -} -func (dst *MoreRepeated) XXX_Merge(src proto.Message) { - xxx_messageInfo_MoreRepeated.Merge(dst, src) -} -func (m *MoreRepeated) XXX_Size() int { - return xxx_messageInfo_MoreRepeated.Size(m) -} -func (m *MoreRepeated) XXX_DiscardUnknown() { - xxx_messageInfo_MoreRepeated.DiscardUnknown(m) -} - -var xxx_messageInfo_MoreRepeated proto.InternalMessageInfo - -func (m *MoreRepeated) GetBools() []bool { - if m != nil { - return m.Bools - } - return nil -} - -func (m *MoreRepeated) GetBoolsPacked() []bool { - if m != nil { - return m.BoolsPacked - } - return nil -} - -func (m *MoreRepeated) GetInts() []int32 { - if m != nil { - return m.Ints - } - return nil -} - -func (m *MoreRepeated) GetIntsPacked() []int32 { - if m != nil { - return m.IntsPacked - } - return nil -} - -func (m *MoreRepeated) GetInt64SPacked() []int64 { - if m != nil { - return m.Int64SPacked - } - return nil -} - -func (m *MoreRepeated) GetStrings() []string { - if m != nil { - return m.Strings - } - return nil -} - -func (m *MoreRepeated) GetFixeds() []uint32 { - if m != nil { - return m.Fixeds - } - return nil -} - -type GroupOld struct { - G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GroupOld) Reset() { *m = GroupOld{} } -func (m *GroupOld) String() string { return proto.CompactTextString(m) } -func (*GroupOld) ProtoMessage() {} -func (*GroupOld) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{25} -} -func (m *GroupOld) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GroupOld.Unmarshal(m, b) -} -func (m *GroupOld) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GroupOld.Marshal(b, m, deterministic) -} -func (dst *GroupOld) XXX_Merge(src proto.Message) { - xxx_messageInfo_GroupOld.Merge(dst, src) -} -func (m *GroupOld) XXX_Size() int { - return xxx_messageInfo_GroupOld.Size(m) -} -func (m *GroupOld) XXX_DiscardUnknown() { - xxx_messageInfo_GroupOld.DiscardUnknown(m) -} - -var xxx_messageInfo_GroupOld proto.InternalMessageInfo - -func (m *GroupOld) GetG() *GroupOld_G { - if m != nil { - return m.G - } - return nil -} - -type GroupOld_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } -func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } -func (*GroupOld_G) ProtoMessage() {} -func (*GroupOld_G) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{25, 0} -} -func (m *GroupOld_G) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GroupOld_G.Unmarshal(m, b) -} -func (m *GroupOld_G) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GroupOld_G.Marshal(b, m, deterministic) -} -func (dst *GroupOld_G) XXX_Merge(src proto.Message) { - xxx_messageInfo_GroupOld_G.Merge(dst, src) -} -func (m *GroupOld_G) XXX_Size() int { - return xxx_messageInfo_GroupOld_G.Size(m) -} -func (m *GroupOld_G) XXX_DiscardUnknown() { - xxx_messageInfo_GroupOld_G.DiscardUnknown(m) -} - -var xxx_messageInfo_GroupOld_G proto.InternalMessageInfo - -func (m *GroupOld_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type GroupNew struct { - G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GroupNew) Reset() { *m = GroupNew{} } -func (m *GroupNew) String() string { return proto.CompactTextString(m) } -func (*GroupNew) ProtoMessage() {} -func (*GroupNew) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{26} -} -func (m *GroupNew) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GroupNew.Unmarshal(m, b) -} -func (m *GroupNew) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GroupNew.Marshal(b, m, deterministic) -} -func (dst *GroupNew) XXX_Merge(src proto.Message) { - xxx_messageInfo_GroupNew.Merge(dst, src) -} -func (m *GroupNew) XXX_Size() int { - return xxx_messageInfo_GroupNew.Size(m) -} -func (m *GroupNew) XXX_DiscardUnknown() { - xxx_messageInfo_GroupNew.DiscardUnknown(m) -} - -var xxx_messageInfo_GroupNew proto.InternalMessageInfo - -func (m *GroupNew) GetG() *GroupNew_G { - if m != nil { - return m.G - } - return nil -} - -type GroupNew_G struct { - X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` - Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } -func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } -func (*GroupNew_G) ProtoMessage() {} -func (*GroupNew_G) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{26, 0} -} -func (m *GroupNew_G) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GroupNew_G.Unmarshal(m, b) -} -func (m *GroupNew_G) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GroupNew_G.Marshal(b, m, deterministic) -} -func (dst *GroupNew_G) XXX_Merge(src proto.Message) { - xxx_messageInfo_GroupNew_G.Merge(dst, src) -} -func (m *GroupNew_G) XXX_Size() int { - return xxx_messageInfo_GroupNew_G.Size(m) -} -func (m *GroupNew_G) XXX_DiscardUnknown() { - xxx_messageInfo_GroupNew_G.DiscardUnknown(m) -} - -var xxx_messageInfo_GroupNew_G proto.InternalMessageInfo - -func (m *GroupNew_G) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *GroupNew_G) GetY() int32 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type FloatingPoint struct { - F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` - Exact *bool `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } -func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } -func (*FloatingPoint) ProtoMessage() {} -func (*FloatingPoint) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{27} -} -func (m *FloatingPoint) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FloatingPoint.Unmarshal(m, b) -} -func (m *FloatingPoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FloatingPoint.Marshal(b, m, deterministic) -} -func (dst *FloatingPoint) XXX_Merge(src proto.Message) { - xxx_messageInfo_FloatingPoint.Merge(dst, src) -} -func (m *FloatingPoint) XXX_Size() int { - return xxx_messageInfo_FloatingPoint.Size(m) -} -func (m *FloatingPoint) XXX_DiscardUnknown() { - xxx_messageInfo_FloatingPoint.DiscardUnknown(m) -} - -var xxx_messageInfo_FloatingPoint proto.InternalMessageInfo - -func (m *FloatingPoint) GetF() float64 { - if m != nil && m.F != nil { - return *m.F - } - return 0 -} - -func (m *FloatingPoint) GetExact() bool { - if m != nil && m.Exact != nil { - return *m.Exact - } - return false -} - -type MessageWithMap struct { - NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } -func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } -func (*MessageWithMap) ProtoMessage() {} -func (*MessageWithMap) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{28} -} -func (m *MessageWithMap) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageWithMap.Unmarshal(m, b) -} -func (m *MessageWithMap) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageWithMap.Marshal(b, m, deterministic) -} -func (dst *MessageWithMap) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageWithMap.Merge(dst, src) -} -func (m *MessageWithMap) XXX_Size() int { - return xxx_messageInfo_MessageWithMap.Size(m) -} -func (m *MessageWithMap) XXX_DiscardUnknown() { - xxx_messageInfo_MessageWithMap.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageWithMap proto.InternalMessageInfo - -func (m *MessageWithMap) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *MessageWithMap) GetByteMapping() map[bool][]byte { - if m != nil { - return m.ByteMapping - } - return nil -} - -func (m *MessageWithMap) GetStrToStr() map[string]string { - if m != nil { - return m.StrToStr - } - return nil -} - -type Oneof struct { - // Types that are valid to be assigned to Union: - // *Oneof_F_Bool - // *Oneof_F_Int32 - // *Oneof_F_Int64 - // *Oneof_F_Fixed32 - // *Oneof_F_Fixed64 - // *Oneof_F_Uint32 - // *Oneof_F_Uint64 - // *Oneof_F_Float - // *Oneof_F_Double - // *Oneof_F_String - // *Oneof_F_Bytes - // *Oneof_F_Sint32 - // *Oneof_F_Sint64 - // *Oneof_F_Enum - // *Oneof_F_Message - // *Oneof_FGroup - // *Oneof_F_Largest_Tag - Union isOneof_Union `protobuf_oneof:"union"` - // Types that are valid to be assigned to Tormato: - // *Oneof_Value - Tormato isOneof_Tormato `protobuf_oneof:"tormato"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Oneof) Reset() { *m = Oneof{} } -func (m *Oneof) String() string { return proto.CompactTextString(m) } -func (*Oneof) ProtoMessage() {} -func (*Oneof) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{29} -} -func (m *Oneof) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Oneof.Unmarshal(m, b) -} -func (m *Oneof) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Oneof.Marshal(b, m, deterministic) -} -func (dst *Oneof) XXX_Merge(src proto.Message) { - xxx_messageInfo_Oneof.Merge(dst, src) -} -func (m *Oneof) XXX_Size() int { - return xxx_messageInfo_Oneof.Size(m) -} -func (m *Oneof) XXX_DiscardUnknown() { - xxx_messageInfo_Oneof.DiscardUnknown(m) -} - -var xxx_messageInfo_Oneof proto.InternalMessageInfo - -type isOneof_Union interface { - isOneof_Union() -} -type isOneof_Tormato interface { - isOneof_Tormato() -} - -type Oneof_F_Bool struct { - F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,oneof"` -} -type Oneof_F_Int32 struct { - F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,oneof"` -} -type Oneof_F_Int64 struct { - F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,oneof"` -} -type Oneof_F_Fixed32 struct { - F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,oneof"` -} -type Oneof_F_Fixed64 struct { - F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,oneof"` -} -type Oneof_F_Uint32 struct { - F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,oneof"` -} -type Oneof_F_Uint64 struct { - F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,oneof"` -} -type Oneof_F_Float struct { - F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,oneof"` -} -type Oneof_F_Double struct { - F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,oneof"` -} -type Oneof_F_String struct { - F_String string `protobuf:"bytes,10,opt,name=F_String,json=FString,oneof"` -} -type Oneof_F_Bytes struct { - F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,oneof"` -} -type Oneof_F_Sint32 struct { - F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,oneof"` -} -type Oneof_F_Sint64 struct { - F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,oneof"` -} -type Oneof_F_Enum struct { - F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=test_proto.MyMessage_Color,oneof"` -} -type Oneof_F_Message struct { - F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=FMessage,oneof"` -} -type Oneof_FGroup struct { - FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"` -} -type Oneof_F_Largest_Tag struct { - F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=FLargestTag,oneof"` -} -type Oneof_Value struct { - Value int32 `protobuf:"varint,100,opt,name=value,oneof"` -} - -func (*Oneof_F_Bool) isOneof_Union() {} -func (*Oneof_F_Int32) isOneof_Union() {} -func (*Oneof_F_Int64) isOneof_Union() {} -func (*Oneof_F_Fixed32) isOneof_Union() {} -func (*Oneof_F_Fixed64) isOneof_Union() {} -func (*Oneof_F_Uint32) isOneof_Union() {} -func (*Oneof_F_Uint64) isOneof_Union() {} -func (*Oneof_F_Float) isOneof_Union() {} -func (*Oneof_F_Double) isOneof_Union() {} -func (*Oneof_F_String) isOneof_Union() {} -func (*Oneof_F_Bytes) isOneof_Union() {} -func (*Oneof_F_Sint32) isOneof_Union() {} -func (*Oneof_F_Sint64) isOneof_Union() {} -func (*Oneof_F_Enum) isOneof_Union() {} -func (*Oneof_F_Message) isOneof_Union() {} -func (*Oneof_FGroup) isOneof_Union() {} -func (*Oneof_F_Largest_Tag) isOneof_Union() {} -func (*Oneof_Value) isOneof_Tormato() {} - -func (m *Oneof) GetUnion() isOneof_Union { - if m != nil { - return m.Union - } - return nil -} -func (m *Oneof) GetTormato() isOneof_Tormato { - if m != nil { - return m.Tormato - } - return nil -} - -func (m *Oneof) GetF_Bool() bool { - if x, ok := m.GetUnion().(*Oneof_F_Bool); ok { - return x.F_Bool - } - return false -} - -func (m *Oneof) GetF_Int32() int32 { - if x, ok := m.GetUnion().(*Oneof_F_Int32); ok { - return x.F_Int32 - } - return 0 -} - -func (m *Oneof) GetF_Int64() int64 { - if x, ok := m.GetUnion().(*Oneof_F_Int64); ok { - return x.F_Int64 - } - return 0 -} - -func (m *Oneof) GetF_Fixed32() uint32 { - if x, ok := m.GetUnion().(*Oneof_F_Fixed32); ok { - return x.F_Fixed32 - } - return 0 -} - -func (m *Oneof) GetF_Fixed64() uint64 { - if x, ok := m.GetUnion().(*Oneof_F_Fixed64); ok { - return x.F_Fixed64 - } - return 0 -} - -func (m *Oneof) GetF_Uint32() uint32 { - if x, ok := m.GetUnion().(*Oneof_F_Uint32); ok { - return x.F_Uint32 - } - return 0 -} - -func (m *Oneof) GetF_Uint64() uint64 { - if x, ok := m.GetUnion().(*Oneof_F_Uint64); ok { - return x.F_Uint64 - } - return 0 -} - -func (m *Oneof) GetF_Float() float32 { - if x, ok := m.GetUnion().(*Oneof_F_Float); ok { - return x.F_Float - } - return 0 -} - -func (m *Oneof) GetF_Double() float64 { - if x, ok := m.GetUnion().(*Oneof_F_Double); ok { - return x.F_Double - } - return 0 -} - -func (m *Oneof) GetF_String() string { - if x, ok := m.GetUnion().(*Oneof_F_String); ok { - return x.F_String - } - return "" -} - -func (m *Oneof) GetF_Bytes() []byte { - if x, ok := m.GetUnion().(*Oneof_F_Bytes); ok { - return x.F_Bytes - } - return nil -} - -func (m *Oneof) GetF_Sint32() int32 { - if x, ok := m.GetUnion().(*Oneof_F_Sint32); ok { - return x.F_Sint32 - } - return 0 -} - -func (m *Oneof) GetF_Sint64() int64 { - if x, ok := m.GetUnion().(*Oneof_F_Sint64); ok { - return x.F_Sint64 - } - return 0 -} - -func (m *Oneof) GetF_Enum() MyMessage_Color { - if x, ok := m.GetUnion().(*Oneof_F_Enum); ok { - return x.F_Enum - } - return MyMessage_RED -} - -func (m *Oneof) GetF_Message() *GoTestField { - if x, ok := m.GetUnion().(*Oneof_F_Message); ok { - return x.F_Message - } - return nil -} - -func (m *Oneof) GetFGroup() *Oneof_F_Group { - if x, ok := m.GetUnion().(*Oneof_FGroup); ok { - return x.FGroup - } - return nil -} - -func (m *Oneof) GetF_Largest_Tag() int32 { - if x, ok := m.GetUnion().(*Oneof_F_Largest_Tag); ok { - return x.F_Largest_Tag - } - return 0 -} - -func (m *Oneof) GetValue() int32 { - if x, ok := m.GetTormato().(*Oneof_Value); ok { - return x.Value - } - return 0 -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{ - (*Oneof_F_Bool)(nil), - (*Oneof_F_Int32)(nil), - (*Oneof_F_Int64)(nil), - (*Oneof_F_Fixed32)(nil), - (*Oneof_F_Fixed64)(nil), - (*Oneof_F_Uint32)(nil), - (*Oneof_F_Uint64)(nil), - (*Oneof_F_Float)(nil), - (*Oneof_F_Double)(nil), - (*Oneof_F_String)(nil), - (*Oneof_F_Bytes)(nil), - (*Oneof_F_Sint32)(nil), - (*Oneof_F_Sint64)(nil), - (*Oneof_F_Enum)(nil), - (*Oneof_F_Message)(nil), - (*Oneof_FGroup)(nil), - (*Oneof_F_Largest_Tag)(nil), - (*Oneof_Value)(nil), - } -} - -func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Oneof) - // union - switch x := m.Union.(type) { - case *Oneof_F_Bool: - t := uint64(0) - if x.F_Bool { - t = 1 - } - b.EncodeVarint(1<<3 | proto.WireVarint) - b.EncodeVarint(t) - case *Oneof_F_Int32: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Int32)) - case *Oneof_F_Int64: - b.EncodeVarint(3<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Int64)) - case *Oneof_F_Fixed32: - b.EncodeVarint(4<<3 | proto.WireFixed32) - b.EncodeFixed32(uint64(x.F_Fixed32)) - case *Oneof_F_Fixed64: - b.EncodeVarint(5<<3 | proto.WireFixed64) - b.EncodeFixed64(uint64(x.F_Fixed64)) - case *Oneof_F_Uint32: - b.EncodeVarint(6<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Uint32)) - case *Oneof_F_Uint64: - b.EncodeVarint(7<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Uint64)) - case *Oneof_F_Float: - b.EncodeVarint(8<<3 | proto.WireFixed32) - b.EncodeFixed32(uint64(math.Float32bits(x.F_Float))) - case *Oneof_F_Double: - b.EncodeVarint(9<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.F_Double)) - case *Oneof_F_String: - b.EncodeVarint(10<<3 | proto.WireBytes) - b.EncodeStringBytes(x.F_String) - case *Oneof_F_Bytes: - b.EncodeVarint(11<<3 | proto.WireBytes) - b.EncodeRawBytes(x.F_Bytes) - case *Oneof_F_Sint32: - b.EncodeVarint(12<<3 | proto.WireVarint) - b.EncodeZigzag32(uint64(x.F_Sint32)) - case *Oneof_F_Sint64: - b.EncodeVarint(13<<3 | proto.WireVarint) - b.EncodeZigzag64(uint64(x.F_Sint64)) - case *Oneof_F_Enum: - b.EncodeVarint(14<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Enum)) - case *Oneof_F_Message: - b.EncodeVarint(15<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.F_Message); err != nil { - return err - } - case *Oneof_FGroup: - b.EncodeVarint(16<<3 | proto.WireStartGroup) - if err := b.Marshal(x.FGroup); err != nil { - return err - } - b.EncodeVarint(16<<3 | proto.WireEndGroup) - case *Oneof_F_Largest_Tag: - b.EncodeVarint(536870911<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.F_Largest_Tag)) - case nil: - default: - return fmt.Errorf("Oneof.Union has unexpected type %T", x) - } - // tormato - switch x := m.Tormato.(type) { - case *Oneof_Value: - b.EncodeVarint(100<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Value)) - case nil: - default: - return fmt.Errorf("Oneof.Tormato has unexpected type %T", x) - } - return nil -} - -func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Oneof) - switch tag { - case 1: // union.F_Bool - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Bool{x != 0} - return true, err - case 2: // union.F_Int32 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Int32{int32(x)} - return true, err - case 3: // union.F_Int64 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Int64{int64(x)} - return true, err - case 4: // union.F_Fixed32 - if wire != proto.WireFixed32 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed32() - m.Union = &Oneof_F_Fixed32{uint32(x)} - return true, err - case 5: // union.F_Fixed64 - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Union = &Oneof_F_Fixed64{x} - return true, err - case 6: // union.F_Uint32 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Uint32{uint32(x)} - return true, err - case 7: // union.F_Uint64 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Uint64{x} - return true, err - case 8: // union.F_Float - if wire != proto.WireFixed32 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed32() - m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))} - return true, err - case 9: // union.F_Double - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Union = &Oneof_F_Double{math.Float64frombits(x)} - return true, err - case 10: // union.F_String - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &Oneof_F_String{x} - return true, err - case 11: // union.F_Bytes - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Union = &Oneof_F_Bytes{x} - return true, err - case 12: // union.F_Sint32 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeZigzag32() - m.Union = &Oneof_F_Sint32{int32(x)} - return true, err - case 13: // union.F_Sint64 - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeZigzag64() - m.Union = &Oneof_F_Sint64{int64(x)} - return true, err - case 14: // union.F_Enum - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Enum{MyMessage_Color(x)} - return true, err - case 15: // union.F_Message - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(GoTestField) - err := b.DecodeMessage(msg) - m.Union = &Oneof_F_Message{msg} - return true, err - case 16: // union.f_group - if wire != proto.WireStartGroup { - return true, proto.ErrInternalBadWireType - } - msg := new(Oneof_F_Group) - err := b.DecodeGroup(msg) - m.Union = &Oneof_FGroup{msg} - return true, err - case 536870911: // union.F_Largest_Tag - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Oneof_F_Largest_Tag{int32(x)} - return true, err - case 100: // tormato.value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Tormato = &Oneof_Value{int32(x)} - return true, err - default: - return false, nil - } -} - -func _Oneof_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Oneof) - // union - switch x := m.Union.(type) { - case *Oneof_F_Bool: - n += 1 // tag and wire - n += 1 - case *Oneof_F_Int32: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.F_Int32)) - case *Oneof_F_Int64: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.F_Int64)) - case *Oneof_F_Fixed32: - n += 1 // tag and wire - n += 4 - case *Oneof_F_Fixed64: - n += 1 // tag and wire - n += 8 - case *Oneof_F_Uint32: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.F_Uint32)) - case *Oneof_F_Uint64: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.F_Uint64)) - case *Oneof_F_Float: - n += 1 // tag and wire - n += 4 - case *Oneof_F_Double: - n += 1 // tag and wire - n += 8 - case *Oneof_F_String: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.F_String))) - n += len(x.F_String) - case *Oneof_F_Bytes: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.F_Bytes))) - n += len(x.F_Bytes) - case *Oneof_F_Sint32: - n += 1 // tag and wire - n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31)))) - case *Oneof_F_Sint64: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63)))) - case *Oneof_F_Enum: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.F_Enum)) - case *Oneof_F_Message: - s := proto.Size(x.F_Message) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Oneof_FGroup: - n += 2 // tag and wire - n += proto.Size(x.FGroup) - n += 2 // tag and wire - case *Oneof_F_Largest_Tag: - n += 10 // tag and wire - n += proto.SizeVarint(uint64(x.F_Largest_Tag)) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - // tormato - switch x := m.Tormato.(type) { - case *Oneof_Value: - n += 2 // tag and wire - n += proto.SizeVarint(uint64(x.Value)) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Oneof_F_Group struct { - X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} } -func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) } -func (*Oneof_F_Group) ProtoMessage() {} -func (*Oneof_F_Group) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{29, 0} -} -func (m *Oneof_F_Group) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Oneof_F_Group.Unmarshal(m, b) -} -func (m *Oneof_F_Group) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Oneof_F_Group.Marshal(b, m, deterministic) -} -func (dst *Oneof_F_Group) XXX_Merge(src proto.Message) { - xxx_messageInfo_Oneof_F_Group.Merge(dst, src) -} -func (m *Oneof_F_Group) XXX_Size() int { - return xxx_messageInfo_Oneof_F_Group.Size(m) -} -func (m *Oneof_F_Group) XXX_DiscardUnknown() { - xxx_messageInfo_Oneof_F_Group.DiscardUnknown(m) -} - -var xxx_messageInfo_Oneof_F_Group proto.InternalMessageInfo - -func (m *Oneof_F_Group) GetX() int32 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -type Communique struct { - MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` - // This is a oneof, called "union". - // - // Types that are valid to be assigned to Union: - // *Communique_Number - // *Communique_Name - // *Communique_Data - // *Communique_TempC - // *Communique_Col - // *Communique_Msg - Union isCommunique_Union `protobuf_oneof:"union"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Communique) Reset() { *m = Communique{} } -func (m *Communique) String() string { return proto.CompactTextString(m) } -func (*Communique) ProtoMessage() {} -func (*Communique) Descriptor() ([]byte, []int) { - return fileDescriptor_test_74787bfc6550f8a7, []int{30} -} -func (m *Communique) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Communique.Unmarshal(m, b) -} -func (m *Communique) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Communique.Marshal(b, m, deterministic) -} -func (dst *Communique) XXX_Merge(src proto.Message) { - xxx_messageInfo_Communique.Merge(dst, src) -} -func (m *Communique) XXX_Size() int { - return xxx_messageInfo_Communique.Size(m) -} -func (m *Communique) XXX_DiscardUnknown() { - xxx_messageInfo_Communique.DiscardUnknown(m) -} - -var xxx_messageInfo_Communique proto.InternalMessageInfo - -type isCommunique_Union interface { - isCommunique_Union() -} - -type Communique_Number struct { - Number int32 `protobuf:"varint,5,opt,name=number,oneof"` -} -type Communique_Name struct { - Name string `protobuf:"bytes,6,opt,name=name,oneof"` -} -type Communique_Data struct { - Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` -} -type Communique_TempC struct { - TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` -} -type Communique_Col struct { - Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=test_proto.MyMessage_Color,oneof"` -} -type Communique_Msg struct { - Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"` -} - -func (*Communique_Number) isCommunique_Union() {} -func (*Communique_Name) isCommunique_Union() {} -func (*Communique_Data) isCommunique_Union() {} -func (*Communique_TempC) isCommunique_Union() {} -func (*Communique_Col) isCommunique_Union() {} -func (*Communique_Msg) isCommunique_Union() {} - -func (m *Communique) GetUnion() isCommunique_Union { - if m != nil { - return m.Union - } - return nil -} - -func (m *Communique) GetMakeMeCry() bool { - if m != nil && m.MakeMeCry != nil { - return *m.MakeMeCry - } - return false -} - -func (m *Communique) GetNumber() int32 { - if x, ok := m.GetUnion().(*Communique_Number); ok { - return x.Number - } - return 0 -} - -func (m *Communique) GetName() string { - if x, ok := m.GetUnion().(*Communique_Name); ok { - return x.Name - } - return "" -} - -func (m *Communique) GetData() []byte { - if x, ok := m.GetUnion().(*Communique_Data); ok { - return x.Data - } - return nil -} - -func (m *Communique) GetTempC() float64 { - if x, ok := m.GetUnion().(*Communique_TempC); ok { - return x.TempC - } - return 0 -} - -func (m *Communique) GetCol() MyMessage_Color { - if x, ok := m.GetUnion().(*Communique_Col); ok { - return x.Col - } - return MyMessage_RED -} - -func (m *Communique) GetMsg() *Strings { - if x, ok := m.GetUnion().(*Communique_Msg); ok { - return x.Msg - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ - (*Communique_Number)(nil), - (*Communique_Name)(nil), - (*Communique_Data)(nil), - (*Communique_TempC)(nil), - (*Communique_Col)(nil), - (*Communique_Msg)(nil), - } -} - -func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Communique) - // union - switch x := m.Union.(type) { - case *Communique_Number: - b.EncodeVarint(5<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Number)) - case *Communique_Name: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Name) - case *Communique_Data: - b.EncodeVarint(7<<3 | proto.WireBytes) - b.EncodeRawBytes(x.Data) - case *Communique_TempC: - b.EncodeVarint(8<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.TempC)) - case *Communique_Col: - b.EncodeVarint(9<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Col)) - case *Communique_Msg: - b.EncodeVarint(10<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Msg); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("Communique.Union has unexpected type %T", x) - } - return nil -} - -func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Communique) - switch tag { - case 5: // union.number - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Number{int32(x)} - return true, err - case 6: // union.name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &Communique_Name{x} - return true, err - case 7: // union.data - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Union = &Communique_Data{x} - return true, err - case 8: // union.temp_c - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Union = &Communique_TempC{math.Float64frombits(x)} - return true, err - case 9: // union.col - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Col{MyMessage_Color(x)} - return true, err - case 10: // union.msg - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Strings) - err := b.DecodeMessage(msg) - m.Union = &Communique_Msg{msg} - return true, err - default: - return false, nil - } -} - -func _Communique_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Communique) - // union - switch x := m.Union.(type) { - case *Communique_Number: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Number)) - case *Communique_Name: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Name))) - n += len(x.Name) - case *Communique_Data: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Data))) - n += len(x.Data) - case *Communique_TempC: - n += 1 // tag and wire - n += 8 - case *Communique_Col: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Col)) - case *Communique_Msg: - s := proto.Size(x.Msg) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -var E_Greeting = &proto.ExtensionDesc{ - ExtendedType: (*MyMessage)(nil), - ExtensionType: ([]string)(nil), - Field: 106, - Name: "test_proto.greeting", - Tag: "bytes,106,rep,name=greeting", - Filename: "test_proto/test.proto", -} - -var E_Complex = &proto.ExtensionDesc{ - ExtendedType: (*OtherMessage)(nil), - ExtensionType: (*ComplexExtension)(nil), - Field: 200, - Name: "test_proto.complex", - Tag: "bytes,200,opt,name=complex", - Filename: "test_proto/test.proto", -} - -var E_RComplex = &proto.ExtensionDesc{ - ExtendedType: (*OtherMessage)(nil), - ExtensionType: ([]*ComplexExtension)(nil), - Field: 201, - Name: "test_proto.r_complex", - Tag: "bytes,201,rep,name=r_complex,json=rComplex", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 101, - Name: "test_proto.no_default_double", - Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 102, - Name: "test_proto.no_default_float", - Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 103, - Name: "test_proto.no_default_int32", - Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 104, - Name: "test_proto.no_default_int64", - Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 105, - Name: "test_proto.no_default_uint32", - Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 106, - Name: "test_proto.no_default_uint64", - Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 107, - Name: "test_proto.no_default_sint32", - Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 108, - Name: "test_proto.no_default_sint64", - Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 109, - Name: "test_proto.no_default_fixed32", - Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 110, - Name: "test_proto.no_default_fixed64", - Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 111, - Name: "test_proto.no_default_sfixed32", - Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 112, - Name: "test_proto.no_default_sfixed64", - Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 113, - Name: "test_proto.no_default_bool", - Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 114, - Name: "test_proto.no_default_string", - Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 115, - Name: "test_proto.no_default_bytes", - Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes", - Filename: "test_proto/test.proto", -} - -var E_NoDefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 116, - Name: "test_proto.no_default_enum", - Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=test_proto.DefaultsMessage_DefaultsEnum", - Filename: "test_proto/test.proto", -} - -var E_DefaultDouble = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float64)(nil), - Field: 201, - Name: "test_proto.default_double", - Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415", - Filename: "test_proto/test.proto", -} - -var E_DefaultFloat = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*float32)(nil), - Field: 202, - Name: "test_proto.default_float", - Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14", - Filename: "test_proto/test.proto", -} - -var E_DefaultInt32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 203, - Name: "test_proto.default_int32", - Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42", - Filename: "test_proto/test.proto", -} - -var E_DefaultInt64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 204, - Name: "test_proto.default_int64", - Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43", - Filename: "test_proto/test.proto", -} - -var E_DefaultUint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 205, - Name: "test_proto.default_uint32", - Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44", - Filename: "test_proto/test.proto", -} - -var E_DefaultUint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 206, - Name: "test_proto.default_uint64", - Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45", - Filename: "test_proto/test.proto", -} - -var E_DefaultSint32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 207, - Name: "test_proto.default_sint32", - Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46", - Filename: "test_proto/test.proto", -} - -var E_DefaultSint64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 208, - Name: "test_proto.default_sint64", - Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47", - Filename: "test_proto/test.proto", -} - -var E_DefaultFixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 209, - Name: "test_proto.default_fixed32", - Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48", - Filename: "test_proto/test.proto", -} - -var E_DefaultFixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*uint64)(nil), - Field: 210, - Name: "test_proto.default_fixed64", - Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49", - Filename: "test_proto/test.proto", -} - -var E_DefaultSfixed32 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 211, - Name: "test_proto.default_sfixed32", - Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50", - Filename: "test_proto/test.proto", -} - -var E_DefaultSfixed64 = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 212, - Name: "test_proto.default_sfixed64", - Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51", - Filename: "test_proto/test.proto", -} - -var E_DefaultBool = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 213, - Name: "test_proto.default_bool", - Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1", - Filename: "test_proto/test.proto", -} - -var E_DefaultString = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*string)(nil), - Field: 214, - Name: "test_proto.default_string", - Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string,def=foo", - Filename: "test_proto/test.proto", -} - -var E_DefaultBytes = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: ([]byte)(nil), - Field: 215, - Name: "test_proto.default_bytes", - Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes", - Filename: "test_proto/test.proto", -} - -var E_DefaultEnum = &proto.ExtensionDesc{ - ExtendedType: (*DefaultsMessage)(nil), - ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), - Field: 216, - Name: "test_proto.default_enum", - Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=test_proto.DefaultsMessage_DefaultsEnum,def=1", - Filename: "test_proto/test.proto", -} - -var E_X201 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 201, - Name: "test_proto.x201", - Tag: "bytes,201,opt,name=x201", - Filename: "test_proto/test.proto", -} - -var E_X202 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 202, - Name: "test_proto.x202", - Tag: "bytes,202,opt,name=x202", - Filename: "test_proto/test.proto", -} - -var E_X203 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 203, - Name: "test_proto.x203", - Tag: "bytes,203,opt,name=x203", - Filename: "test_proto/test.proto", -} - -var E_X204 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 204, - Name: "test_proto.x204", - Tag: "bytes,204,opt,name=x204", - Filename: "test_proto/test.proto", -} - -var E_X205 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 205, - Name: "test_proto.x205", - Tag: "bytes,205,opt,name=x205", - Filename: "test_proto/test.proto", -} - -var E_X206 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 206, - Name: "test_proto.x206", - Tag: "bytes,206,opt,name=x206", - Filename: "test_proto/test.proto", -} - -var E_X207 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 207, - Name: "test_proto.x207", - Tag: "bytes,207,opt,name=x207", - Filename: "test_proto/test.proto", -} - -var E_X208 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 208, - Name: "test_proto.x208", - Tag: "bytes,208,opt,name=x208", - Filename: "test_proto/test.proto", -} - -var E_X209 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 209, - Name: "test_proto.x209", - Tag: "bytes,209,opt,name=x209", - Filename: "test_proto/test.proto", -} - -var E_X210 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 210, - Name: "test_proto.x210", - Tag: "bytes,210,opt,name=x210", - Filename: "test_proto/test.proto", -} - -var E_X211 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 211, - Name: "test_proto.x211", - Tag: "bytes,211,opt,name=x211", - Filename: "test_proto/test.proto", -} - -var E_X212 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 212, - Name: "test_proto.x212", - Tag: "bytes,212,opt,name=x212", - Filename: "test_proto/test.proto", -} - -var E_X213 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 213, - Name: "test_proto.x213", - Tag: "bytes,213,opt,name=x213", - Filename: "test_proto/test.proto", -} - -var E_X214 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 214, - Name: "test_proto.x214", - Tag: "bytes,214,opt,name=x214", - Filename: "test_proto/test.proto", -} - -var E_X215 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 215, - Name: "test_proto.x215", - Tag: "bytes,215,opt,name=x215", - Filename: "test_proto/test.proto", -} - -var E_X216 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 216, - Name: "test_proto.x216", - Tag: "bytes,216,opt,name=x216", - Filename: "test_proto/test.proto", -} - -var E_X217 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 217, - Name: "test_proto.x217", - Tag: "bytes,217,opt,name=x217", - Filename: "test_proto/test.proto", -} - -var E_X218 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 218, - Name: "test_proto.x218", - Tag: "bytes,218,opt,name=x218", - Filename: "test_proto/test.proto", -} - -var E_X219 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 219, - Name: "test_proto.x219", - Tag: "bytes,219,opt,name=x219", - Filename: "test_proto/test.proto", -} - -var E_X220 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 220, - Name: "test_proto.x220", - Tag: "bytes,220,opt,name=x220", - Filename: "test_proto/test.proto", -} - -var E_X221 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 221, - Name: "test_proto.x221", - Tag: "bytes,221,opt,name=x221", - Filename: "test_proto/test.proto", -} - -var E_X222 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 222, - Name: "test_proto.x222", - Tag: "bytes,222,opt,name=x222", - Filename: "test_proto/test.proto", -} - -var E_X223 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 223, - Name: "test_proto.x223", - Tag: "bytes,223,opt,name=x223", - Filename: "test_proto/test.proto", -} - -var E_X224 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 224, - Name: "test_proto.x224", - Tag: "bytes,224,opt,name=x224", - Filename: "test_proto/test.proto", -} - -var E_X225 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 225, - Name: "test_proto.x225", - Tag: "bytes,225,opt,name=x225", - Filename: "test_proto/test.proto", -} - -var E_X226 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 226, - Name: "test_proto.x226", - Tag: "bytes,226,opt,name=x226", - Filename: "test_proto/test.proto", -} - -var E_X227 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 227, - Name: "test_proto.x227", - Tag: "bytes,227,opt,name=x227", - Filename: "test_proto/test.proto", -} - -var E_X228 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 228, - Name: "test_proto.x228", - Tag: "bytes,228,opt,name=x228", - Filename: "test_proto/test.proto", -} - -var E_X229 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 229, - Name: "test_proto.x229", - Tag: "bytes,229,opt,name=x229", - Filename: "test_proto/test.proto", -} - -var E_X230 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 230, - Name: "test_proto.x230", - Tag: "bytes,230,opt,name=x230", - Filename: "test_proto/test.proto", -} - -var E_X231 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 231, - Name: "test_proto.x231", - Tag: "bytes,231,opt,name=x231", - Filename: "test_proto/test.proto", -} - -var E_X232 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 232, - Name: "test_proto.x232", - Tag: "bytes,232,opt,name=x232", - Filename: "test_proto/test.proto", -} - -var E_X233 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 233, - Name: "test_proto.x233", - Tag: "bytes,233,opt,name=x233", - Filename: "test_proto/test.proto", -} - -var E_X234 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 234, - Name: "test_proto.x234", - Tag: "bytes,234,opt,name=x234", - Filename: "test_proto/test.proto", -} - -var E_X235 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 235, - Name: "test_proto.x235", - Tag: "bytes,235,opt,name=x235", - Filename: "test_proto/test.proto", -} - -var E_X236 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 236, - Name: "test_proto.x236", - Tag: "bytes,236,opt,name=x236", - Filename: "test_proto/test.proto", -} - -var E_X237 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 237, - Name: "test_proto.x237", - Tag: "bytes,237,opt,name=x237", - Filename: "test_proto/test.proto", -} - -var E_X238 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 238, - Name: "test_proto.x238", - Tag: "bytes,238,opt,name=x238", - Filename: "test_proto/test.proto", -} - -var E_X239 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 239, - Name: "test_proto.x239", - Tag: "bytes,239,opt,name=x239", - Filename: "test_proto/test.proto", -} - -var E_X240 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 240, - Name: "test_proto.x240", - Tag: "bytes,240,opt,name=x240", - Filename: "test_proto/test.proto", -} - -var E_X241 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 241, - Name: "test_proto.x241", - Tag: "bytes,241,opt,name=x241", - Filename: "test_proto/test.proto", -} - -var E_X242 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 242, - Name: "test_proto.x242", - Tag: "bytes,242,opt,name=x242", - Filename: "test_proto/test.proto", -} - -var E_X243 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 243, - Name: "test_proto.x243", - Tag: "bytes,243,opt,name=x243", - Filename: "test_proto/test.proto", -} - -var E_X244 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 244, - Name: "test_proto.x244", - Tag: "bytes,244,opt,name=x244", - Filename: "test_proto/test.proto", -} - -var E_X245 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 245, - Name: "test_proto.x245", - Tag: "bytes,245,opt,name=x245", - Filename: "test_proto/test.proto", -} - -var E_X246 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 246, - Name: "test_proto.x246", - Tag: "bytes,246,opt,name=x246", - Filename: "test_proto/test.proto", -} - -var E_X247 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 247, - Name: "test_proto.x247", - Tag: "bytes,247,opt,name=x247", - Filename: "test_proto/test.proto", -} - -var E_X248 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 248, - Name: "test_proto.x248", - Tag: "bytes,248,opt,name=x248", - Filename: "test_proto/test.proto", -} - -var E_X249 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 249, - Name: "test_proto.x249", - Tag: "bytes,249,opt,name=x249", - Filename: "test_proto/test.proto", -} - -var E_X250 = &proto.ExtensionDesc{ - ExtendedType: (*MyMessageSet)(nil), - ExtensionType: (*Empty)(nil), - Field: 250, - Name: "test_proto.x250", - Tag: "bytes,250,opt,name=x250", - Filename: "test_proto/test.proto", -} - -func init() { - proto.RegisterType((*GoEnum)(nil), "test_proto.GoEnum") - proto.RegisterType((*GoTestField)(nil), "test_proto.GoTestField") - proto.RegisterType((*GoTest)(nil), "test_proto.GoTest") - proto.RegisterType((*GoTest_RequiredGroup)(nil), "test_proto.GoTest.RequiredGroup") - proto.RegisterType((*GoTest_RepeatedGroup)(nil), "test_proto.GoTest.RepeatedGroup") - proto.RegisterType((*GoTest_OptionalGroup)(nil), "test_proto.GoTest.OptionalGroup") - proto.RegisterType((*GoTestRequiredGroupField)(nil), "test_proto.GoTestRequiredGroupField") - proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "test_proto.GoTestRequiredGroupField.Group") - proto.RegisterType((*GoSkipTest)(nil), "test_proto.GoSkipTest") - proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "test_proto.GoSkipTest.SkipGroup") - proto.RegisterType((*NonPackedTest)(nil), "test_proto.NonPackedTest") - proto.RegisterType((*PackedTest)(nil), "test_proto.PackedTest") - proto.RegisterType((*MaxTag)(nil), "test_proto.MaxTag") - proto.RegisterType((*OldMessage)(nil), "test_proto.OldMessage") - proto.RegisterType((*OldMessage_Nested)(nil), "test_proto.OldMessage.Nested") - proto.RegisterType((*NewMessage)(nil), "test_proto.NewMessage") - proto.RegisterType((*NewMessage_Nested)(nil), "test_proto.NewMessage.Nested") - proto.RegisterType((*InnerMessage)(nil), "test_proto.InnerMessage") - proto.RegisterType((*OtherMessage)(nil), "test_proto.OtherMessage") - proto.RegisterType((*RequiredInnerMessage)(nil), "test_proto.RequiredInnerMessage") - proto.RegisterType((*MyMessage)(nil), "test_proto.MyMessage") - proto.RegisterType((*MyMessage_SomeGroup)(nil), "test_proto.MyMessage.SomeGroup") - proto.RegisterType((*Ext)(nil), "test_proto.Ext") - proto.RegisterMapType((map[int32]int32)(nil), "test_proto.Ext.MapFieldEntry") - proto.RegisterType((*ComplexExtension)(nil), "test_proto.ComplexExtension") - proto.RegisterType((*DefaultsMessage)(nil), "test_proto.DefaultsMessage") - proto.RegisterType((*MyMessageSet)(nil), "test_proto.MyMessageSet") - proto.RegisterType((*Empty)(nil), "test_proto.Empty") - proto.RegisterType((*MessageList)(nil), "test_proto.MessageList") - proto.RegisterType((*MessageList_Message)(nil), "test_proto.MessageList.Message") - proto.RegisterType((*Strings)(nil), "test_proto.Strings") - proto.RegisterType((*Defaults)(nil), "test_proto.Defaults") - proto.RegisterType((*SubDefaults)(nil), "test_proto.SubDefaults") - proto.RegisterType((*RepeatedEnum)(nil), "test_proto.RepeatedEnum") - proto.RegisterType((*MoreRepeated)(nil), "test_proto.MoreRepeated") - proto.RegisterType((*GroupOld)(nil), "test_proto.GroupOld") - proto.RegisterType((*GroupOld_G)(nil), "test_proto.GroupOld.G") - proto.RegisterType((*GroupNew)(nil), "test_proto.GroupNew") - proto.RegisterType((*GroupNew_G)(nil), "test_proto.GroupNew.G") - proto.RegisterType((*FloatingPoint)(nil), "test_proto.FloatingPoint") - proto.RegisterType((*MessageWithMap)(nil), "test_proto.MessageWithMap") - proto.RegisterMapType((map[bool][]byte)(nil), "test_proto.MessageWithMap.ByteMappingEntry") - proto.RegisterMapType((map[int64]*FloatingPoint)(nil), "test_proto.MessageWithMap.MsgMappingEntry") - proto.RegisterMapType((map[int32]string)(nil), "test_proto.MessageWithMap.NameMappingEntry") - proto.RegisterMapType((map[string]string)(nil), "test_proto.MessageWithMap.StrToStrEntry") - proto.RegisterType((*Oneof)(nil), "test_proto.Oneof") - proto.RegisterType((*Oneof_F_Group)(nil), "test_proto.Oneof.F_Group") - proto.RegisterType((*Communique)(nil), "test_proto.Communique") - proto.RegisterEnum("test_proto.FOO", FOO_name, FOO_value) - proto.RegisterEnum("test_proto.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) - proto.RegisterEnum("test_proto.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) - proto.RegisterEnum("test_proto.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) - proto.RegisterEnum("test_proto.Defaults_Color", Defaults_Color_name, Defaults_Color_value) - proto.RegisterEnum("test_proto.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) - proto.RegisterExtension(E_Ext_More) - proto.RegisterExtension(E_Ext_Text) - proto.RegisterExtension(E_Ext_Number) - proto.RegisterExtension(E_Greeting) - proto.RegisterExtension(E_Complex) - proto.RegisterExtension(E_RComplex) - proto.RegisterExtension(E_NoDefaultDouble) - proto.RegisterExtension(E_NoDefaultFloat) - proto.RegisterExtension(E_NoDefaultInt32) - proto.RegisterExtension(E_NoDefaultInt64) - proto.RegisterExtension(E_NoDefaultUint32) - proto.RegisterExtension(E_NoDefaultUint64) - proto.RegisterExtension(E_NoDefaultSint32) - proto.RegisterExtension(E_NoDefaultSint64) - proto.RegisterExtension(E_NoDefaultFixed32) - proto.RegisterExtension(E_NoDefaultFixed64) - proto.RegisterExtension(E_NoDefaultSfixed32) - proto.RegisterExtension(E_NoDefaultSfixed64) - proto.RegisterExtension(E_NoDefaultBool) - proto.RegisterExtension(E_NoDefaultString) - proto.RegisterExtension(E_NoDefaultBytes) - proto.RegisterExtension(E_NoDefaultEnum) - proto.RegisterExtension(E_DefaultDouble) - proto.RegisterExtension(E_DefaultFloat) - proto.RegisterExtension(E_DefaultInt32) - proto.RegisterExtension(E_DefaultInt64) - proto.RegisterExtension(E_DefaultUint32) - proto.RegisterExtension(E_DefaultUint64) - proto.RegisterExtension(E_DefaultSint32) - proto.RegisterExtension(E_DefaultSint64) - proto.RegisterExtension(E_DefaultFixed32) - proto.RegisterExtension(E_DefaultFixed64) - proto.RegisterExtension(E_DefaultSfixed32) - proto.RegisterExtension(E_DefaultSfixed64) - proto.RegisterExtension(E_DefaultBool) - proto.RegisterExtension(E_DefaultString) - proto.RegisterExtension(E_DefaultBytes) - proto.RegisterExtension(E_DefaultEnum) - proto.RegisterExtension(E_X201) - proto.RegisterExtension(E_X202) - proto.RegisterExtension(E_X203) - proto.RegisterExtension(E_X204) - proto.RegisterExtension(E_X205) - proto.RegisterExtension(E_X206) - proto.RegisterExtension(E_X207) - proto.RegisterExtension(E_X208) - proto.RegisterExtension(E_X209) - proto.RegisterExtension(E_X210) - proto.RegisterExtension(E_X211) - proto.RegisterExtension(E_X212) - proto.RegisterExtension(E_X213) - proto.RegisterExtension(E_X214) - proto.RegisterExtension(E_X215) - proto.RegisterExtension(E_X216) - proto.RegisterExtension(E_X217) - proto.RegisterExtension(E_X218) - proto.RegisterExtension(E_X219) - proto.RegisterExtension(E_X220) - proto.RegisterExtension(E_X221) - proto.RegisterExtension(E_X222) - proto.RegisterExtension(E_X223) - proto.RegisterExtension(E_X224) - proto.RegisterExtension(E_X225) - proto.RegisterExtension(E_X226) - proto.RegisterExtension(E_X227) - proto.RegisterExtension(E_X228) - proto.RegisterExtension(E_X229) - proto.RegisterExtension(E_X230) - proto.RegisterExtension(E_X231) - proto.RegisterExtension(E_X232) - proto.RegisterExtension(E_X233) - proto.RegisterExtension(E_X234) - proto.RegisterExtension(E_X235) - proto.RegisterExtension(E_X236) - proto.RegisterExtension(E_X237) - proto.RegisterExtension(E_X238) - proto.RegisterExtension(E_X239) - proto.RegisterExtension(E_X240) - proto.RegisterExtension(E_X241) - proto.RegisterExtension(E_X242) - proto.RegisterExtension(E_X243) - proto.RegisterExtension(E_X244) - proto.RegisterExtension(E_X245) - proto.RegisterExtension(E_X246) - proto.RegisterExtension(E_X247) - proto.RegisterExtension(E_X248) - proto.RegisterExtension(E_X249) - proto.RegisterExtension(E_X250) -} - -func init() { proto.RegisterFile("test_proto/test.proto", fileDescriptor_test_74787bfc6550f8a7) } - -var fileDescriptor_test_74787bfc6550f8a7 = []byte{ - // 4680 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5b, 0xd9, 0x73, 0x1b, 0x47, - 0x7a, 0xd7, 0x0c, 0xee, 0x0f, 0x20, 0x31, 0x6c, 0xd1, 0x12, 0x44, 0x59, 0xd2, 0x08, 0x6b, 0xaf, - 0x61, 0xc9, 0xa2, 0x48, 0x60, 0x08, 0x49, 0x70, 0xec, 0xb2, 0x0e, 0x82, 0x62, 0x49, 0x24, 0xe4, - 0x21, 0x6d, 0x67, 0x95, 0x07, 0x14, 0x48, 0x0c, 0x40, 0xac, 0x80, 0x19, 0x18, 0x18, 0x44, 0x64, - 0x52, 0xa9, 0xf2, 0x63, 0xaa, 0xf2, 0x94, 0x4d, 0x52, 0x95, 0xf7, 0xbc, 0xe4, 0x25, 0xd7, 0x43, - 0xf2, 0x37, 0xc4, 0xd7, 0x5e, 0xde, 0x2b, 0xc9, 0x26, 0x9b, 0xfb, 0xce, 0xe6, 0xde, 0x23, 0x2f, - 0x4e, 0xf5, 0xd7, 0x3d, 0x33, 0x3d, 0x03, 0xa8, 0x45, 0x3e, 0x71, 0xa6, 0xfb, 0xf7, 0xfd, 0xfa, - 0xfa, 0xf5, 0xf7, 0xf5, 0xd7, 0x18, 0xc2, 0x0b, 0xae, 0x35, 0x76, 0x9b, 0xc3, 0x91, 0xe3, 0x3a, - 0xd7, 0xe9, 0xe3, 0x32, 0x3e, 0x12, 0x08, 0x8a, 0x8b, 0x57, 0x21, 0xb9, 0xe1, 0xac, 0xdb, 0x93, - 0x01, 0xb9, 0x0c, 0xb1, 0x8e, 0xe3, 0x14, 0x14, 0x5d, 0x2d, 0xcd, 0x97, 0xf3, 0xcb, 0x01, 0x66, - 0xb9, 0xde, 0x68, 0x98, 0xb4, 0xae, 0x78, 0x03, 0xb2, 0x1b, 0xce, 0xae, 0x35, 0x76, 0xeb, 0x3d, - 0xab, 0xdf, 0x26, 0x8b, 0x90, 0x78, 0xd8, 0xda, 0xb3, 0xfa, 0x68, 0x93, 0x31, 0xd9, 0x0b, 0x21, - 0x10, 0xdf, 0x3d, 0x1a, 0x5a, 0x05, 0x15, 0x0b, 0xf1, 0xb9, 0xf8, 0x87, 0x45, 0xda, 0x0c, 0xb5, - 0x24, 0x57, 0x21, 0xfe, 0xa0, 0x67, 0xb7, 0x79, 0x3b, 0x67, 0xc5, 0x76, 0x18, 0x62, 0xf9, 0xc1, - 0xe6, 0xf6, 0x3d, 0x13, 0x41, 0xb4, 0x85, 0xdd, 0xd6, 0x5e, 0x9f, 0x92, 0x29, 0xb4, 0x05, 0x7c, - 0xa1, 0xa5, 0x8f, 0x5a, 0xa3, 0xd6, 0xa0, 0x10, 0xd3, 0x95, 0x52, 0xc2, 0x64, 0x2f, 0xe4, 0x0d, - 0x98, 0x33, 0xad, 0xf7, 0x27, 0xbd, 0x91, 0xd5, 0xc6, 0xee, 0x15, 0xe2, 0xba, 0x5a, 0xca, 0xce, - 0x6a, 0x01, 0xab, 0xcd, 0x30, 0x9a, 0x99, 0x0f, 0xad, 0x96, 0xeb, 0x99, 0x27, 0xf4, 0xd8, 0x73, - 0xcc, 0x05, 0x34, 0x35, 0x6f, 0x0c, 0xdd, 0x9e, 0x63, 0xb7, 0xfa, 0xcc, 0x3c, 0xa9, 0x2b, 0x52, - 0xf3, 0x10, 0x9a, 0x7c, 0x11, 0xf2, 0xf5, 0xe6, 0x1d, 0xc7, 0xe9, 0x37, 0x47, 0xbc, 0x57, 0x05, - 0xd0, 0xd5, 0x52, 0xda, 0x9c, 0xab, 0xd3, 0x52, 0xaf, 0xab, 0xa4, 0x04, 0x5a, 0xbd, 0xb9, 0x69, - 0xbb, 0x95, 0x72, 0x00, 0xcc, 0xea, 0x6a, 0x29, 0x61, 0xce, 0xd7, 0xb1, 0x78, 0x0a, 0x59, 0x35, - 0x02, 0x64, 0x4e, 0x57, 0x4b, 0x31, 0x86, 0xac, 0x1a, 0x3e, 0xf2, 0x35, 0x20, 0xf5, 0x66, 0xbd, - 0x77, 0x68, 0xb5, 0x45, 0xd6, 0x39, 0x5d, 0x2d, 0xa5, 0x4c, 0xad, 0xce, 0x2b, 0x66, 0xa0, 0x45, - 0xe6, 0x79, 0x5d, 0x2d, 0x25, 0x3d, 0xb4, 0xc0, 0x7d, 0x05, 0x16, 0xea, 0xcd, 0x77, 0x7a, 0xe1, - 0x0e, 0xe7, 0x75, 0xb5, 0x34, 0x67, 0xe6, 0xeb, 0xac, 0x7c, 0x1a, 0x2b, 0x12, 0x6b, 0xba, 0x5a, - 0x8a, 0x73, 0xac, 0xc0, 0x8b, 0xa3, 0xab, 0xf7, 0x9d, 0x96, 0x1b, 0x40, 0x17, 0x74, 0xb5, 0xa4, - 0x9a, 0xf3, 0x75, 0x2c, 0x0e, 0xb3, 0xde, 0x73, 0x26, 0x7b, 0x7d, 0x2b, 0x80, 0x12, 0x5d, 0x2d, - 0x29, 0x66, 0xbe, 0xce, 0xca, 0xc3, 0xd8, 0x1d, 0x77, 0xd4, 0xb3, 0xbb, 0x01, 0xf6, 0x34, 0xea, - 0x38, 0x5f, 0x67, 0xe5, 0xe1, 0x1e, 0xdc, 0x39, 0x72, 0xad, 0x71, 0x00, 0xb5, 0x74, 0xb5, 0x94, - 0x33, 0xe7, 0xeb, 0x58, 0x1c, 0x61, 0x8d, 0xcc, 0x41, 0x47, 0x57, 0x4b, 0x0b, 0x94, 0x75, 0xc6, - 0x1c, 0xec, 0x44, 0xe6, 0xa0, 0xab, 0xab, 0x25, 0xc2, 0xb1, 0xc2, 0x1c, 0x2c, 0xc3, 0xe9, 0x7a, - 0x73, 0xa7, 0x13, 0x5d, 0xb8, 0x03, 0x5d, 0x2d, 0xe5, 0xcd, 0x85, 0xba, 0x57, 0x33, 0x0b, 0x2f, - 0xb2, 0xf7, 0x74, 0xb5, 0xa4, 0xf9, 0x78, 0x81, 0x5f, 0xd4, 0x24, 0x93, 0x7a, 0x61, 0x51, 0x8f, - 0x09, 0x9a, 0x64, 0x85, 0x61, 0x4d, 0x72, 0xe0, 0x0b, 0x7a, 0x4c, 0xd4, 0x64, 0x04, 0x89, 0xcd, - 0x73, 0xe4, 0x19, 0x3d, 0x26, 0x6a, 0x92, 0x23, 0x23, 0x9a, 0xe4, 0xd8, 0xb3, 0x7a, 0x2c, 0xac, - 0xc9, 0x29, 0xb4, 0xc8, 0x5c, 0xd0, 0x63, 0x61, 0x4d, 0x72, 0x74, 0x58, 0x93, 0x1c, 0x7c, 0x4e, - 0x8f, 0x85, 0x34, 0x19, 0xc5, 0x8a, 0xc4, 0x4b, 0x7a, 0x2c, 0xa4, 0x49, 0x71, 0x74, 0x9e, 0x26, - 0x39, 0xf4, 0xbc, 0x1e, 0x13, 0x35, 0x29, 0xb2, 0xfa, 0x9a, 0xe4, 0xd0, 0x17, 0xf5, 0x58, 0x48, - 0x93, 0x22, 0xd6, 0xd7, 0x24, 0xc7, 0x5e, 0xd0, 0x63, 0x21, 0x4d, 0x72, 0xec, 0xab, 0xa2, 0x26, - 0x39, 0xf4, 0x43, 0x45, 0x8f, 0x89, 0xa2, 0xe4, 0xd0, 0xab, 0x21, 0x51, 0x72, 0xec, 0x47, 0x14, - 0x2b, 0xaa, 0x32, 0x0a, 0x16, 0x67, 0xe1, 0x63, 0x0a, 0x16, 0x65, 0xc9, 0xc1, 0xd7, 0x23, 0xb2, - 0xe4, 0xf0, 0x4f, 0x28, 0x3c, 0xac, 0xcb, 0x69, 0x03, 0x91, 0xff, 0x53, 0x6a, 0x10, 0x16, 0x26, - 0x37, 0x08, 0x84, 0xe9, 0x70, 0x27, 0x5a, 0xb8, 0xa8, 0x2b, 0xbe, 0x30, 0x3d, 0xcf, 0x2a, 0x0a, - 0xd3, 0x07, 0x5e, 0xc2, 0x90, 0xc1, 0x85, 0x39, 0x85, 0xac, 0x1a, 0x01, 0x52, 0xd7, 0x95, 0x40, - 0x98, 0x3e, 0x32, 0x24, 0x4c, 0x1f, 0x7b, 0x59, 0x57, 0x44, 0x61, 0xce, 0x40, 0x8b, 0xcc, 0x45, - 0x5d, 0x11, 0x85, 0xe9, 0xa3, 0x45, 0x61, 0xfa, 0xe0, 0x2f, 0xe8, 0x8a, 0x20, 0xcc, 0x69, 0xac, - 0x48, 0xfc, 0x92, 0xae, 0x08, 0xc2, 0x0c, 0x8f, 0x8e, 0x09, 0xd3, 0x87, 0xbe, 0xac, 0x2b, 0x81, - 0x30, 0xc3, 0xac, 0x5c, 0x98, 0x3e, 0xf4, 0x8b, 0xba, 0x22, 0x08, 0x33, 0x8c, 0xe5, 0xc2, 0xf4, - 0xb1, 0xaf, 0x60, 0x9c, 0xf6, 0x84, 0xe9, 0x63, 0x05, 0x61, 0xfa, 0xd0, 0xdf, 0xa1, 0x31, 0xdd, - 0x17, 0xa6, 0x0f, 0x15, 0x85, 0xe9, 0x63, 0x7f, 0x97, 0x62, 0x03, 0x61, 0x4e, 0x83, 0xc5, 0x59, - 0xf8, 0x3d, 0x0a, 0x0e, 0x84, 0xe9, 0x83, 0xc3, 0xc2, 0xf4, 0xe1, 0xbf, 0x4f, 0xe1, 0xa2, 0x30, - 0x67, 0x19, 0x88, 0xfc, 0x7f, 0x40, 0x0d, 0x44, 0x61, 0xfa, 0x06, 0xcb, 0x38, 0x4c, 0x2a, 0xcc, - 0xb6, 0xd5, 0x69, 0x4d, 0xfa, 0x54, 0xc6, 0x25, 0xaa, 0xcc, 0x5a, 0xdc, 0x1d, 0x4d, 0x2c, 0x3a, - 0x56, 0xc7, 0xe9, 0xdf, 0xf3, 0xea, 0xc8, 0x32, 0xed, 0x3e, 0x13, 0x68, 0x60, 0xf0, 0x2a, 0x55, - 0x68, 0x4d, 0xad, 0x94, 0xcd, 0x3c, 0x53, 0xe9, 0x34, 0xbe, 0x6a, 0x08, 0xf8, 0x2b, 0x54, 0xa7, - 0x35, 0xb5, 0x6a, 0x30, 0x7c, 0xd5, 0x08, 0xf0, 0x15, 0x3a, 0x00, 0x4f, 0xac, 0x81, 0xc5, 0x55, - 0xaa, 0xd6, 0x5a, 0xac, 0x52, 0x5e, 0x31, 0x17, 0x3c, 0xc9, 0xce, 0x32, 0x0a, 0x35, 0xf3, 0x1a, - 0x15, 0x6d, 0x2d, 0x56, 0x35, 0x7c, 0x23, 0xb1, 0xa5, 0x32, 0x15, 0x3a, 0x97, 0x6e, 0x60, 0x73, - 0x8d, 0x6a, 0xb7, 0x16, 0xaf, 0x94, 0x57, 0x56, 0x4c, 0x8d, 0x2b, 0x78, 0x86, 0x4d, 0xa8, 0x9d, - 0x65, 0xaa, 0xe1, 0x5a, 0xbc, 0x6a, 0xf8, 0x36, 0xe1, 0x76, 0x16, 0x3c, 0x29, 0x07, 0x26, 0xd7, - 0xa9, 0x96, 0x6b, 0xc9, 0xca, 0xaa, 0xb1, 0xba, 0x76, 0xcb, 0xcc, 0x33, 0x4d, 0x07, 0x36, 0x06, - 0x6d, 0x87, 0x8b, 0x3a, 0x30, 0x5a, 0xa1, 0xaa, 0xae, 0x25, 0xcb, 0x37, 0x56, 0x6f, 0x96, 0x6f, - 0x9a, 0x1a, 0x57, 0x77, 0x60, 0xf5, 0x26, 0xb5, 0xe2, 0xf2, 0x0e, 0xac, 0x56, 0xa9, 0xbe, 0x6b, - 0xda, 0x81, 0xd5, 0xef, 0x3b, 0xaf, 0xe9, 0xc5, 0xa7, 0xce, 0xa8, 0xdf, 0xbe, 0x5c, 0x04, 0x53, - 0xe3, 0x8a, 0x17, 0x5b, 0x5d, 0xf0, 0x24, 0x1f, 0x98, 0xff, 0x2a, 0x3d, 0xb1, 0xe6, 0x6a, 0xa9, - 0x3b, 0xbd, 0xae, 0xed, 0x8c, 0x2d, 0x33, 0xcf, 0xc4, 0x1f, 0x99, 0x93, 0x9d, 0xe8, 0x3c, 0x7e, - 0x85, 0x9a, 0x2d, 0xd4, 0x62, 0xd7, 0x2a, 0x65, 0xda, 0xd2, 0xac, 0x79, 0xdc, 0x89, 0xce, 0xe3, - 0xaf, 0x51, 0x1b, 0x52, 0x8b, 0x5d, 0xab, 0x1a, 0xdc, 0x46, 0x9c, 0xc7, 0x2a, 0x2c, 0x0a, 0x7b, - 0x21, 0xb0, 0xfa, 0x75, 0x6a, 0x95, 0x67, 0x2d, 0x11, 0x7f, 0x47, 0xcc, 0xb4, 0x0b, 0xb5, 0xf6, - 0x1b, 0xd4, 0x4e, 0x63, 0xad, 0x11, 0x7f, 0x63, 0x04, 0x76, 0x37, 0xe0, 0x4c, 0xe4, 0x2c, 0xd1, - 0x1c, 0xb6, 0xf6, 0x9f, 0x58, 0xed, 0x42, 0x99, 0x1e, 0x29, 0xee, 0xa8, 0x9a, 0x62, 0x9e, 0x0e, - 0x1d, 0x2b, 0x1e, 0x61, 0x35, 0xb9, 0x05, 0x67, 0xa3, 0x87, 0x0b, 0xcf, 0xb2, 0x42, 0xcf, 0x18, - 0x68, 0xb9, 0x18, 0x3e, 0x67, 0x44, 0x4c, 0x85, 0xa0, 0xe2, 0x99, 0x1a, 0xf4, 0xd0, 0x11, 0x98, - 0x06, 0xb1, 0x85, 0x9b, 0xbe, 0x01, 0xe7, 0xa6, 0x8f, 0x1f, 0x9e, 0xf1, 0x1a, 0x3d, 0x85, 0xa0, - 0xf1, 0x99, 0xe8, 0x49, 0x64, 0xca, 0x7c, 0x46, 0xdb, 0x55, 0x7a, 0x2c, 0x11, 0xcd, 0xa7, 0x5a, - 0x7f, 0x1d, 0x0a, 0x53, 0x07, 0x14, 0xcf, 0xfa, 0x06, 0x3d, 0xa7, 0xa0, 0xf5, 0x0b, 0x91, 0xb3, - 0x4a, 0xd4, 0x78, 0x46, 0xd3, 0x37, 0xe9, 0xc1, 0x45, 0x30, 0x9e, 0x6a, 0x19, 0xa7, 0x2c, 0x7c, - 0x84, 0xf1, 0x6c, 0x6f, 0xd1, 0x93, 0x0c, 0x9f, 0xb2, 0xd0, 0x69, 0x46, 0x6c, 0x37, 0x72, 0xa6, - 0xf1, 0x6c, 0x6b, 0xf4, 0x68, 0xc3, 0xdb, 0x0d, 0x1f, 0x6f, 0xb8, 0xf1, 0xcf, 0x50, 0xe3, 0x9d, - 0xd9, 0x23, 0xfe, 0x51, 0x8c, 0x1e, 0x4a, 0xb8, 0xf5, 0xce, 0xac, 0x21, 0xfb, 0xd6, 0x33, 0x86, - 0xfc, 0x63, 0x6a, 0x4d, 0x04, 0xeb, 0xa9, 0x31, 0xbf, 0x05, 0x4b, 0x33, 0xce, 0x2b, 0x9e, 0xfd, - 0x4f, 0xa8, 0x7d, 0x1e, 0xed, 0xcf, 0x4e, 0x1d, 0x5d, 0xa6, 0x19, 0x66, 0xf4, 0xe0, 0xa7, 0x94, - 0x41, 0x0b, 0x31, 0x4c, 0xf5, 0xa1, 0x0e, 0x73, 0xde, 0x79, 0xbc, 0x3b, 0x72, 0x26, 0xc3, 0x42, - 0x5d, 0x57, 0x4b, 0x50, 0xd6, 0x67, 0x64, 0xc7, 0xde, 0xf1, 0x7c, 0x83, 0xe2, 0xcc, 0xb0, 0x19, - 0xe3, 0x61, 0xcc, 0x8c, 0xe7, 0x91, 0x1e, 0x7b, 0x26, 0x0f, 0xc3, 0xf9, 0x3c, 0x82, 0x19, 0xe5, - 0xf1, 0xc2, 0x1d, 0xe3, 0x79, 0xac, 0x2b, 0xcf, 0xe0, 0xf1, 0x82, 0x1f, 0xe7, 0x09, 0x99, 0x2d, - 0xad, 0x05, 0x39, 0x39, 0xd6, 0x93, 0x97, 0xa2, 0x49, 0xfa, 0x06, 0x66, 0x57, 0xe1, 0x42, 0x66, - 0x26, 0x74, 0x6f, 0xda, 0xec, 0xed, 0x67, 0x98, 0x85, 0x7a, 0x33, 0x6d, 0xf6, 0x73, 0x33, 0xcc, - 0x8a, 0xbf, 0xa9, 0x40, 0xfc, 0xc1, 0xe6, 0xf6, 0x3d, 0x92, 0x86, 0xf8, 0xbb, 0x8d, 0xcd, 0x7b, - 0xda, 0x29, 0xfa, 0x74, 0xa7, 0xd1, 0x78, 0xa8, 0x29, 0x24, 0x03, 0x89, 0x3b, 0x5f, 0xda, 0x5d, - 0xdf, 0xd1, 0x54, 0x92, 0x87, 0x6c, 0x7d, 0x73, 0x7b, 0x63, 0xdd, 0x7c, 0x64, 0x6e, 0x6e, 0xef, - 0x6a, 0x31, 0x5a, 0x57, 0x7f, 0xd8, 0xb8, 0xbd, 0xab, 0xc5, 0x49, 0x0a, 0x62, 0xb4, 0x2c, 0x41, - 0x00, 0x92, 0x3b, 0xbb, 0xe6, 0xe6, 0xf6, 0x86, 0x96, 0xa4, 0x2c, 0xbb, 0x9b, 0x5b, 0xeb, 0x5a, - 0x8a, 0x22, 0x77, 0xdf, 0x79, 0xf4, 0x70, 0x5d, 0x4b, 0xd3, 0xc7, 0xdb, 0xa6, 0x79, 0xfb, 0x4b, - 0x5a, 0x86, 0x1a, 0x6d, 0xdd, 0x7e, 0xa4, 0x01, 0x56, 0xdf, 0xbe, 0xf3, 0x70, 0x5d, 0xcb, 0x92, - 0x1c, 0xa4, 0xeb, 0xef, 0x6c, 0xdf, 0xdd, 0xdd, 0x6c, 0x6c, 0x6b, 0xb9, 0xe2, 0x2f, 0x42, 0x81, - 0x4d, 0x73, 0x68, 0x16, 0xd9, 0x95, 0xc1, 0x5b, 0x90, 0x60, 0x6b, 0xa3, 0xa0, 0x56, 0xae, 0x4c, - 0xaf, 0xcd, 0xb4, 0xd1, 0x32, 0x5b, 0x25, 0x66, 0xb8, 0x74, 0x01, 0x12, 0x6c, 0x9e, 0x16, 0x21, - 0xc1, 0xe6, 0x47, 0xc5, 0xab, 0x04, 0xf6, 0x52, 0xfc, 0x2d, 0x15, 0x60, 0xc3, 0xd9, 0x79, 0xd2, - 0x1b, 0xe2, 0xc5, 0xcd, 0x05, 0x80, 0xf1, 0x93, 0xde, 0xb0, 0x89, 0x3b, 0x90, 0x5f, 0x3a, 0x64, - 0x68, 0x09, 0xfa, 0x5e, 0x72, 0x19, 0x72, 0x58, 0xcd, 0xb7, 0x08, 0xde, 0x35, 0xa4, 0xcc, 0x2c, - 0x2d, 0xe3, 0x4e, 0x32, 0x0c, 0xa9, 0x1a, 0x78, 0xc5, 0x90, 0x14, 0x20, 0x55, 0x83, 0x5c, 0x02, - 0x7c, 0x6d, 0x8e, 0x31, 0x9a, 0xe2, 0xb5, 0x42, 0xc6, 0xc4, 0x76, 0x59, 0x7c, 0x25, 0x6f, 0x02, - 0xb6, 0xc9, 0x46, 0x9e, 0x9f, 0xb5, 0x4b, 0xbc, 0x0e, 0x2f, 0xd3, 0x07, 0x36, 0xde, 0xc0, 0x64, - 0xa9, 0x01, 0x19, 0xbf, 0x9c, 0xb6, 0x86, 0xa5, 0x7c, 0x4c, 0x1a, 0x8e, 0x09, 0xb0, 0xc8, 0x1f, - 0x14, 0x03, 0xf0, 0xfe, 0x2c, 0x60, 0x7f, 0x98, 0x11, 0xeb, 0x50, 0xf1, 0x02, 0xcc, 0x6d, 0x3b, - 0x36, 0xdb, 0xc7, 0x38, 0x4f, 0x39, 0x50, 0x5a, 0x05, 0x05, 0xf3, 0x5f, 0xa5, 0x55, 0xbc, 0x08, - 0x20, 0xd4, 0x69, 0xa0, 0xec, 0xb1, 0x3a, 0xf4, 0x07, 0xca, 0x5e, 0xf1, 0x2a, 0x24, 0xb7, 0x5a, - 0x87, 0xbb, 0xad, 0x2e, 0xb9, 0x0c, 0xd0, 0x6f, 0x8d, 0xdd, 0x66, 0x07, 0x57, 0xe2, 0xf3, 0xcf, - 0x3f, 0xff, 0x5c, 0xc1, 0xc3, 0x74, 0x86, 0x96, 0xb2, 0x15, 0x19, 0x03, 0x34, 0xfa, 0xed, 0x2d, - 0x6b, 0x3c, 0x6e, 0x75, 0x2d, 0xb2, 0x06, 0x49, 0xdb, 0x1a, 0xd3, 0xe8, 0xab, 0xe0, 0x5d, 0xd3, - 0x05, 0x71, 0x1e, 0x02, 0xdc, 0xf2, 0x36, 0x82, 0x4c, 0x0e, 0x26, 0x1a, 0xc4, 0xec, 0xc9, 0x00, - 0x6f, 0xd4, 0x12, 0x26, 0x7d, 0x5c, 0x7a, 0x11, 0x92, 0x0c, 0x43, 0x08, 0xc4, 0xed, 0xd6, 0xc0, - 0x2a, 0xb0, 0x96, 0xf1, 0xb9, 0xf8, 0x15, 0x05, 0x60, 0xdb, 0x7a, 0x7a, 0xac, 0x56, 0x03, 0x9c, - 0xa4, 0xd5, 0x18, 0x6b, 0xf5, 0x75, 0x59, 0xab, 0x54, 0x6d, 0x1d, 0xc7, 0x69, 0x37, 0xd9, 0x42, - 0xb3, 0xeb, 0xbf, 0x0c, 0x2d, 0xc1, 0x95, 0x2b, 0x3e, 0x86, 0xdc, 0xa6, 0x6d, 0x5b, 0x23, 0xaf, - 0x57, 0x04, 0xe2, 0x07, 0xce, 0xd8, 0xe5, 0x37, 0x91, 0xf8, 0x4c, 0x0a, 0x10, 0x1f, 0x3a, 0x23, - 0x97, 0x8d, 0xb4, 0x16, 0x37, 0x56, 0x56, 0x56, 0x4c, 0x2c, 0x21, 0x2f, 0x42, 0x66, 0xdf, 0xb1, - 0x6d, 0x6b, 0x9f, 0x0e, 0x23, 0x86, 0xa9, 0x63, 0x50, 0x50, 0xfc, 0x65, 0x05, 0x72, 0x0d, 0xf7, - 0x20, 0x20, 0xd7, 0x20, 0xf6, 0xc4, 0x3a, 0xc2, 0xee, 0xc5, 0x4c, 0xfa, 0x48, 0x37, 0xcc, 0xcf, - 0xb7, 0xfa, 0x13, 0x76, 0x2f, 0x99, 0x33, 0xd9, 0x0b, 0x39, 0x03, 0xc9, 0xa7, 0x56, 0xaf, 0x7b, - 0xe0, 0x22, 0xa7, 0x6a, 0xf2, 0x37, 0xb2, 0x0c, 0x89, 0x1e, 0xed, 0x6c, 0x21, 0x8e, 0x33, 0x56, - 0x10, 0x67, 0x4c, 0x1c, 0x85, 0xc9, 0x60, 0x57, 0xd2, 0xe9, 0xb6, 0xf6, 0xc1, 0x07, 0x1f, 0x7c, - 0xa0, 0x16, 0x0f, 0x60, 0xd1, 0xdb, 0xc4, 0xa1, 0xe1, 0x3e, 0x82, 0x42, 0xdf, 0x72, 0x9a, 0x9d, - 0x9e, 0xdd, 0xea, 0xf7, 0x8f, 0x9a, 0x4f, 0x1d, 0xbb, 0xd9, 0xb2, 0x9b, 0xce, 0x78, 0xbf, 0x35, - 0xc2, 0x29, 0x90, 0x35, 0xb2, 0xd8, 0xb7, 0x9c, 0x3a, 0x33, 0x7c, 0xcf, 0xb1, 0x6f, 0xdb, 0x0d, - 0x6a, 0x55, 0xfc, 0x2c, 0x0e, 0x99, 0xad, 0x23, 0x8f, 0x7f, 0x11, 0x12, 0xfb, 0xce, 0xc4, 0x66, - 0xf3, 0x99, 0x30, 0xd9, 0x8b, 0xbf, 0x4e, 0xaa, 0xb0, 0x4e, 0x8b, 0x90, 0x78, 0x7f, 0xe2, 0xb8, - 0x16, 0x0e, 0x39, 0x63, 0xb2, 0x17, 0x3a, 0x63, 0x43, 0xcb, 0x2d, 0xc4, 0xf1, 0x9a, 0x82, 0x3e, - 0x06, 0x73, 0x90, 0x38, 0xd6, 0x1c, 0x90, 0x15, 0x48, 0x3a, 0x74, 0x0d, 0xc6, 0x85, 0x24, 0xde, - 0xc3, 0x86, 0x0c, 0xc4, 0xd5, 0x31, 0x39, 0x8e, 0x3c, 0x80, 0x85, 0xa7, 0x56, 0x73, 0x30, 0x19, - 0xbb, 0xcd, 0xae, 0xd3, 0x6c, 0x5b, 0xd6, 0xd0, 0x1a, 0x15, 0xe6, 0xb0, 0xb5, 0x90, 0x87, 0x98, - 0x35, 0xa1, 0xe6, 0xfc, 0x53, 0x6b, 0x6b, 0x32, 0x76, 0x37, 0x9c, 0x7b, 0x68, 0x47, 0xd6, 0x20, - 0x33, 0xb2, 0xa8, 0x5f, 0xa0, 0x5d, 0xce, 0x4d, 0xf7, 0x20, 0x64, 0x9c, 0x1e, 0x59, 0x43, 0x2c, - 0x20, 0x37, 0x20, 0xbd, 0xd7, 0x7b, 0x62, 0x8d, 0x0f, 0xac, 0x76, 0x21, 0xa5, 0x2b, 0xa5, 0xf9, - 0xf2, 0x79, 0xd1, 0xca, 0x9f, 0xe0, 0xe5, 0xbb, 0x4e, 0xdf, 0x19, 0x99, 0x3e, 0x98, 0xbc, 0x01, - 0x99, 0xb1, 0x33, 0xb0, 0x98, 0xda, 0xd3, 0x18, 0x6c, 0x2f, 0xcd, 0xb6, 0xdc, 0x71, 0x06, 0x96, - 0xe7, 0xd5, 0x3c, 0x0b, 0x72, 0x9e, 0x75, 0x77, 0x8f, 0x26, 0x13, 0x05, 0xc0, 0x0b, 0x1f, 0xda, - 0x29, 0x4c, 0x2e, 0xc8, 0x12, 0xed, 0x54, 0xb7, 0x43, 0xcf, 0x6c, 0x85, 0x2c, 0xe6, 0xf2, 0xfe, - 0xfb, 0xd2, 0x6b, 0x90, 0xf1, 0x09, 0x03, 0x77, 0xc8, 0x5c, 0x50, 0x06, 0x3d, 0x04, 0x73, 0x87, - 0xcc, 0xff, 0xbc, 0x0c, 0x09, 0xec, 0x38, 0x8d, 0x5c, 0xe6, 0x3a, 0x0d, 0x94, 0x19, 0x48, 0x6c, - 0x98, 0xeb, 0xeb, 0xdb, 0x9a, 0x82, 0x31, 0xf3, 0xe1, 0x3b, 0xeb, 0x9a, 0x2a, 0xe8, 0xf7, 0xb7, - 0x55, 0x88, 0xad, 0x1f, 0xa2, 0x72, 0xda, 0x2d, 0xb7, 0xe5, 0xed, 0x70, 0xfa, 0x4c, 0x6a, 0x90, - 0x19, 0xb4, 0xbc, 0xb6, 0x54, 0x9c, 0xe2, 0x90, 0x2f, 0x59, 0x3f, 0x74, 0x97, 0xb7, 0x5a, 0xac, - 0xe5, 0x75, 0xdb, 0x1d, 0x1d, 0x99, 0xe9, 0x01, 0x7f, 0x5d, 0x7a, 0x1d, 0xe6, 0x42, 0x55, 0xe2, - 0x16, 0x4d, 0xcc, 0xd8, 0xa2, 0x09, 0xbe, 0x45, 0x6b, 0xea, 0x4d, 0xa5, 0x5c, 0x83, 0xf8, 0xc0, - 0x19, 0x59, 0xe4, 0x85, 0x99, 0x13, 0x5c, 0xe8, 0xa2, 0x64, 0xf2, 0x91, 0xae, 0x98, 0x68, 0x53, - 0x7e, 0x15, 0xe2, 0xae, 0x75, 0xe8, 0x3e, 0xcb, 0xf6, 0x80, 0x8d, 0x8f, 0x42, 0xca, 0xd7, 0x20, - 0x69, 0x4f, 0x06, 0x7b, 0xd6, 0xe8, 0x59, 0xe0, 0x1e, 0x76, 0x8c, 0x83, 0x8a, 0xef, 0x82, 0x76, - 0xd7, 0x19, 0x0c, 0xfb, 0xd6, 0xe1, 0xfa, 0xa1, 0x6b, 0xd9, 0xe3, 0x9e, 0x63, 0xd3, 0x31, 0x74, - 0x7a, 0x23, 0x74, 0x6b, 0x38, 0x06, 0x7c, 0xa1, 0x6e, 0x66, 0x6c, 0xed, 0x3b, 0x76, 0x9b, 0x0f, - 0x8d, 0xbf, 0x51, 0xb4, 0x7b, 0xd0, 0x1b, 0x51, 0x8f, 0x46, 0x83, 0x0f, 0x7b, 0x29, 0x6e, 0x40, - 0x9e, 0xa7, 0x61, 0x63, 0xde, 0x70, 0xf1, 0x0a, 0xe4, 0xbc, 0x22, 0xfc, 0xe5, 0x27, 0x0d, 0xf1, - 0xc7, 0xeb, 0x66, 0x43, 0x3b, 0x45, 0xd7, 0xb5, 0xb1, 0xbd, 0xae, 0x29, 0xf4, 0x61, 0xf7, 0xbd, - 0x46, 0x68, 0x2d, 0x5f, 0x84, 0x9c, 0xdf, 0xf7, 0x1d, 0xcb, 0xc5, 0x1a, 0x1a, 0xa5, 0x52, 0x35, - 0x35, 0xad, 0x14, 0x53, 0x90, 0x58, 0x1f, 0x0c, 0xdd, 0xa3, 0xe2, 0x2f, 0x41, 0x96, 0x83, 0x1e, - 0xf6, 0xc6, 0x2e, 0xb9, 0x05, 0xa9, 0x01, 0x1f, 0xaf, 0x82, 0x67, 0xd1, 0xb0, 0xac, 0x03, 0xa4, - 0xf7, 0x6c, 0x7a, 0xf8, 0xa5, 0x0a, 0xa4, 0x04, 0xf7, 0xce, 0x3d, 0x8f, 0x2a, 0x7a, 0x1e, 0xe6, - 0xa3, 0x62, 0x82, 0x8f, 0x2a, 0x6e, 0x41, 0x8a, 0x05, 0xe6, 0x31, 0x1e, 0x37, 0x58, 0xfe, 0xce, - 0x34, 0xc6, 0xc4, 0x97, 0x65, 0x65, 0xec, 0x0c, 0x75, 0x09, 0xb2, 0xb8, 0x67, 0x7c, 0x15, 0x52, - 0x6f, 0x0e, 0x58, 0xc4, 0x14, 0xff, 0x47, 0x09, 0x48, 0x7b, 0x73, 0x45, 0xce, 0x43, 0x92, 0x25, - 0xb1, 0x48, 0xe5, 0x5d, 0xea, 0x24, 0x30, 0x6d, 0x25, 0xe7, 0x21, 0xc5, 0x13, 0x55, 0x1e, 0x70, - 0xd4, 0x4a, 0xd9, 0x4c, 0xb2, 0xc4, 0xd4, 0xaf, 0xac, 0x1a, 0xe8, 0x27, 0xd9, 0x75, 0x4d, 0x92, - 0xa5, 0x9e, 0x44, 0x87, 0x8c, 0x9f, 0x6c, 0x62, 0x88, 0xe0, 0x77, 0x33, 0x69, 0x2f, 0xbb, 0x14, - 0x10, 0x55, 0x03, 0x1d, 0x28, 0xbf, 0x88, 0x49, 0xd7, 0x83, 0x73, 0x53, 0xda, 0x4b, 0x19, 0xf1, - 0x97, 0x27, 0xef, 0xd6, 0x25, 0xc5, 0x93, 0xc4, 0x00, 0x50, 0x35, 0xd0, 0x33, 0x79, 0x57, 0x2c, - 0x29, 0x9e, 0x08, 0x92, 0x4b, 0xb4, 0x8b, 0x98, 0xd8, 0xa1, 0xff, 0x09, 0xee, 0x53, 0x92, 0x2c, - 0xdd, 0x23, 0x97, 0x29, 0x03, 0xcb, 0xde, 0xd0, 0x35, 0x04, 0x97, 0x27, 0x29, 0x9e, 0xd4, 0x91, - 0xab, 0x14, 0xc2, 0xa6, 0xbf, 0x00, 0xcf, 0xb8, 0x29, 0x49, 0xf1, 0x9b, 0x12, 0xa2, 0xd3, 0x06, - 0xd1, 0x43, 0xa1, 0x57, 0x12, 0x6e, 0x45, 0x92, 0xec, 0x56, 0x84, 0x5c, 0x44, 0x3a, 0x36, 0xa8, - 0x5c, 0x70, 0x03, 0x92, 0xe2, 0x59, 0x60, 0x50, 0x8f, 0x67, 0x49, 0xff, 0xb6, 0x23, 0xc5, 0xf3, - 0x3c, 0x72, 0x93, 0xae, 0x17, 0x55, 0x78, 0x61, 0x1e, 0x7d, 0xf1, 0x92, 0x28, 0x3d, 0x6f, 0x55, - 0x99, 0x2b, 0xae, 0x31, 0x37, 0x66, 0x26, 0xea, 0xb8, 0x23, 0x96, 0xa8, 0xe5, 0xa3, 0x9e, 0xdd, - 0x29, 0xe4, 0x71, 0x2e, 0x62, 0x3d, 0xbb, 0x63, 0x26, 0xea, 0xb4, 0x84, 0xa9, 0x60, 0x9b, 0xd6, - 0x69, 0x58, 0x17, 0xbf, 0xc6, 0x2a, 0x69, 0x11, 0x29, 0x40, 0xa2, 0xde, 0xdc, 0x6e, 0xd9, 0x85, - 0x05, 0x66, 0x67, 0xb7, 0x6c, 0x33, 0x5e, 0xdf, 0x6e, 0xd9, 0xe4, 0x55, 0x88, 0x8d, 0x27, 0x7b, - 0x05, 0x32, 0xfd, 0xb3, 0xe0, 0xce, 0x64, 0xcf, 0xeb, 0x8c, 0x49, 0x31, 0xe4, 0x3c, 0xa4, 0xc7, - 0xee, 0xa8, 0xf9, 0x0b, 0xd6, 0xc8, 0x29, 0x9c, 0xc6, 0x69, 0x3c, 0x65, 0xa6, 0xc6, 0xee, 0xe8, - 0xb1, 0x35, 0x72, 0x8e, 0xe9, 0x83, 0x8b, 0x17, 0x21, 0x2b, 0xf0, 0x92, 0x3c, 0x28, 0x36, 0x3b, - 0xc0, 0xd4, 0x94, 0x1b, 0xa6, 0x62, 0x17, 0xdf, 0x85, 0x9c, 0x97, 0x62, 0xe1, 0x88, 0x0d, 0xba, - 0x9b, 0xfa, 0xce, 0x08, 0x77, 0xe9, 0x7c, 0xf9, 0x62, 0x38, 0x62, 0x06, 0x40, 0x1e, 0xb9, 0x18, - 0xb8, 0xa8, 0x45, 0x3a, 0xa3, 0x14, 0x7f, 0xa0, 0x40, 0x6e, 0xcb, 0x19, 0x05, 0xbf, 0x5f, 0x2c, - 0x42, 0x62, 0xcf, 0x71, 0xfa, 0x63, 0x24, 0x4e, 0x9b, 0xec, 0x85, 0xbc, 0x0c, 0x39, 0x7c, 0xf0, - 0x92, 0x64, 0xd5, 0xbf, 0x05, 0xca, 0x62, 0x39, 0xcf, 0x8b, 0x09, 0xc4, 0x7b, 0xb6, 0x3b, 0xe6, - 0x1e, 0x0d, 0x9f, 0xc9, 0x17, 0x20, 0x4b, 0xff, 0x7a, 0x96, 0x71, 0xff, 0x34, 0x0d, 0xb4, 0x98, - 0x1b, 0xbe, 0x02, 0x73, 0xa8, 0x01, 0x1f, 0x96, 0xf2, 0x6f, 0x7c, 0x72, 0xac, 0x82, 0x03, 0x0b, - 0x90, 0x62, 0x0e, 0x61, 0x8c, 0x3f, 0xf8, 0x66, 0x4c, 0xef, 0x95, 0xba, 0x59, 0x4c, 0x54, 0xd8, - 0x09, 0x24, 0x65, 0xf2, 0xb7, 0xe2, 0x5d, 0x48, 0x63, 0xb8, 0x6c, 0xf4, 0xdb, 0xe4, 0x25, 0x50, - 0xba, 0x05, 0x0b, 0xc3, 0xf5, 0x99, 0x50, 0x16, 0xc2, 0x01, 0xcb, 0x1b, 0xa6, 0xd2, 0x5d, 0x5a, - 0x00, 0x65, 0x83, 0xa6, 0x05, 0x87, 0xdc, 0x61, 0x2b, 0x87, 0xc5, 0xb7, 0x39, 0xc9, 0xb6, 0xf5, - 0x54, 0x4e, 0xb2, 0x6d, 0x3d, 0x65, 0x24, 0x97, 0xa6, 0x48, 0xe8, 0xdb, 0x11, 0xff, 0x0d, 0x5c, - 0x39, 0x2a, 0x56, 0x60, 0x0e, 0x37, 0x6a, 0xcf, 0xee, 0x3e, 0x72, 0x7a, 0x36, 0x26, 0x22, 0x1d, - 0x3c, 0xc0, 0x29, 0xa6, 0xd2, 0xa1, 0xeb, 0x60, 0x1d, 0xb6, 0xf6, 0xd9, 0x71, 0x38, 0x6d, 0xb2, - 0x97, 0xe2, 0xf7, 0xe3, 0x30, 0xcf, 0x9d, 0xec, 0x7b, 0x3d, 0xf7, 0x60, 0xab, 0x35, 0x24, 0xdb, - 0x90, 0xa3, 0xfe, 0xb5, 0x39, 0x68, 0x0d, 0x87, 0x74, 0x23, 0x2b, 0x18, 0x9a, 0xaf, 0xce, 0x70, - 0xdb, 0xdc, 0x62, 0x79, 0xbb, 0x35, 0xb0, 0xb6, 0x18, 0x9a, 0x05, 0xea, 0xac, 0x1d, 0x94, 0x90, - 0x07, 0x90, 0x1d, 0x8c, 0xbb, 0x3e, 0x1d, 0x8b, 0xf4, 0x57, 0x24, 0x74, 0x5b, 0xe3, 0x6e, 0x88, - 0x0d, 0x06, 0x7e, 0x01, 0xed, 0x1c, 0xf5, 0xce, 0x3e, 0x5b, 0xec, 0xb9, 0x9d, 0xa3, 0xae, 0x24, - 0xdc, 0xb9, 0xbd, 0xa0, 0x84, 0xd4, 0x01, 0xe8, 0x56, 0x73, 0x1d, 0x9a, 0xe1, 0xa1, 0x96, 0xb2, - 0xe5, 0x92, 0x84, 0x6d, 0xc7, 0x1d, 0xed, 0x3a, 0x3b, 0xee, 0x88, 0x1f, 0x48, 0xc6, 0xfc, 0x75, - 0xe9, 0x4d, 0xd0, 0xa2, 0xb3, 0xf0, 0xbc, 0x33, 0x49, 0x46, 0x38, 0x93, 0x2c, 0xfd, 0x2c, 0xe4, - 0x23, 0xc3, 0x16, 0xcd, 0x09, 0x33, 0xbf, 0x2e, 0x9a, 0x67, 0xcb, 0xe7, 0x42, 0xdf, 0x68, 0x88, - 0x4b, 0x2f, 0x32, 0xbf, 0x09, 0x5a, 0x74, 0x0a, 0x44, 0xea, 0xb4, 0x24, 0xa1, 0x41, 0xfb, 0xd7, - 0x61, 0x2e, 0x34, 0x68, 0xd1, 0x38, 0xf3, 0x9c, 0x61, 0x15, 0x7f, 0x25, 0x01, 0x89, 0x86, 0x6d, - 0x39, 0x1d, 0x72, 0x36, 0x1c, 0x3b, 0xef, 0x9f, 0xf2, 0xe2, 0xe6, 0xb9, 0x48, 0xdc, 0xbc, 0x7f, - 0xca, 0x8f, 0x9a, 0xe7, 0x22, 0x51, 0xd3, 0xab, 0xaa, 0x1a, 0xe4, 0xc2, 0x54, 0xcc, 0xbc, 0x7f, - 0x4a, 0x08, 0x98, 0x17, 0xa6, 0x02, 0x66, 0x50, 0x5d, 0x35, 0xa8, 0x83, 0x0d, 0x47, 0xcb, 0xfb, - 0xa7, 0x82, 0x48, 0x79, 0x3e, 0x1a, 0x29, 0xfd, 0xca, 0xaa, 0xc1, 0xba, 0x24, 0x44, 0x49, 0xec, - 0x12, 0x8b, 0x8f, 0xe7, 0xa3, 0xf1, 0x11, 0xed, 0x78, 0x64, 0x3c, 0x1f, 0x8d, 0x8c, 0x58, 0xc9, - 0x23, 0xe1, 0xb9, 0x48, 0x24, 0x44, 0x52, 0x16, 0x02, 0xcf, 0x47, 0x43, 0x20, 0xb3, 0x13, 0x7a, - 0x2a, 0xc6, 0x3f, 0xbf, 0xb2, 0x6a, 0x10, 0x23, 0x12, 0xfc, 0x64, 0x89, 0x08, 0xae, 0x06, 0x86, - 0x81, 0x2a, 0x9d, 0x38, 0xef, 0x80, 0x9a, 0x97, 0x7e, 0xc2, 0x82, 0x33, 0xea, 0x1d, 0xd0, 0x0c, - 0x48, 0x75, 0x78, 0xae, 0xae, 0xa1, 0x27, 0x0b, 0x89, 0x13, 0x25, 0xb0, 0x5c, 0x6f, 0xa2, 0x47, - 0xa3, 0xa3, 0xeb, 0xb0, 0x84, 0xa3, 0x04, 0x73, 0xf5, 0xe6, 0xc3, 0xd6, 0xa8, 0x4b, 0xa1, 0xbb, - 0xad, 0xae, 0x7f, 0xeb, 0x41, 0x55, 0x90, 0xad, 0xf3, 0x9a, 0xdd, 0x56, 0x97, 0x9c, 0xf1, 0x24, - 0xd6, 0xc6, 0x5a, 0x85, 0x8b, 0x6c, 0xe9, 0x2c, 0x9d, 0x3a, 0x46, 0x86, 0xbe, 0x71, 0x81, 0xfb, - 0xc6, 0x3b, 0x29, 0x48, 0x4c, 0xec, 0x9e, 0x63, 0xdf, 0xc9, 0x40, 0xca, 0x75, 0x46, 0x83, 0x96, - 0xeb, 0x14, 0x7f, 0xa8, 0x00, 0xdc, 0x75, 0x06, 0x83, 0x89, 0xdd, 0x7b, 0x7f, 0x62, 0x91, 0x8b, - 0x90, 0x1d, 0xb4, 0x9e, 0x58, 0xcd, 0x81, 0xd5, 0xdc, 0x1f, 0x79, 0xbb, 0x21, 0x43, 0x8b, 0xb6, - 0xac, 0xbb, 0xa3, 0x23, 0x52, 0xf0, 0x0e, 0xf0, 0xa8, 0x20, 0x14, 0x26, 0x3f, 0xd0, 0x2f, 0xf2, - 0xe3, 0x68, 0x92, 0xaf, 0xa4, 0x77, 0x20, 0x65, 0x49, 0x4e, 0x8a, 0xaf, 0x21, 0x4b, 0x73, 0xce, - 0x42, 0xd2, 0xb5, 0x06, 0xc3, 0xe6, 0x3e, 0x0a, 0x86, 0x8a, 0x22, 0x41, 0xdf, 0xef, 0x92, 0xeb, - 0x10, 0xdb, 0x77, 0xfa, 0x28, 0x95, 0xe7, 0xae, 0x0e, 0x45, 0x92, 0x57, 0x20, 0x36, 0x18, 0x33, - 0xf9, 0x64, 0xcb, 0xa7, 0x43, 0x27, 0x08, 0x16, 0xb2, 0x28, 0x70, 0x30, 0xee, 0xfa, 0x63, 0xbf, - 0x92, 0x87, 0x58, 0xbd, 0xd1, 0xa0, 0xa7, 0x82, 0x7a, 0xa3, 0xb1, 0xaa, 0x29, 0xb5, 0x55, 0x48, - 0x77, 0x47, 0x96, 0x45, 0x1d, 0xc5, 0xb3, 0xb2, 0x92, 0x2f, 0x63, 0x14, 0xf4, 0x61, 0xb5, 0xb7, - 0x21, 0xb5, 0xcf, 0xf2, 0x12, 0xf2, 0xcc, 0x1c, 0xbc, 0xf0, 0xc7, 0xec, 0x2e, 0xe8, 0x45, 0x11, - 0x10, 0xcd, 0x66, 0x4c, 0x8f, 0xa7, 0xb6, 0x0b, 0x99, 0x51, 0xf3, 0xf9, 0xa4, 0x1f, 0xb2, 0xc8, - 0x23, 0x27, 0x4d, 0x8f, 0x78, 0x51, 0x6d, 0x03, 0x16, 0x6c, 0xc7, 0xfb, 0x49, 0xaa, 0xd9, 0xe6, - 0xfb, 0x6e, 0xd6, 0x91, 0xcf, 0x6b, 0xc0, 0x62, 0x3f, 0x6c, 0xdb, 0x0e, 0xaf, 0x60, 0x7b, 0xb5, - 0xb6, 0x0e, 0x9a, 0x40, 0xd4, 0x61, 0x9b, 0x5b, 0xc6, 0xd3, 0x61, 0xbf, 0xa5, 0xfb, 0x3c, 0xe8, - 0x0f, 0x22, 0x34, 0x7c, 0xc7, 0xca, 0x68, 0xba, 0xec, 0xd3, 0x04, 0x9f, 0x06, 0x9d, 0xe0, 0x34, - 0x0d, 0xf5, 0x5f, 0x32, 0x9a, 0x03, 0xf6, 0xdd, 0x82, 0x48, 0x53, 0x35, 0x22, 0xb3, 0x33, 0x39, - 0x46, 0x77, 0x7a, 0xec, 0xc3, 0x03, 0x9f, 0x87, 0xb9, 0xc7, 0x19, 0x44, 0xcf, 0xeb, 0xd0, 0x97, - 0xd9, 0x57, 0x09, 0x21, 0xa2, 0xa9, 0x1e, 0x8d, 0x8f, 0xd1, 0xa3, 0x27, 0xec, 0x23, 0x00, 0x9f, - 0x68, 0x67, 0x56, 0x8f, 0xc6, 0xc7, 0xe8, 0x51, 0x9f, 0x7d, 0x20, 0x10, 0x22, 0xaa, 0x1a, 0xb5, - 0x4d, 0x20, 0xe2, 0xc2, 0xf3, 0x58, 0x22, 0x65, 0x1a, 0xb0, 0x0f, 0x3f, 0x82, 0xa5, 0x67, 0x46, - 0xb3, 0xa8, 0x9e, 0xd7, 0x29, 0x9b, 0x7d, 0x15, 0x12, 0xa6, 0xaa, 0x1a, 0xb5, 0x07, 0x70, 0x5a, - 0x1c, 0xde, 0xb1, 0xba, 0xe5, 0xb0, 0x4f, 0x1a, 0x82, 0x01, 0x72, 0xab, 0x99, 0x64, 0xcf, 0xeb, - 0xd8, 0x90, 0x7d, 0xee, 0x10, 0x21, 0xab, 0x1a, 0xb5, 0xbb, 0x90, 0x17, 0xc8, 0xf6, 0x30, 0x0b, - 0x96, 0x11, 0xbd, 0xcf, 0x3e, 0xd2, 0xf1, 0x89, 0x68, 0xfc, 0x8f, 0xae, 0x1e, 0x8b, 0x88, 0x52, - 0x9a, 0x11, 0xfb, 0xc6, 0x24, 0xe8, 0x0f, 0xda, 0x44, 0x36, 0xca, 0x1e, 0x0b, 0x9f, 0x32, 0x9e, - 0x31, 0xfb, 0xfe, 0x24, 0xe8, 0x0e, 0x35, 0xa9, 0x0d, 0x42, 0x83, 0xb2, 0x68, 0x50, 0x94, 0xb2, - 0xb8, 0xe8, 0xbf, 0x4b, 0x12, 0xc8, 0xb2, 0x78, 0xd9, 0x22, 0x0c, 0x9f, 0xbe, 0xd6, 0x1e, 0xc0, - 0xfc, 0x49, 0x5c, 0xd6, 0x87, 0x0a, 0xcb, 0xbc, 0x2b, 0xcb, 0x34, 0x39, 0x37, 0xe7, 0xda, 0x21, - 0xcf, 0xb5, 0x01, 0x73, 0x27, 0x70, 0x5b, 0x1f, 0x29, 0x2c, 0x7f, 0xa5, 0x5c, 0x66, 0xae, 0x1d, - 0xf6, 0x5d, 0x73, 0x27, 0x70, 0x5c, 0x1f, 0x2b, 0xec, 0xc2, 0xc3, 0x28, 0xfb, 0x34, 0x9e, 0xef, - 0x9a, 0x3b, 0x81, 0xe3, 0xfa, 0x84, 0xe5, 0xa7, 0xaa, 0x51, 0x11, 0x69, 0xd0, 0x53, 0xcc, 0x9f, - 0xc4, 0x71, 0x7d, 0xaa, 0xe0, 0x05, 0x88, 0x6a, 0x18, 0xfe, 0xfc, 0xf8, 0xbe, 0x6b, 0xfe, 0x24, - 0x8e, 0xeb, 0xab, 0x0a, 0x5e, 0x94, 0xa8, 0xc6, 0x5a, 0x88, 0x28, 0xdc, 0xa3, 0xe3, 0x38, 0xae, - 0xaf, 0x29, 0x78, 0x7b, 0xa1, 0x1a, 0x55, 0x9f, 0x68, 0x67, 0xaa, 0x47, 0xc7, 0x71, 0x5c, 0x5f, - 0xc7, 0x6c, 0xa0, 0xa6, 0x1a, 0x37, 0x42, 0x44, 0xe8, 0xbb, 0xf2, 0x27, 0x72, 0x5c, 0xdf, 0x50, - 0xf0, 0xa2, 0x49, 0x35, 0x6e, 0x9a, 0x5e, 0x0f, 0x02, 0xdf, 0x95, 0x3f, 0x91, 0xe3, 0xfa, 0xa6, - 0x82, 0x37, 0x52, 0xaa, 0x71, 0x2b, 0x4c, 0x85, 0xbe, 0x4b, 0x3b, 0x99, 0xe3, 0xfa, 0x4c, 0xc1, - 0xef, 0x4f, 0xd4, 0xb5, 0x15, 0xd3, 0xeb, 0x84, 0xe0, 0xbb, 0xb4, 0x93, 0x39, 0xae, 0x6f, 0x29, - 0xf8, 0x51, 0x8a, 0xba, 0xb6, 0x1a, 0x21, 0xab, 0x1a, 0xb5, 0x75, 0xc8, 0x1d, 0xdf, 0x71, 0x7d, - 0x5b, 0xbc, 0xef, 0xcb, 0xb6, 0x05, 0xef, 0xf5, 0x58, 0x58, 0xbf, 0x63, 0xb8, 0xae, 0xef, 0x60, - 0xd6, 0x54, 0x7b, 0xe1, 0x3e, 0xbb, 0x15, 0x63, 0x26, 0xaf, 0xb5, 0xad, 0xce, 0x1b, 0x1d, 0xc7, - 0x09, 0x96, 0x94, 0x39, 0xb4, 0x46, 0xb0, 0x7b, 0x8e, 0xe1, 0xcd, 0xbe, 0xab, 0xe0, 0x25, 0x5a, - 0x8e, 0x53, 0xa3, 0x85, 0xbf, 0x8f, 0x98, 0x6b, 0xb3, 0x83, 0x31, 0x3f, 0xdf, 0xaf, 0x7d, 0x4f, - 0x39, 0x99, 0x63, 0xab, 0xc5, 0x1a, 0xdb, 0xeb, 0xfe, 0xe4, 0x60, 0xc9, 0x5b, 0x10, 0x3f, 0x2c, - 0xaf, 0xac, 0x86, 0x8f, 0x78, 0xe2, 0x1d, 0x32, 0x73, 0x67, 0xd9, 0xf2, 0x42, 0xe8, 0xb2, 0x7d, - 0x30, 0x74, 0x8f, 0x4c, 0xb4, 0xe4, 0x0c, 0x65, 0x09, 0xc3, 0x47, 0x52, 0x86, 0x32, 0x67, 0xa8, - 0x48, 0x18, 0x3e, 0x96, 0x32, 0x54, 0x38, 0x83, 0x21, 0x61, 0xf8, 0x44, 0xca, 0x60, 0x70, 0x86, - 0x35, 0x09, 0xc3, 0xa7, 0x52, 0x86, 0x35, 0xce, 0x50, 0x95, 0x30, 0x7c, 0x55, 0xca, 0x50, 0xe5, - 0x0c, 0x37, 0x24, 0x0c, 0x5f, 0x93, 0x32, 0xdc, 0xe0, 0x0c, 0x37, 0x25, 0x0c, 0x5f, 0x97, 0x32, - 0xdc, 0xe4, 0x0c, 0xb7, 0x24, 0x0c, 0xdf, 0x90, 0x32, 0xdc, 0x62, 0x0c, 0xab, 0x2b, 0x12, 0x86, - 0x6f, 0xca, 0x18, 0x56, 0x57, 0x38, 0x83, 0x4c, 0x93, 0x9f, 0x49, 0x19, 0xb8, 0x26, 0x57, 0x65, - 0x9a, 0xfc, 0x96, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0x6f, 0x4b, 0x19, 0xb8, 0x26, 0x57, - 0x65, 0x9a, 0xfc, 0x8e, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0xef, 0x4a, 0x19, 0xb8, 0x26, - 0x57, 0x65, 0x9a, 0xfc, 0x9e, 0x94, 0x81, 0x6b, 0x72, 0x55, 0xa6, 0xc9, 0x3f, 0x91, 0x32, 0x70, - 0x4d, 0xae, 0xca, 0x34, 0xf9, 0xa7, 0x52, 0x06, 0xae, 0xc9, 0x55, 0x99, 0x26, 0xff, 0x4c, 0xca, - 0xc0, 0x35, 0x59, 0x96, 0x69, 0xf2, 0xfb, 0x32, 0x86, 0x32, 0xd7, 0x64, 0x59, 0xa6, 0xc9, 0x3f, - 0x97, 0x32, 0x70, 0x4d, 0x96, 0x65, 0x9a, 0xfc, 0x0b, 0x29, 0x03, 0xd7, 0x64, 0x59, 0xa6, 0xc9, - 0x1f, 0x48, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xa5, 0x94, 0x81, 0x6b, 0xb2, 0x2c, 0xd3, - 0xe4, 0x5f, 0x49, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xb5, 0x94, 0x81, 0x6b, 0xb2, 0x2c, - 0xd3, 0xe4, 0xdf, 0x48, 0x19, 0xb8, 0x26, 0xcb, 0x32, 0x4d, 0xfe, 0xad, 0x94, 0x81, 0x6b, 0xb2, - 0x2c, 0xd3, 0xe4, 0xdf, 0x49, 0x19, 0xb8, 0x26, 0x2b, 0x32, 0x4d, 0xfe, 0xbd, 0x8c, 0xa1, 0xc2, - 0x35, 0x59, 0x91, 0x69, 0xf2, 0x1f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff, 0x51, 0xca, - 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0x9f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff, 0x59, - 0xca, 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0x5f, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, 0xff, - 0x55, 0xca, 0xc0, 0x35, 0x59, 0x91, 0x69, 0xf2, 0xdf, 0xa4, 0x0c, 0x5c, 0x93, 0x15, 0x99, 0x26, - 0x7f, 0x28, 0x65, 0xe0, 0x9a, 0xac, 0xc8, 0x34, 0xf9, 0xef, 0x52, 0x06, 0xae, 0x49, 0x43, 0xa6, - 0xc9, 0xff, 0x90, 0x31, 0x18, 0x5c, 0x93, 0x86, 0x4c, 0x93, 0xff, 0x29, 0x65, 0xe0, 0x9a, 0x34, - 0x64, 0x9a, 0xfc, 0x2f, 0x29, 0x03, 0xd7, 0xa4, 0x21, 0xd3, 0xe4, 0x7f, 0x4b, 0x19, 0xb8, 0x26, - 0x0d, 0x99, 0x26, 0xff, 0x47, 0xca, 0xc0, 0x35, 0x69, 0xc8, 0x34, 0xf9, 0xbf, 0x52, 0x06, 0xae, - 0x49, 0x43, 0xa6, 0xc9, 0x1f, 0x49, 0x19, 0xb8, 0x26, 0x0d, 0x99, 0x26, 0x7f, 0x2c, 0x65, 0xe0, - 0x9a, 0x34, 0x64, 0x9a, 0xfc, 0x89, 0x94, 0x81, 0x6b, 0xd2, 0x90, 0x69, 0xf2, 0xa7, 0x52, 0x06, - 0xae, 0xc9, 0x35, 0x99, 0x26, 0xff, 0x4f, 0xc6, 0xb0, 0xb6, 0x72, 0xe7, 0xda, 0xe3, 0xab, 0xdd, - 0x9e, 0x7b, 0x30, 0xd9, 0x5b, 0xde, 0x77, 0x06, 0xd7, 0xbb, 0x4e, 0xbf, 0x65, 0x77, 0xaf, 0x23, - 0x6c, 0x6f, 0xd2, 0xb9, 0x1e, 0xfc, 0xeb, 0x35, 0x33, 0xfd, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x46, 0xc7, 0xb3, 0x38, 0x92, 0x3d, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/proto/test_proto/test.proto b/examples/github.com/golang/protobuf/proto/test_proto/test.proto deleted file mode 100755 index 22068a9..0000000 --- a/examples/github.com/golang/protobuf/proto/test_proto/test.proto +++ /dev/null @@ -1,562 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// A feature-rich test file for the protocol compiler and libraries. - -syntax = "proto2"; - -option go_package = "github.com/golang/protobuf/proto/test_proto"; - -package test_proto; - -enum FOO { FOO1 = 1; }; - -message GoEnum { - required FOO foo = 1; -} - -message GoTestField { - required string Label = 1; - required string Type = 2; -} - -message GoTest { - // An enum, for completeness. - enum KIND { - VOID = 0; - - // Basic types - BOOL = 1; - BYTES = 2; - FINGERPRINT = 3; - FLOAT = 4; - INT = 5; - STRING = 6; - TIME = 7; - - // Groupings - TUPLE = 8; - ARRAY = 9; - MAP = 10; - - // Table types - TABLE = 11; - - // Functions - FUNCTION = 12; // last tag - }; - - // Some typical parameters - required KIND Kind = 1; - optional string Table = 2; - optional int32 Param = 3; - - // Required, repeated and optional foreign fields. - required GoTestField RequiredField = 4; - repeated GoTestField RepeatedField = 5; - optional GoTestField OptionalField = 6; - - // Required fields of all basic types - required bool F_Bool_required = 10; - required int32 F_Int32_required = 11; - required int64 F_Int64_required = 12; - required fixed32 F_Fixed32_required = 13; - required fixed64 F_Fixed64_required = 14; - required uint32 F_Uint32_required = 15; - required uint64 F_Uint64_required = 16; - required float F_Float_required = 17; - required double F_Double_required = 18; - required string F_String_required = 19; - required bytes F_Bytes_required = 101; - required sint32 F_Sint32_required = 102; - required sint64 F_Sint64_required = 103; - required sfixed32 F_Sfixed32_required = 104; - required sfixed64 F_Sfixed64_required = 105; - - // Repeated fields of all basic types - repeated bool F_Bool_repeated = 20; - repeated int32 F_Int32_repeated = 21; - repeated int64 F_Int64_repeated = 22; - repeated fixed32 F_Fixed32_repeated = 23; - repeated fixed64 F_Fixed64_repeated = 24; - repeated uint32 F_Uint32_repeated = 25; - repeated uint64 F_Uint64_repeated = 26; - repeated float F_Float_repeated = 27; - repeated double F_Double_repeated = 28; - repeated string F_String_repeated = 29; - repeated bytes F_Bytes_repeated = 201; - repeated sint32 F_Sint32_repeated = 202; - repeated sint64 F_Sint64_repeated = 203; - repeated sfixed32 F_Sfixed32_repeated = 204; - repeated sfixed64 F_Sfixed64_repeated = 205; - - // Optional fields of all basic types - optional bool F_Bool_optional = 30; - optional int32 F_Int32_optional = 31; - optional int64 F_Int64_optional = 32; - optional fixed32 F_Fixed32_optional = 33; - optional fixed64 F_Fixed64_optional = 34; - optional uint32 F_Uint32_optional = 35; - optional uint64 F_Uint64_optional = 36; - optional float F_Float_optional = 37; - optional double F_Double_optional = 38; - optional string F_String_optional = 39; - optional bytes F_Bytes_optional = 301; - optional sint32 F_Sint32_optional = 302; - optional sint64 F_Sint64_optional = 303; - optional sfixed32 F_Sfixed32_optional = 304; - optional sfixed64 F_Sfixed64_optional = 305; - - // Default-valued fields of all basic types - optional bool F_Bool_defaulted = 40 [default=true]; - optional int32 F_Int32_defaulted = 41 [default=32]; - optional int64 F_Int64_defaulted = 42 [default=64]; - optional fixed32 F_Fixed32_defaulted = 43 [default=320]; - optional fixed64 F_Fixed64_defaulted = 44 [default=640]; - optional uint32 F_Uint32_defaulted = 45 [default=3200]; - optional uint64 F_Uint64_defaulted = 46 [default=6400]; - optional float F_Float_defaulted = 47 [default=314159.]; - optional double F_Double_defaulted = 48 [default=271828.]; - optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; - optional sint32 F_Sint32_defaulted = 402 [default = -32]; - optional sint64 F_Sint64_defaulted = 403 [default = -64]; - optional sfixed32 F_Sfixed32_defaulted = 404 [default = -32]; - optional sfixed64 F_Sfixed64_defaulted = 405 [default = -64]; - - // Packed repeated fields (no string or bytes). - repeated bool F_Bool_repeated_packed = 50 [packed=true]; - repeated int32 F_Int32_repeated_packed = 51 [packed=true]; - repeated int64 F_Int64_repeated_packed = 52 [packed=true]; - repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; - repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; - repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; - repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; - repeated float F_Float_repeated_packed = 57 [packed=true]; - repeated double F_Double_repeated_packed = 58 [packed=true]; - repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; - repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; - repeated sfixed32 F_Sfixed32_repeated_packed = 504 [packed=true]; - repeated sfixed64 F_Sfixed64_repeated_packed = 505 [packed=true]; - - // Required, repeated, and optional groups. - required group RequiredGroup = 70 { - required string RequiredField = 71; - }; - - repeated group RepeatedGroup = 80 { - required string RequiredField = 81; - }; - - optional group OptionalGroup = 90 { - required string RequiredField = 91; - }; -} - -// For testing a group containing a required field. -message GoTestRequiredGroupField { - required group Group = 1 { - required int32 Field = 2; - }; -} - -// For testing skipping of unrecognized fields. -// Numbers are all big, larger than tag numbers in GoTestField, -// the message used in the corresponding test. -message GoSkipTest { - required int32 skip_int32 = 11; - required fixed32 skip_fixed32 = 12; - required fixed64 skip_fixed64 = 13; - required string skip_string = 14; - required group SkipGroup = 15 { - required int32 group_int32 = 16; - required string group_string = 17; - } -} - -// For testing packed/non-packed decoder switching. -// A serialized instance of one should be deserializable as the other. -message NonPackedTest { - repeated int32 a = 1; -} - -message PackedTest { - repeated int32 b = 1 [packed=true]; -} - -message MaxTag { - // Maximum possible tag number. - optional string last_field = 536870911; -} - -message OldMessage { - message Nested { - optional string name = 1; - } - optional Nested nested = 1; - - optional int32 num = 2; -} - -// NewMessage is wire compatible with OldMessage; -// imagine it as a future version. -message NewMessage { - message Nested { - optional string name = 1; - optional string food_group = 2; - } - optional Nested nested = 1; - - // This is an int32 in OldMessage. - optional int64 num = 2; -} - -// Smaller tests for ASCII formatting. - -message InnerMessage { - required string host = 1; - optional int32 port = 2 [default=4000]; - optional bool connected = 3; -} - -message OtherMessage { - optional int64 key = 1; - optional bytes value = 2; - optional float weight = 3; - optional InnerMessage inner = 4; - - extensions 100 to max; -} - -message RequiredInnerMessage { - required InnerMessage leo_finally_won_an_oscar = 1; -} - -message MyMessage { - required int32 count = 1; - optional string name = 2; - optional string quote = 3; - repeated string pet = 4; - optional InnerMessage inner = 5; - repeated OtherMessage others = 6; - optional RequiredInnerMessage we_must_go_deeper = 13; - repeated InnerMessage rep_inner = 12; - - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - }; - optional Color bikeshed = 7; - - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // This field becomes [][]byte in the generated code. - repeated bytes rep_bytes = 10; - - optional double bigfloat = 11; - - extensions 100 to max; -} - -message Ext { - extend MyMessage { - optional Ext more = 103; - optional string text = 104; - optional int32 number = 105; - } - - optional string data = 1; - map map_field = 2; -} - -extend MyMessage { - repeated string greeting = 106; - // leave field 200 unregistered for testing -} - -message ComplexExtension { - optional int32 first = 1; - optional int32 second = 2; - repeated int32 third = 3; -} - -extend OtherMessage { - optional ComplexExtension complex = 200; - repeated ComplexExtension r_complex = 201; -} - -message DefaultsMessage { - enum DefaultsEnum { - ZERO = 0; - ONE = 1; - TWO = 2; - }; - extensions 100 to max; -} - -extend DefaultsMessage { - optional double no_default_double = 101; - optional float no_default_float = 102; - optional int32 no_default_int32 = 103; - optional int64 no_default_int64 = 104; - optional uint32 no_default_uint32 = 105; - optional uint64 no_default_uint64 = 106; - optional sint32 no_default_sint32 = 107; - optional sint64 no_default_sint64 = 108; - optional fixed32 no_default_fixed32 = 109; - optional fixed64 no_default_fixed64 = 110; - optional sfixed32 no_default_sfixed32 = 111; - optional sfixed64 no_default_sfixed64 = 112; - optional bool no_default_bool = 113; - optional string no_default_string = 114; - optional bytes no_default_bytes = 115; - optional DefaultsMessage.DefaultsEnum no_default_enum = 116; - - optional double default_double = 201 [default = 3.1415]; - optional float default_float = 202 [default = 3.14]; - optional int32 default_int32 = 203 [default = 42]; - optional int64 default_int64 = 204 [default = 43]; - optional uint32 default_uint32 = 205 [default = 44]; - optional uint64 default_uint64 = 206 [default = 45]; - optional sint32 default_sint32 = 207 [default = 46]; - optional sint64 default_sint64 = 208 [default = 47]; - optional fixed32 default_fixed32 = 209 [default = 48]; - optional fixed64 default_fixed64 = 210 [default = 49]; - optional sfixed32 default_sfixed32 = 211 [default = 50]; - optional sfixed64 default_sfixed64 = 212 [default = 51]; - optional bool default_bool = 213 [default = true]; - optional string default_string = 214 [default = "Hello, string,def=foo"]; - optional bytes default_bytes = 215 [default = "Hello, bytes"]; - optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; -} - -message MyMessageSet { - option message_set_wire_format = true; - extensions 100 to max; -} - -message Empty { -} - -extend MyMessageSet { - optional Empty x201 = 201; - optional Empty x202 = 202; - optional Empty x203 = 203; - optional Empty x204 = 204; - optional Empty x205 = 205; - optional Empty x206 = 206; - optional Empty x207 = 207; - optional Empty x208 = 208; - optional Empty x209 = 209; - optional Empty x210 = 210; - optional Empty x211 = 211; - optional Empty x212 = 212; - optional Empty x213 = 213; - optional Empty x214 = 214; - optional Empty x215 = 215; - optional Empty x216 = 216; - optional Empty x217 = 217; - optional Empty x218 = 218; - optional Empty x219 = 219; - optional Empty x220 = 220; - optional Empty x221 = 221; - optional Empty x222 = 222; - optional Empty x223 = 223; - optional Empty x224 = 224; - optional Empty x225 = 225; - optional Empty x226 = 226; - optional Empty x227 = 227; - optional Empty x228 = 228; - optional Empty x229 = 229; - optional Empty x230 = 230; - optional Empty x231 = 231; - optional Empty x232 = 232; - optional Empty x233 = 233; - optional Empty x234 = 234; - optional Empty x235 = 235; - optional Empty x236 = 236; - optional Empty x237 = 237; - optional Empty x238 = 238; - optional Empty x239 = 239; - optional Empty x240 = 240; - optional Empty x241 = 241; - optional Empty x242 = 242; - optional Empty x243 = 243; - optional Empty x244 = 244; - optional Empty x245 = 245; - optional Empty x246 = 246; - optional Empty x247 = 247; - optional Empty x248 = 248; - optional Empty x249 = 249; - optional Empty x250 = 250; -} - -message MessageList { - repeated group Message = 1 { - required string name = 2; - required int32 count = 3; - } -} - -message Strings { - optional string string_field = 1; - optional bytes bytes_field = 2; -} - -message Defaults { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - - // Default-valued fields of all basic types. - // Same as GoTest, but copied here to make testing easier. - optional bool F_Bool = 1 [default=true]; - optional int32 F_Int32 = 2 [default=32]; - optional int64 F_Int64 = 3 [default=64]; - optional fixed32 F_Fixed32 = 4 [default=320]; - optional fixed64 F_Fixed64 = 5 [default=640]; - optional uint32 F_Uint32 = 6 [default=3200]; - optional uint64 F_Uint64 = 7 [default=6400]; - optional float F_Float = 8 [default=314159.]; - optional double F_Double = 9 [default=271828.]; - optional string F_String = 10 [default="hello, \"world!\"\n"]; - optional bytes F_Bytes = 11 [default="Bignose"]; - optional sint32 F_Sint32 = 12 [default=-32]; - optional sint64 F_Sint64 = 13 [default=-64]; - optional Color F_Enum = 14 [default=GREEN]; - - // More fields with crazy defaults. - optional float F_Pinf = 15 [default=inf]; - optional float F_Ninf = 16 [default=-inf]; - optional float F_Nan = 17 [default=nan]; - - // Sub-message. - optional SubDefaults sub = 18; - - // Redundant but explicit defaults. - optional string str_zero = 19 [default=""]; -} - -message SubDefaults { - optional int64 n = 1 [default=7]; -} - -message RepeatedEnum { - enum Color { - RED = 1; - } - repeated Color color = 1; -} - -message MoreRepeated { - repeated bool bools = 1; - repeated bool bools_packed = 2 [packed=true]; - repeated int32 ints = 3; - repeated int32 ints_packed = 4 [packed=true]; - repeated int64 int64s_packed = 7 [packed=true]; - repeated string strings = 5; - repeated fixed32 fixeds = 6; -} - -// GroupOld and GroupNew have the same wire format. -// GroupNew has a new field inside a group. - -message GroupOld { - optional group G = 101 { - optional int32 x = 2; - } -} - -message GroupNew { - optional group G = 101 { - optional int32 x = 2; - optional int32 y = 3; - } -} - -message FloatingPoint { - required double f = 1; - optional bool exact = 2; -} - -message MessageWithMap { - map name_mapping = 1; - map msg_mapping = 2; - map byte_mapping = 3; - map str_to_str = 4; -} - -message Oneof { - oneof union { - bool F_Bool = 1; - int32 F_Int32 = 2; - int64 F_Int64 = 3; - fixed32 F_Fixed32 = 4; - fixed64 F_Fixed64 = 5; - uint32 F_Uint32 = 6; - uint64 F_Uint64 = 7; - float F_Float = 8; - double F_Double = 9; - string F_String = 10; - bytes F_Bytes = 11; - sint32 F_Sint32 = 12; - sint64 F_Sint64 = 13; - MyMessage.Color F_Enum = 14; - GoTestField F_Message = 15; - group F_Group = 16 { - optional int32 x = 17; - } - int32 F_Largest_Tag = 536870911; - } - - oneof tormato { - int32 value = 100; - } -} - -message Communique { - optional bool make_me_cry = 1; - - // This is a oneof, called "union". - oneof union { - int32 number = 5; - string name = 6; - bytes data = 7; - double temp_c = 8; - MyMessage.Color col = 9; - Strings msg = 10; - } -} diff --git a/examples/github.com/golang/protobuf/proto/text.go b/examples/github.com/golang/protobuf/proto/text.go deleted file mode 100755 index 2205fda..0000000 --- a/examples/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,843 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.mkeyprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/examples/github.com/golang/protobuf/proto/text_parser.go b/examples/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100755 index 0685bae..0000000 --- a/examples/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,880 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/examples/github.com/golang/protobuf/proto/text_parser_test.go b/examples/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100755 index a819808..0000000 --- a/examples/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,706 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "fmt" - "math" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/test_proto" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\x00\xAB\xCD\xEF'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\x00\xAB\xCD\xEF"), - }, - }, - - // Quoted string with unicode escapes. - { - in: `count: 42 name: "\u0047\U00000047\uffff\U0010ffff"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("GG\uffff\U0010ffff"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Bad \u escape - { - in: `count: 42 name: "\u000"`, - err: `line 1.16: invalid quoted string "\u000": \u requires 4 following digits`, - }, - - // Bad \U escape - { - in: `count: 42 name: "\U0000000"`, - err: `line 1.16: invalid quoted string "\U0000000": \U requires 8 following digits`, - }, - - // Bad \U escape - { - in: `count: 42 name: "\xxx"`, - err: `line 1.16: invalid quoted string "\xxx": \xxx contains non-hexadecimal digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // unclosed bracket doesn't cause infinite loop - { - in: `[`, - err: `line 1.0: unclosed type_url or extension name`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: fmt.Sprintf(`proto: required field "%T.count" not set`, MyMessage{}), - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: fmt.Sprintf(`proto: required field "%T.host" not set`, InnerMessage{}), - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [test_proto.Ext.more]:`), - buildExtStructTest(`count: 42 [test_proto.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [test_proto.Ext.text]:"Hello, world!" [test_proto.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [test_proto.greeting]:"bula" [test_proto.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !Equal(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !Equal(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/examples/github.com/golang/protobuf/proto/text_test.go b/examples/github.com/golang/protobuf/proto/text_test.go deleted file mode 100755 index 3c8b033..0000000 --- a/examples/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,518 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "sync" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/test_proto" - anypb "github.com/golang/protobuf/ptypes/any" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[test_proto.Ext.more]: < - data: "Big gobs for big rats" -> -[test_proto.greeting]: "adg" -[test_proto.greeting]: "easy" -[test_proto.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func TestRacyMarshal(t *testing.T) { - // This test should be run with the race detector. - - any := &pb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any, pb.E_Ext_Text, proto.String("bar")) - b, err := proto.Marshal(any) - if err != nil { - panic(err) - } - m := &proto3pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any), Value: b}, - } - - wantText := proto.MarshalTextString(m) - wantBytes, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal error: %v", err) - } - - var wg sync.WaitGroup - defer wg.Wait() - wg.Add(20) - for i := 0; i < 10; i++ { - go func() { - defer wg.Done() - got := proto.MarshalTextString(m) - if got != wantText { - t.Errorf("proto.MarshalTextString = %q, want %q", got, wantText) - } - }() - go func() { - defer wg.Done() - got, err := proto.Marshal(m) - if !bytes.Equal(got, wantBytes) || err != nil { - t.Errorf("proto.Marshal = (%x, %v), want (%x, nil)", got, err, wantBytes) - } - }() - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go deleted file mode 100755 index e855b1f..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ /dev/null @@ -1,2812 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/descriptor.proto - -package descriptor // import "github.com/golang/protobuf/protoc-gen-go/descriptor" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type FieldDescriptorProto_Type int32 - -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{0} -} -func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) -} -func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorSet.Merge(dst, src) -} -func (m *FileDescriptorSet) XXX_Size() int { - return xxx_messageInfo_FileDescriptorSet.Size(m) -} -func (m *FileDescriptorSet) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{1} -} -func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) -} -func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorProto.Merge(dst, src) -} -func (m *FileDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FileDescriptorProto.Size(m) -} -func (m *FileDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2} -} -func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) -} -func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto.Merge(dst, src) -} -func (m *DescriptorProto) XXX_Size() int { - return xxx_messageInfo_DescriptorProto.Size(m) -} -func (m *DescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 0} -} -func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src) -} -func (m *DescriptorProto_ExtensionRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) -} -func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 1} -} -func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src) -} -func (m *DescriptorProto_ReservedRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) -} -func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{3} -} - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} -func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) -} -func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) -} -func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src) -} -func (m *ExtensionRangeOptions) XXX_Size() int { - return xxx_messageInfo_ExtensionRangeOptions.Size(m) -} -func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4} -} -func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) -} -func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldDescriptorProto.Merge(dst, src) -} -func (m *FieldDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FieldDescriptorProto.Size(m) -} -func (m *FieldDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{5} -} -func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) -} -func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofDescriptorProto.Merge(dst, src) -} -func (m *OneofDescriptorProto) XXX_Size() int { - return xxx_messageInfo_OneofDescriptorProto.Size(m) -} -func (m *OneofDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6} -} -func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) -} -func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto.Merge(dst, src) -} -func (m *EnumDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto.Size(m) -} -func (m *EnumDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -// Range of reserved numeric values. Reserved values may not be used by -// entries in the same enum. Reserved ranges may not overlap. -// -// Note that this is distinct from DescriptorProto.ReservedRange in that it -// is inclusive such that it can appropriately represent the entire int32 -// domain. -type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } -func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} -func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6, 0} -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo - -func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{7} -} -func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) -} -func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src) -} -func (m *EnumValueDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumValueDescriptorProto.Size(m) -} -func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{8} -} -func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) -} -func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src) -} -func (m *ServiceDescriptorProto) XXX_Size() int { - return xxx_messageInfo_ServiceDescriptorProto.Size(m) -} -func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{9} -} -func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) -} -func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodDescriptorProto.Merge(dst, src) -} -func (m *MethodDescriptorProto) XXX_Size() int { - return xxx_messageInfo_MethodDescriptorProto.Size(m) -} -func (m *MethodDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10} -} - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} -func (m *FileOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileOptions.Unmarshal(m, b) -} -func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) -} -func (dst *FileOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileOptions.Merge(dst, src) -} -func (m *FileOptions) XXX_Size() int { - return xxx_messageInfo_FileOptions.Size(m) -} -func (m *FileOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FileOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FileOptions proto.InternalMessageInfo - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -// Deprecated: Do not use. -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{11} -} - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} -func (m *MessageOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageOptions.Unmarshal(m, b) -} -func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) -} -func (dst *MessageOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageOptions.Merge(dst, src) -} -func (m *MessageOptions) XXX_Size() int { - return xxx_messageInfo_MessageOptions.Size(m) -} -func (m *MessageOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MessageOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageOptions proto.InternalMessageInfo - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12} -} - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} -func (m *FieldOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldOptions.Unmarshal(m, b) -} -func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) -} -func (dst *FieldOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldOptions.Merge(dst, src) -} -func (m *FieldOptions) XXX_Size() int { - return xxx_messageInfo_FieldOptions.Size(m) -} -func (m *FieldOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FieldOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldOptions proto.InternalMessageInfo - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{13} -} - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} -func (m *OneofOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofOptions.Unmarshal(m, b) -} -func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) -} -func (dst *OneofOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofOptions.Merge(dst, src) -} -func (m *OneofOptions) XXX_Size() int { - return xxx_messageInfo_OneofOptions.Size(m) -} -func (m *OneofOptions) XXX_DiscardUnknown() { - xxx_messageInfo_OneofOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofOptions proto.InternalMessageInfo - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{14} -} - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} -func (m *EnumOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumOptions.Unmarshal(m, b) -} -func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) -} -func (dst *EnumOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumOptions.Merge(dst, src) -} -func (m *EnumOptions) XXX_Size() int { - return xxx_messageInfo_EnumOptions.Size(m) -} -func (m *EnumOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumOptions proto.InternalMessageInfo - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{15} -} - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} -func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) -} -func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) -} -func (dst *EnumValueOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueOptions.Merge(dst, src) -} -func (m *EnumValueOptions) XXX_Size() int { - return xxx_messageInfo_EnumValueOptions.Size(m) -} -func (m *EnumValueOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{16} -} - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} -func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) -} -func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) -} -func (dst *ServiceOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceOptions.Merge(dst, src) -} -func (m *ServiceOptions) XXX_Size() int { - return xxx_messageInfo_ServiceOptions.Size(m) -} -func (m *ServiceOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17} -} - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} -func (m *MethodOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodOptions.Unmarshal(m, b) -} -func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) -} -func (dst *MethodOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodOptions.Merge(dst, src) -} -func (m *MethodOptions) XXX_Size() int { - return xxx_messageInfo_MethodOptions.Size(m) -} -func (m *MethodOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MethodOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodOptions proto.InternalMessageInfo - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18} -} -func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) -} -func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption.Merge(dst, src) -} -func (m *UninterpretedOption) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption.Size(m) -} -func (m *UninterpretedOption) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18, 0} -} -func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) -} -func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src) -} -func (m *UninterpretedOption_NamePart) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) -} -func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19} -} -func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) -} -func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo.Merge(dst, src) -} -func (m *SourceCodeInfo) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo.Size(m) -} -func (m *SourceCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19, 0} -} -func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) -} -func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src) -} -func (m *SourceCodeInfo_Location) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo_Location.Size(m) -} -func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20} -} -func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src) -} -func (m *GeneratedCodeInfo) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo.Size(m) -} -func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo - -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} - -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20, 0} -} -func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) -} -func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo - -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} - -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} - -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func init() { - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) -} - -func init() { - proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_descriptor_4df4cb5f42392df6) -} - -var fileDescriptor_descriptor_4df4cb5f42392df6 = []byte{ - // 2555 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, - 0xf5, 0xcf, 0xf2, 0x4b, 0xe4, 0x21, 0x45, 0x8d, 0x46, 0x8a, 0xbd, 0x56, 0x3e, 0x2c, 0x33, 0x1f, - 0x96, 0x9d, 0x7f, 0xa8, 0xc0, 0xb1, 0x1d, 0x47, 0xfe, 0x23, 0x2d, 0x45, 0xae, 0x15, 0xaa, 0x12, - 0xc9, 0x2e, 0xa9, 0xe6, 0x03, 0x28, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, - 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0xd5, 0xab, 0xde, 0x16, 0x45, 0xd1, 0x8b, 0xde, 0x04, 0xe8, - 0x03, 0x14, 0xc8, 0x5d, 0x9f, 0xa0, 0x40, 0xde, 0xa0, 0x68, 0x0b, 0xb4, 0x8f, 0xd0, 0xcb, 0x62, - 0x66, 0x76, 0x97, 0xbb, 0x24, 0x15, 0x2b, 0x01, 0xe2, 0x5c, 0x91, 0xf3, 0x9b, 0xdf, 0x39, 0x73, - 0xe6, 0xcc, 0x99, 0x33, 0x67, 0x66, 0x61, 0x7b, 0xe4, 0x38, 0x23, 0x8b, 0xee, 0xba, 0x9e, 0x13, - 0x38, 0xa7, 0xd3, 0xe1, 0xae, 0x41, 0x7d, 0xdd, 0x33, 0xdd, 0xc0, 0xf1, 0xea, 0x1c, 0xc3, 0x6b, - 0x82, 0x51, 0x8f, 0x18, 0xb5, 0x63, 0x58, 0x7f, 0x60, 0x5a, 0xb4, 0x15, 0x13, 0xfb, 0x34, 0xc0, - 0xf7, 0x20, 0x37, 0x34, 0x2d, 0x2a, 0x4b, 0xdb, 0xd9, 0x9d, 0xf2, 0xad, 0x37, 0xeb, 0x73, 0x42, - 0xf5, 0xb4, 0x44, 0x8f, 0xc1, 0x2a, 0x97, 0xa8, 0xfd, 0x2b, 0x07, 0x1b, 0x4b, 0x7a, 0x31, 0x86, - 0x9c, 0x4d, 0x26, 0x4c, 0xa3, 0xb4, 0x53, 0x52, 0xf9, 0x7f, 0x2c, 0xc3, 0x8a, 0x4b, 0xf4, 0x47, - 0x64, 0x44, 0xe5, 0x0c, 0x87, 0xa3, 0x26, 0x7e, 0x1d, 0xc0, 0xa0, 0x2e, 0xb5, 0x0d, 0x6a, 0xeb, - 0x67, 0x72, 0x76, 0x3b, 0xbb, 0x53, 0x52, 0x13, 0x08, 0x7e, 0x07, 0xd6, 0xdd, 0xe9, 0xa9, 0x65, - 0xea, 0x5a, 0x82, 0x06, 0xdb, 0xd9, 0x9d, 0xbc, 0x8a, 0x44, 0x47, 0x6b, 0x46, 0xbe, 0x0e, 0x6b, - 0x4f, 0x28, 0x79, 0x94, 0xa4, 0x96, 0x39, 0xb5, 0xca, 0xe0, 0x04, 0xb1, 0x09, 0x95, 0x09, 0xf5, - 0x7d, 0x32, 0xa2, 0x5a, 0x70, 0xe6, 0x52, 0x39, 0xc7, 0x67, 0xbf, 0xbd, 0x30, 0xfb, 0xf9, 0x99, - 0x97, 0x43, 0xa9, 0xc1, 0x99, 0x4b, 0x71, 0x03, 0x4a, 0xd4, 0x9e, 0x4e, 0x84, 0x86, 0xfc, 0x39, - 0xfe, 0x53, 0xec, 0xe9, 0x64, 0x5e, 0x4b, 0x91, 0x89, 0x85, 0x2a, 0x56, 0x7c, 0xea, 0x3d, 0x36, - 0x75, 0x2a, 0x17, 0xb8, 0x82, 0xeb, 0x0b, 0x0a, 0xfa, 0xa2, 0x7f, 0x5e, 0x47, 0x24, 0x87, 0x9b, - 0x50, 0xa2, 0x4f, 0x03, 0x6a, 0xfb, 0xa6, 0x63, 0xcb, 0x2b, 0x5c, 0xc9, 0x5b, 0x4b, 0x56, 0x91, - 0x5a, 0xc6, 0xbc, 0x8a, 0x99, 0x1c, 0xbe, 0x0b, 0x2b, 0x8e, 0x1b, 0x98, 0x8e, 0xed, 0xcb, 0xc5, - 0x6d, 0x69, 0xa7, 0x7c, 0xeb, 0xd5, 0xa5, 0x81, 0xd0, 0x15, 0x1c, 0x35, 0x22, 0xe3, 0x36, 0x20, - 0xdf, 0x99, 0x7a, 0x3a, 0xd5, 0x74, 0xc7, 0xa0, 0x9a, 0x69, 0x0f, 0x1d, 0xb9, 0xc4, 0x15, 0x5c, - 0x5d, 0x9c, 0x08, 0x27, 0x36, 0x1d, 0x83, 0xb6, 0xed, 0xa1, 0xa3, 0x56, 0xfd, 0x54, 0x1b, 0x5f, - 0x82, 0x82, 0x7f, 0x66, 0x07, 0xe4, 0xa9, 0x5c, 0xe1, 0x11, 0x12, 0xb6, 0x6a, 0x5f, 0x17, 0x60, - 0xed, 0x22, 0x21, 0x76, 0x1f, 0xf2, 0x43, 0x36, 0x4b, 0x39, 0xf3, 0x5d, 0x7c, 0x20, 0x64, 0xd2, - 0x4e, 0x2c, 0x7c, 0x4f, 0x27, 0x36, 0xa0, 0x6c, 0x53, 0x3f, 0xa0, 0x86, 0x88, 0x88, 0xec, 0x05, - 0x63, 0x0a, 0x84, 0xd0, 0x62, 0x48, 0xe5, 0xbe, 0x57, 0x48, 0x7d, 0x0a, 0x6b, 0xb1, 0x49, 0x9a, - 0x47, 0xec, 0x51, 0x14, 0x9b, 0xbb, 0xcf, 0xb3, 0xa4, 0xae, 0x44, 0x72, 0x2a, 0x13, 0x53, 0xab, - 0x34, 0xd5, 0xc6, 0x2d, 0x00, 0xc7, 0xa6, 0xce, 0x50, 0x33, 0xa8, 0x6e, 0xc9, 0xc5, 0x73, 0xbc, - 0xd4, 0x65, 0x94, 0x05, 0x2f, 0x39, 0x02, 0xd5, 0x2d, 0xfc, 0xe1, 0x2c, 0xd4, 0x56, 0xce, 0x89, - 0x94, 0x63, 0xb1, 0xc9, 0x16, 0xa2, 0xed, 0x04, 0xaa, 0x1e, 0x65, 0x71, 0x4f, 0x8d, 0x70, 0x66, - 0x25, 0x6e, 0x44, 0xfd, 0xb9, 0x33, 0x53, 0x43, 0x31, 0x31, 0xb1, 0x55, 0x2f, 0xd9, 0xc4, 0x6f, - 0x40, 0x0c, 0x68, 0x3c, 0xac, 0x80, 0x67, 0xa1, 0x4a, 0x04, 0x76, 0xc8, 0x84, 0x6e, 0x7d, 0x09, - 0xd5, 0xb4, 0x7b, 0xf0, 0x26, 0xe4, 0xfd, 0x80, 0x78, 0x01, 0x8f, 0xc2, 0xbc, 0x2a, 0x1a, 0x18, - 0x41, 0x96, 0xda, 0x06, 0xcf, 0x72, 0x79, 0x95, 0xfd, 0xc5, 0x3f, 0x9d, 0x4d, 0x38, 0xcb, 0x27, - 0xfc, 0xf6, 0xe2, 0x8a, 0xa6, 0x34, 0xcf, 0xcf, 0x7b, 0xeb, 0x03, 0x58, 0x4d, 0x4d, 0xe0, 0xa2, - 0x43, 0xd7, 0x7e, 0x05, 0x2f, 0x2f, 0x55, 0x8d, 0x3f, 0x85, 0xcd, 0xa9, 0x6d, 0xda, 0x01, 0xf5, - 0x5c, 0x8f, 0xb2, 0x88, 0x15, 0x43, 0xc9, 0xff, 0x5e, 0x39, 0x27, 0xe6, 0x4e, 0x92, 0x6c, 0xa1, - 0x45, 0xdd, 0x98, 0x2e, 0x82, 0x37, 0x4b, 0xc5, 0xff, 0xac, 0xa0, 0x67, 0xcf, 0x9e, 0x3d, 0xcb, - 0xd4, 0x7e, 0x57, 0x80, 0xcd, 0x65, 0x7b, 0x66, 0xe9, 0xf6, 0xbd, 0x04, 0x05, 0x7b, 0x3a, 0x39, - 0xa5, 0x1e, 0x77, 0x52, 0x5e, 0x0d, 0x5b, 0xb8, 0x01, 0x79, 0x8b, 0x9c, 0x52, 0x4b, 0xce, 0x6d, - 0x4b, 0x3b, 0xd5, 0x5b, 0xef, 0x5c, 0x68, 0x57, 0xd6, 0x8f, 0x98, 0x88, 0x2a, 0x24, 0xf1, 0x47, - 0x90, 0x0b, 0x53, 0x34, 0xd3, 0x70, 0xf3, 0x62, 0x1a, 0xd8, 0x5e, 0x52, 0xb9, 0x1c, 0x7e, 0x05, - 0x4a, 0xec, 0x57, 0xc4, 0x46, 0x81, 0xdb, 0x5c, 0x64, 0x00, 0x8b, 0x0b, 0xbc, 0x05, 0x45, 0xbe, - 0x4d, 0x0c, 0x1a, 0x1d, 0x6d, 0x71, 0x9b, 0x05, 0x96, 0x41, 0x87, 0x64, 0x6a, 0x05, 0xda, 0x63, - 0x62, 0x4d, 0x29, 0x0f, 0xf8, 0x92, 0x5a, 0x09, 0xc1, 0x5f, 0x30, 0x0c, 0x5f, 0x85, 0xb2, 0xd8, - 0x55, 0xa6, 0x6d, 0xd0, 0xa7, 0x3c, 0x7b, 0xe6, 0x55, 0xb1, 0xd1, 0xda, 0x0c, 0x61, 0xc3, 0x3f, - 0xf4, 0x1d, 0x3b, 0x0a, 0x4d, 0x3e, 0x04, 0x03, 0xf8, 0xf0, 0x1f, 0xcc, 0x27, 0xee, 0xd7, 0x96, - 0x4f, 0x6f, 0x3e, 0xa6, 0x6a, 0x7f, 0xc9, 0x40, 0x8e, 0xe7, 0x8b, 0x35, 0x28, 0x0f, 0x3e, 0xeb, - 0x29, 0x5a, 0xab, 0x7b, 0xb2, 0x7f, 0xa4, 0x20, 0x09, 0x57, 0x01, 0x38, 0xf0, 0xe0, 0xa8, 0xdb, - 0x18, 0xa0, 0x4c, 0xdc, 0x6e, 0x77, 0x06, 0x77, 0x6f, 0xa3, 0x6c, 0x2c, 0x70, 0x22, 0x80, 0x5c, - 0x92, 0xf0, 0xfe, 0x2d, 0x94, 0xc7, 0x08, 0x2a, 0x42, 0x41, 0xfb, 0x53, 0xa5, 0x75, 0xf7, 0x36, - 0x2a, 0xa4, 0x91, 0xf7, 0x6f, 0xa1, 0x15, 0xbc, 0x0a, 0x25, 0x8e, 0xec, 0x77, 0xbb, 0x47, 0xa8, - 0x18, 0xeb, 0xec, 0x0f, 0xd4, 0x76, 0xe7, 0x00, 0x95, 0x62, 0x9d, 0x07, 0x6a, 0xf7, 0xa4, 0x87, - 0x20, 0xd6, 0x70, 0xac, 0xf4, 0xfb, 0x8d, 0x03, 0x05, 0x95, 0x63, 0xc6, 0xfe, 0x67, 0x03, 0xa5, - 0x8f, 0x2a, 0x29, 0xb3, 0xde, 0xbf, 0x85, 0x56, 0xe3, 0x21, 0x94, 0xce, 0xc9, 0x31, 0xaa, 0xe2, - 0x75, 0x58, 0x15, 0x43, 0x44, 0x46, 0xac, 0xcd, 0x41, 0x77, 0x6f, 0x23, 0x34, 0x33, 0x44, 0x68, - 0x59, 0x4f, 0x01, 0x77, 0x6f, 0x23, 0x5c, 0x6b, 0x42, 0x9e, 0x47, 0x17, 0xc6, 0x50, 0x3d, 0x6a, - 0xec, 0x2b, 0x47, 0x5a, 0xb7, 0x37, 0x68, 0x77, 0x3b, 0x8d, 0x23, 0x24, 0xcd, 0x30, 0x55, 0xf9, - 0xf9, 0x49, 0x5b, 0x55, 0x5a, 0x28, 0x93, 0xc4, 0x7a, 0x4a, 0x63, 0xa0, 0xb4, 0x50, 0xb6, 0xa6, - 0xc3, 0xe6, 0xb2, 0x3c, 0xb9, 0x74, 0x67, 0x24, 0x96, 0x38, 0x73, 0xce, 0x12, 0x73, 0x5d, 0x0b, - 0x4b, 0xfc, 0xcf, 0x0c, 0x6c, 0x2c, 0x39, 0x2b, 0x96, 0x0e, 0xf2, 0x13, 0xc8, 0x8b, 0x10, 0x15, - 0xa7, 0xe7, 0x8d, 0xa5, 0x87, 0x0e, 0x0f, 0xd8, 0x85, 0x13, 0x94, 0xcb, 0x25, 0x2b, 0x88, 0xec, - 0x39, 0x15, 0x04, 0x53, 0xb1, 0x90, 0xd3, 0x7f, 0xb9, 0x90, 0xd3, 0xc5, 0xb1, 0x77, 0xf7, 0x22, - 0xc7, 0x1e, 0xc7, 0xbe, 0x5b, 0x6e, 0xcf, 0x2f, 0xc9, 0xed, 0xf7, 0x61, 0x7d, 0x41, 0xd1, 0x85, - 0x73, 0xec, 0xaf, 0x25, 0x90, 0xcf, 0x73, 0xce, 0x73, 0x32, 0x5d, 0x26, 0x95, 0xe9, 0xee, 0xcf, - 0x7b, 0xf0, 0xda, 0xf9, 0x8b, 0xb0, 0xb0, 0xd6, 0x5f, 0x49, 0x70, 0x69, 0x79, 0xa5, 0xb8, 0xd4, - 0x86, 0x8f, 0xa0, 0x30, 0xa1, 0xc1, 0xd8, 0x89, 0xaa, 0xa5, 0xb7, 0x97, 0x9c, 0xc1, 0xac, 0x7b, - 0x7e, 0xb1, 0x43, 0xa9, 0xe4, 0x21, 0x9e, 0x3d, 0xaf, 0xdc, 0x13, 0xd6, 0x2c, 0x58, 0xfa, 0x9b, - 0x0c, 0xbc, 0xbc, 0x54, 0xf9, 0x52, 0x43, 0x5f, 0x03, 0x30, 0x6d, 0x77, 0x1a, 0x88, 0x8a, 0x48, - 0x24, 0xd8, 0x12, 0x47, 0x78, 0xf2, 0x62, 0xc9, 0x73, 0x1a, 0xc4, 0xfd, 0x59, 0xde, 0x0f, 0x02, - 0xe2, 0x84, 0x7b, 0x33, 0x43, 0x73, 0xdc, 0xd0, 0xd7, 0xcf, 0x99, 0xe9, 0x42, 0x60, 0xbe, 0x07, - 0x48, 0xb7, 0x4c, 0x6a, 0x07, 0x9a, 0x1f, 0x78, 0x94, 0x4c, 0x4c, 0x7b, 0xc4, 0x4f, 0x90, 0xe2, - 0x5e, 0x7e, 0x48, 0x2c, 0x9f, 0xaa, 0x6b, 0xa2, 0xbb, 0x1f, 0xf5, 0x32, 0x09, 0x1e, 0x40, 0x5e, - 0x42, 0xa2, 0x90, 0x92, 0x10, 0xdd, 0xb1, 0x44, 0xed, 0xeb, 0x22, 0x94, 0x13, 0x75, 0x35, 0xbe, - 0x06, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0xf0, 0x44, 0x99, 0x61, 0xbd, 0xf0, 0xbe, - 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0xee, 0xb4, 0x22, - 0xa7, 0x62, 0xd6, 0xd7, 0x65, 0x5d, 0xcd, 0xa8, 0x07, 0xdf, 0x81, 0x0d, 0x2e, 0x31, 0x99, 0x5a, - 0x81, 0xe9, 0x5a, 0x54, 0x63, 0xb7, 0x37, 0x9f, 0x9f, 0x24, 0xb1, 0x65, 0xeb, 0x8c, 0x71, 0x1c, - 0x12, 0x98, 0x45, 0x3e, 0x6e, 0xc1, 0x6b, 0x5c, 0x6c, 0x44, 0x6d, 0xea, 0x91, 0x80, 0x6a, 0xf4, - 0x8b, 0x29, 0xb1, 0x7c, 0x8d, 0xd8, 0x86, 0x36, 0x26, 0xfe, 0x58, 0xde, 0x64, 0x0a, 0xf6, 0x33, - 0xb2, 0xa4, 0x5e, 0x61, 0xc4, 0x83, 0x90, 0xa7, 0x70, 0x5a, 0xc3, 0x36, 0x3e, 0x26, 0xfe, 0x18, - 0xef, 0xc1, 0x25, 0xae, 0xc5, 0x0f, 0x3c, 0xd3, 0x1e, 0x69, 0xfa, 0x98, 0xea, 0x8f, 0xb4, 0x69, - 0x30, 0xbc, 0x27, 0xbf, 0x92, 0x1c, 0x9f, 0x5b, 0xd8, 0xe7, 0x9c, 0x26, 0xa3, 0x9c, 0x04, 0xc3, - 0x7b, 0xb8, 0x0f, 0x15, 0xb6, 0x18, 0x13, 0xf3, 0x4b, 0xaa, 0x0d, 0x1d, 0x8f, 0x1f, 0x8d, 0xd5, - 0x25, 0xa9, 0x29, 0xe1, 0xc1, 0x7a, 0x37, 0x14, 0x38, 0x76, 0x0c, 0xba, 0x97, 0xef, 0xf7, 0x14, - 0xa5, 0xa5, 0x96, 0x23, 0x2d, 0x0f, 0x1c, 0x8f, 0x05, 0xd4, 0xc8, 0x89, 0x1d, 0x5c, 0x16, 0x01, - 0x35, 0x72, 0x22, 0xf7, 0xde, 0x81, 0x0d, 0x5d, 0x17, 0x73, 0x36, 0x75, 0x2d, 0xbc, 0x63, 0xf9, - 0x32, 0x4a, 0x39, 0x4b, 0xd7, 0x0f, 0x04, 0x21, 0x8c, 0x71, 0x1f, 0x7f, 0x08, 0x2f, 0xcf, 0x9c, - 0x95, 0x14, 0x5c, 0x5f, 0x98, 0xe5, 0xbc, 0xe8, 0x1d, 0xd8, 0x70, 0xcf, 0x16, 0x05, 0x71, 0x6a, - 0x44, 0xf7, 0x6c, 0x5e, 0xec, 0x03, 0xd8, 0x74, 0xc7, 0xee, 0xa2, 0xdc, 0xcd, 0xa4, 0x1c, 0x76, - 0xc7, 0xee, 0xbc, 0xe0, 0x5b, 0xfc, 0xc2, 0xed, 0x51, 0x9d, 0x04, 0xd4, 0x90, 0x2f, 0x27, 0xe9, - 0x89, 0x0e, 0xbc, 0x0b, 0x48, 0xd7, 0x35, 0x6a, 0x93, 0x53, 0x8b, 0x6a, 0xc4, 0xa3, 0x36, 0xf1, - 0xe5, 0xab, 0x49, 0x72, 0x55, 0xd7, 0x15, 0xde, 0xdb, 0xe0, 0x9d, 0xf8, 0x26, 0xac, 0x3b, 0xa7, - 0x0f, 0x75, 0x11, 0x92, 0x9a, 0xeb, 0xd1, 0xa1, 0xf9, 0x54, 0x7e, 0x93, 0xfb, 0x77, 0x8d, 0x75, - 0xf0, 0x80, 0xec, 0x71, 0x18, 0xdf, 0x00, 0xa4, 0xfb, 0x63, 0xe2, 0xb9, 0x3c, 0x27, 0xfb, 0x2e, - 0xd1, 0xa9, 0xfc, 0x96, 0xa0, 0x0a, 0xbc, 0x13, 0xc1, 0x6c, 0x4b, 0xf8, 0x4f, 0xcc, 0x61, 0x10, - 0x69, 0xbc, 0x2e, 0xb6, 0x04, 0xc7, 0x42, 0x6d, 0x3b, 0x80, 0x98, 0x2b, 0x52, 0x03, 0xef, 0x70, - 0x5a, 0xd5, 0x1d, 0xbb, 0xc9, 0x71, 0xdf, 0x80, 0x55, 0xc6, 0x9c, 0x0d, 0x7a, 0x43, 0x14, 0x64, - 0xee, 0x38, 0x31, 0xe2, 0x0f, 0x56, 0x1b, 0xd7, 0xf6, 0xa0, 0x92, 0x8c, 0x4f, 0x5c, 0x02, 0x11, - 0xa1, 0x48, 0x62, 0xc5, 0x4a, 0xb3, 0xdb, 0x62, 0x65, 0xc6, 0xe7, 0x0a, 0xca, 0xb0, 0x72, 0xe7, - 0xa8, 0x3d, 0x50, 0x34, 0xf5, 0xa4, 0x33, 0x68, 0x1f, 0x2b, 0x28, 0x9b, 0xa8, 0xab, 0x0f, 0x73, - 0xc5, 0xb7, 0xd1, 0xf5, 0xda, 0x37, 0x19, 0xa8, 0xa6, 0x2f, 0x4a, 0xf8, 0xff, 0xe1, 0x72, 0xf4, - 0xaa, 0xe1, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0xe3, 0x4c, 0x88, 0x38, 0xc4, 0xe2, 0xa5, 0xdb, - 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0x5b, 0x4c, 0x48, 0x80, 0x8f, 0xe0, 0xaa, 0xed, - 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0x4f, 0xd2, 0x88, 0xae, 0x53, 0xdf, 0x77, - 0xc4, 0x81, 0x15, 0x6b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x96, 0xc9, 0x1b, 0x21, 0x75, 0x2e, - 0xcc, 0xb2, 0xe7, 0x85, 0xd9, 0x2b, 0x50, 0x9a, 0x10, 0x57, 0xa3, 0x76, 0xe0, 0x9d, 0xf1, 0xf2, - 0xb8, 0xa8, 0x16, 0x27, 0xc4, 0x55, 0x58, 0xfb, 0x85, 0xdc, 0x52, 0x0e, 0x73, 0xc5, 0x22, 0x2a, - 0x1d, 0xe6, 0x8a, 0x25, 0x04, 0xb5, 0x7f, 0x64, 0xa1, 0x92, 0x2c, 0x97, 0xd9, 0xed, 0x43, 0xe7, - 0x27, 0x8b, 0xc4, 0x73, 0xcf, 0x1b, 0xdf, 0x5a, 0x5c, 0xd7, 0x9b, 0xec, 0xc8, 0xd9, 0x2b, 0x88, - 0x22, 0x56, 0x15, 0x92, 0xec, 0xb8, 0x67, 0xd9, 0x86, 0x8a, 0xa2, 0xa1, 0xa8, 0x86, 0x2d, 0x7c, - 0x00, 0x85, 0x87, 0x3e, 0xd7, 0x5d, 0xe0, 0xba, 0xdf, 0xfc, 0x76, 0xdd, 0x87, 0x7d, 0xae, 0xbc, - 0x74, 0xd8, 0xd7, 0x3a, 0x5d, 0xf5, 0xb8, 0x71, 0xa4, 0x86, 0xe2, 0xf8, 0x0a, 0xe4, 0x2c, 0xf2, - 0xe5, 0x59, 0xfa, 0x70, 0xe2, 0xd0, 0x45, 0x17, 0xe1, 0x0a, 0xe4, 0x9e, 0x50, 0xf2, 0x28, 0x7d, - 0x24, 0x70, 0xe8, 0x07, 0xdc, 0x0c, 0xbb, 0x90, 0xe7, 0xfe, 0xc2, 0x00, 0xa1, 0xc7, 0xd0, 0x4b, - 0xb8, 0x08, 0xb9, 0x66, 0x57, 0x65, 0x1b, 0x02, 0x41, 0x45, 0xa0, 0x5a, 0xaf, 0xad, 0x34, 0x15, - 0x94, 0xa9, 0xdd, 0x81, 0x82, 0x70, 0x02, 0xdb, 0x2c, 0xb1, 0x1b, 0xd0, 0x4b, 0x61, 0x33, 0xd4, - 0x21, 0x45, 0xbd, 0x27, 0xc7, 0xfb, 0x8a, 0x8a, 0x32, 0xe9, 0xa5, 0xce, 0xa1, 0x7c, 0xcd, 0x87, - 0x4a, 0xb2, 0x5e, 0x7e, 0x31, 0x77, 0xe1, 0xbf, 0x4a, 0x50, 0x4e, 0xd4, 0xbf, 0xac, 0x70, 0x21, - 0x96, 0xe5, 0x3c, 0xd1, 0x88, 0x65, 0x12, 0x3f, 0x0c, 0x0d, 0xe0, 0x50, 0x83, 0x21, 0x17, 0x5d, - 0xba, 0x17, 0xb4, 0x45, 0xf2, 0xa8, 0x50, 0xfb, 0xa3, 0x04, 0x68, 0xbe, 0x00, 0x9d, 0x33, 0x53, - 0xfa, 0x31, 0xcd, 0xac, 0xfd, 0x41, 0x82, 0x6a, 0xba, 0xea, 0x9c, 0x33, 0xef, 0xda, 0x8f, 0x6a, - 0xde, 0xdf, 0x33, 0xb0, 0x9a, 0xaa, 0x35, 0x2f, 0x6a, 0xdd, 0x17, 0xb0, 0x6e, 0x1a, 0x74, 0xe2, - 0x3a, 0x01, 0xb5, 0xf5, 0x33, 0xcd, 0xa2, 0x8f, 0xa9, 0x25, 0xd7, 0x78, 0xd2, 0xd8, 0xfd, 0xf6, - 0x6a, 0xb6, 0xde, 0x9e, 0xc9, 0x1d, 0x31, 0xb1, 0xbd, 0x8d, 0x76, 0x4b, 0x39, 0xee, 0x75, 0x07, - 0x4a, 0xa7, 0xf9, 0x99, 0x76, 0xd2, 0xf9, 0x59, 0xa7, 0xfb, 0x49, 0x47, 0x45, 0xe6, 0x1c, 0xed, - 0x07, 0xdc, 0xf6, 0x3d, 0x40, 0xf3, 0x46, 0xe1, 0xcb, 0xb0, 0xcc, 0x2c, 0xf4, 0x12, 0xde, 0x80, - 0xb5, 0x4e, 0x57, 0xeb, 0xb7, 0x5b, 0x8a, 0xa6, 0x3c, 0x78, 0xa0, 0x34, 0x07, 0x7d, 0xf1, 0x3e, - 0x11, 0xb3, 0x07, 0xa9, 0x0d, 0x5e, 0xfb, 0x7d, 0x16, 0x36, 0x96, 0x58, 0x82, 0x1b, 0xe1, 0xcd, - 0x42, 0x5c, 0x76, 0xde, 0xbd, 0x88, 0xf5, 0x75, 0x56, 0x10, 0xf4, 0x88, 0x17, 0x84, 0x17, 0x91, - 0x1b, 0xc0, 0xbc, 0x64, 0x07, 0xe6, 0xd0, 0xa4, 0x5e, 0xf8, 0x9c, 0x23, 0xae, 0x1b, 0x6b, 0x33, - 0x5c, 0xbc, 0xe8, 0xfc, 0x1f, 0x60, 0xd7, 0xf1, 0xcd, 0xc0, 0x7c, 0x4c, 0x35, 0xd3, 0x8e, 0xde, - 0x7e, 0xd8, 0xf5, 0x23, 0xa7, 0xa2, 0xa8, 0xa7, 0x6d, 0x07, 0x31, 0xdb, 0xa6, 0x23, 0x32, 0xc7, - 0x66, 0xc9, 0x3c, 0xab, 0xa2, 0xa8, 0x27, 0x66, 0x5f, 0x83, 0x8a, 0xe1, 0x4c, 0x59, 0x4d, 0x26, - 0x78, 0xec, 0xec, 0x90, 0xd4, 0xb2, 0xc0, 0x62, 0x4a, 0x58, 0x6d, 0xcf, 0x1e, 0x9d, 0x2a, 0x6a, - 0x59, 0x60, 0x82, 0x72, 0x1d, 0xd6, 0xc8, 0x68, 0xe4, 0x31, 0xe5, 0x91, 0x22, 0x71, 0x7f, 0xa8, - 0xc6, 0x30, 0x27, 0x6e, 0x1d, 0x42, 0x31, 0xf2, 0x03, 0x3b, 0xaa, 0x99, 0x27, 0x34, 0x57, 0x5c, - 0x8a, 0x33, 0x3b, 0x25, 0xb5, 0x68, 0x47, 0x9d, 0xd7, 0xa0, 0x62, 0xfa, 0xda, 0xec, 0x0d, 0x3d, - 0xb3, 0x9d, 0xd9, 0x29, 0xaa, 0x65, 0xd3, 0x8f, 0xdf, 0x1f, 0x6b, 0x5f, 0x65, 0xa0, 0x9a, 0xfe, - 0x06, 0x80, 0x5b, 0x50, 0xb4, 0x1c, 0x9d, 0xf0, 0xd0, 0x12, 0x1f, 0xa0, 0x76, 0x9e, 0xf3, 0xd9, - 0xa0, 0x7e, 0x14, 0xf2, 0xd5, 0x58, 0x72, 0xeb, 0x6f, 0x12, 0x14, 0x23, 0x18, 0x5f, 0x82, 0x9c, - 0x4b, 0x82, 0x31, 0x57, 0x97, 0xdf, 0xcf, 0x20, 0x49, 0xe5, 0x6d, 0x86, 0xfb, 0x2e, 0xb1, 0x79, - 0x08, 0x84, 0x38, 0x6b, 0xb3, 0x75, 0xb5, 0x28, 0x31, 0xf8, 0xe5, 0xc4, 0x99, 0x4c, 0xa8, 0x1d, - 0xf8, 0xd1, 0xba, 0x86, 0x78, 0x33, 0x84, 0xf1, 0x3b, 0xb0, 0x1e, 0x78, 0xc4, 0xb4, 0x52, 0xdc, - 0x1c, 0xe7, 0xa2, 0xa8, 0x23, 0x26, 0xef, 0xc1, 0x95, 0x48, 0xaf, 0x41, 0x03, 0xa2, 0x8f, 0xa9, - 0x31, 0x13, 0x2a, 0xf0, 0x47, 0x88, 0xcb, 0x21, 0xa1, 0x15, 0xf6, 0x47, 0xb2, 0xb5, 0x6f, 0x24, - 0x58, 0x8f, 0xae, 0x53, 0x46, 0xec, 0xac, 0x63, 0x00, 0x62, 0xdb, 0x4e, 0x90, 0x74, 0xd7, 0x62, - 0x28, 0x2f, 0xc8, 0xd5, 0x1b, 0xb1, 0x90, 0x9a, 0x50, 0xb0, 0x35, 0x01, 0x98, 0xf5, 0x9c, 0xeb, - 0xb6, 0xab, 0x50, 0x0e, 0x3f, 0xf0, 0xf0, 0xaf, 0x84, 0xe2, 0x02, 0x0e, 0x02, 0x62, 0xf7, 0x2e, - 0xbc, 0x09, 0xf9, 0x53, 0x3a, 0x32, 0xed, 0xf0, 0xd9, 0x56, 0x34, 0xa2, 0x67, 0x92, 0x5c, 0xfc, - 0x4c, 0xb2, 0xff, 0x5b, 0x09, 0x36, 0x74, 0x67, 0x32, 0x6f, 0xef, 0x3e, 0x9a, 0x7b, 0x05, 0xf0, - 0x3f, 0x96, 0x3e, 0xff, 0x68, 0x64, 0x06, 0xe3, 0xe9, 0x69, 0x5d, 0x77, 0x26, 0xbb, 0x23, 0xc7, - 0x22, 0xf6, 0x68, 0xf6, 0x99, 0x93, 0xff, 0xd1, 0xdf, 0x1d, 0x51, 0xfb, 0xdd, 0x91, 0x93, 0xf8, - 0xe8, 0x79, 0x7f, 0xf6, 0xf7, 0xbf, 0x92, 0xf4, 0xa7, 0x4c, 0xf6, 0xa0, 0xb7, 0xff, 0xe7, 0xcc, - 0xd6, 0x81, 0x18, 0xae, 0x17, 0xb9, 0x47, 0xa5, 0x43, 0x8b, 0xea, 0x6c, 0xca, 0xff, 0x0b, 0x00, - 0x00, 0xff, 0xff, 0x1a, 0x28, 0x25, 0x79, 0x42, 0x1d, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto deleted file mode 100755 index 8697a50..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto +++ /dev/null @@ -1,872 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// The messages in this file describe the definitions found in .proto files. -// A valid .proto file can be translated directly to a FileDescriptorProto -// without any other information (e.g. without reading its imports). - - -syntax = "proto2"; - -package google.protobuf; -option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.Protobuf.Reflection"; -option objc_class_prefix = "GPB"; -option cc_enable_arenas = true; - -// descriptor.proto must be optimized for speed because reflection-based -// algorithms don't work during bootstrapping. -option optimize_for = SPEED; - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} - -// Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. - - // Names of files imported by this file. - repeated string dependency = 3; - // Indexes of the public imported files in the dependency list above. - repeated int32 public_dependency = 10; - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - repeated int32 weak_dependency = 11; - - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; - - optional FileOptions options = 8; - - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - optional SourceCodeInfo source_code_info = 9; - - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - optional string syntax = 12; -} - -// Describes a message type. -message DescriptorProto { - optional string name = 1; - - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; - - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; - - message ExtensionRange { - optional int32 start = 1; - optional int32 end = 2; - - optional ExtensionRangeOptions options = 3; - } - repeated ExtensionRange extension_range = 5; - - repeated OneofDescriptorProto oneof_decl = 8; - - optional MessageOptions options = 7; - - // Range of reserved tag numbers. Reserved tag numbers may not be used by - // fields or extension ranges in the same message. Reserved ranges may - // not overlap. - message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - } - repeated ReservedRange reserved_range = 9; - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - repeated string reserved_name = 10; -} - -message ExtensionRangeOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -// Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. - - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - }; - - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - }; - - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; - - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - optional Type type = 5; - - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; - - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; - - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - optional string default_value = 7; - - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - optional int32 oneof_index = 9; - - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - optional string json_name = 10; - - optional FieldOptions options = 8; -} - -// Describes a oneof. -message OneofDescriptorProto { - optional string name = 1; - optional OneofOptions options = 2; -} - -// Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; - - repeated EnumValueDescriptorProto value = 2; - - optional EnumOptions options = 3; - - // Range of reserved numeric values. Reserved values may not be used by - // entries in the same enum. Reserved ranges may not overlap. - // - // Note that this is distinct from DescriptorProto.ReservedRange in that it - // is inclusive such that it can appropriately represent the entire int32 - // domain. - message EnumReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Inclusive. - } - - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - repeated EnumReservedRange reserved_range = 4; - - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - repeated string reserved_name = 5; -} - -// Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; - - optional EnumValueOptions options = 3; -} - -// Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; - - optional ServiceOptions options = 3; -} - -// Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; - - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; - - optional MethodOptions options = 4; - - // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default=false]; - // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default=false]; -} - - -// =================================================================== -// Options - -// Each of the definitions above may have "options" attached. These are -// just annotations which may cause code to be generated slightly differently -// or may contain hints for code that manipulates protocol messages. -// -// Clients may define custom options as extensions of the *Options messages. -// These extensions may not yet be known at parsing time, so the parser cannot -// store the values in them. Instead it stores them in a field in the *Options -// message called uninterpreted_option. This field must have the same name -// across all *Options messages. We then use this field to populate the -// extensions when we build a descriptor, at which point all protos have been -// parsed and so all extensions are known. -// -// Extension numbers for custom options may be chosen as follows: -// * For options which will only be used within a single application or -// organization, or for experimental options, use field numbers 50000 -// through 99999. It is up to you to ensure that you do not use the -// same number for multiple options. -// * For options which will be published and used publicly by multiple -// independent entities, e-mail protobuf-global-extension-registry@google.com -// to reserve extension numbers. Simply provide your project name (e.g. -// Objective-C plugin) and your project website (if available) -- there's no -// need to explain how you intend to use them. Usually you only need one -// extension number. You can declare multiple options with only one extension -// number by putting them in a sub-message. See the Custom Options section of -// the docs for examples: -// https://developers.google.com/protocol-buffers/docs/proto#options -// If this turns out to be popular, a web service will be set up -// to automatically assign option numbers. - - -message FileOptions { - - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; - - - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - optional string java_outer_classname = 8; - - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default=false]; - - // This option does nothing. - optional bool java_generate_equals_and_hash = 20 [deprecated=true]; - - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default=false]; - - - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default=SPEED]; - - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - optional string go_package = 11; - - - - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - optional bool cc_generic_services = 16 [default=false]; - optional bool java_generic_services = 17 [default=false]; - optional bool py_generic_services = 18 [default=false]; - optional bool php_generic_services = 42 [default=false]; - - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default=false]; - - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default=false]; - - - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - optional string objc_class_prefix = 36; - - // Namespace for generated classes; defaults to the package. - optional string csharp_namespace = 37; - - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - optional string swift_prefix = 39; - - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - optional string php_class_prefix = 40; - - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - optional string php_namespace = 41; - - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. - // See the documentation for the "Options" section above. - extensions 1000 to max; - - reserved 38; -} - -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default=false]; - - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default=false]; - - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default=false]; - - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - optional bool map_entry = 7; - - reserved 8; // javalite_serializable - reserved 9; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; - - CORD = 1; - - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - optional bool packed = 2; - - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - optional JSType jstype = 6 [default = JS_NORMAL]; - enum JSType { - // Use the default type. - JS_NORMAL = 0; - - // Use JavaScript strings. - JS_STRING = 1; - - // Use JavaScript numbers. - JS_NUMBER = 2; - } - - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - optional bool lazy = 5 [default=false]; - - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default=false]; - - // For Google-internal migration only. Do not use. - optional bool weak = 10 [default=false]; - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - reserved 4; // removed jtype -} - -message OneofOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumOptions { - - // Set this option to true to allow mapping different tag names to the same - // value. - optional bool allow_alias = 2; - - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - optional bool deprecated = 3 [default=false]; - - reserved 5; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumValueOptions { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default=false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message ServiceOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - optional bool deprecated = 33 [default=false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MethodOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default=false]; - - // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, - // or neither? HTTP based RPC implementation may choose GET verb for safe - // methods, and PUT verb for idempotent methods instead of the default POST. - enum IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects - } - optional IdempotencyLevel idempotency_level = - 34 [default=IDEMPOTENCY_UNKNOWN]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; - - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; - optional string aggregate_value = 8; -} - -// =================================================================== -// Optional source code info - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -message SourceCodeInfo { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - repeated Location location = 1; - message Location { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - repeated int32 path = 1 [packed=true]; - - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - repeated int32 span = 2 [packed=true]; - - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - optional string leading_comments = 3; - optional string trailing_comments = 4; - repeated string leading_detached_comments = 6; - } -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -message GeneratedCodeInfo { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - repeated Annotation annotation = 1; - message Annotation { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed=true]; - - // Identifies the filesystem path to the original source .proto. - optional string source_file = 2; - - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - optional int32 begin = 3; - - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - optional int32 end = 4; - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/doc.go b/examples/github.com/golang/protobuf/protoc-gen-go/doc.go deleted file mode 100755 index 0d6055d..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/doc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* - A plugin for the Google protocol buffer compiler to generate Go code. - Run it by building this program and putting it in your path with the name - protoc-gen-go - That word 'go' at the end becomes part of the option string set for the - protocol compiler, so once the protocol compiler (protoc) is installed - you can run - protoc --go_out=output_directory input_directory/file.proto - to generate Go bindings for the protocol defined by file.proto. - With that input, the output will be written to - output_directory/file.pb.go - - The generated code is documented in the package comment for - the library. - - See the README and documentation for protocol buffers to learn more: - https://developers.google.com/protocol-buffers/ - -*/ -package documentation diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/generator/generator.go b/examples/github.com/golang/protobuf/protoc-gen-go/generator/generator.go deleted file mode 100755 index e0aba85..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/generator/generator.go +++ /dev/null @@ -1,2928 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* - The code generator for the plugin for the Google protocol buffer compiler. - It generates Go code from the protocol buffer description files read by the - main routine. -*/ -package generator - -import ( - "bufio" - "bytes" - "compress/gzip" - "crypto/sha256" - "encoding/hex" - "fmt" - "go/build" - "go/parser" - "go/printer" - "go/token" - "log" - "os" - "path" - "sort" - "strconv" - "strings" - "unicode" - "unicode/utf8" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/protoc-gen-go/generator/internal/remap" - - "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" -) - -// generatedCodeVersion indicates a version of the generated code. -// It is incremented whenever an incompatibility between the generated code and -// proto package is introduced; the generated code references -// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). -const generatedCodeVersion = 2 - -// A Plugin provides functionality to add to the output during Go code generation, -// such as to produce RPC stubs. -type Plugin interface { - // Name identifies the plugin. - Name() string - // Init is called once after data structures are built but before - // code generation begins. - Init(g *Generator) - // Generate produces the code generated by the plugin for this file, - // except for the imports, by calling the generator's methods P, In, and Out. - Generate(file *FileDescriptor) - // GenerateImports produces the import declarations for this file. - // It is called after Generate. - GenerateImports(file *FileDescriptor) -} - -var plugins []Plugin - -// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated. -// It is typically called during initialization. -func RegisterPlugin(p Plugin) { - plugins = append(plugins, p) -} - -// A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf". -type GoImportPath string - -func (p GoImportPath) String() string { return strconv.Quote(string(p)) } - -// A GoPackageName is the name of a Go package. e.g., "protobuf". -type GoPackageName string - -// Each type we import as a protocol buffer (other than FileDescriptorProto) needs -// a pointer to the FileDescriptorProto that represents it. These types achieve that -// wrapping by placing each Proto inside a struct with the pointer to its File. The -// structs have the same names as their contents, with "Proto" removed. -// FileDescriptor is used to store the things that it points to. - -// The file and package name method are common to messages and enums. -type common struct { - file *FileDescriptor // File this object comes from. -} - -// GoImportPath is the import path of the Go package containing the type. -func (c *common) GoImportPath() GoImportPath { - return c.file.importPath -} - -func (c *common) File() *FileDescriptor { return c.file } - -func fileIsProto3(file *descriptor.FileDescriptorProto) bool { - return file.GetSyntax() == "proto3" -} - -func (c *common) proto3() bool { return fileIsProto3(c.file.FileDescriptorProto) } - -// Descriptor represents a protocol buffer message. -type Descriptor struct { - common - *descriptor.DescriptorProto - parent *Descriptor // The containing message, if any. - nested []*Descriptor // Inner messages, if any. - enums []*EnumDescriptor // Inner enums, if any. - ext []*ExtensionDescriptor // Extensions, if any. - typename []string // Cached typename vector. - index int // The index into the container, whether the file or another message. - path string // The SourceCodeInfo path as comma-separated integers. - group bool -} - -// TypeName returns the elements of the dotted type name. -// The package name is not part of this name. -func (d *Descriptor) TypeName() []string { - if d.typename != nil { - return d.typename - } - n := 0 - for parent := d; parent != nil; parent = parent.parent { - n++ - } - s := make([]string, n) - for parent := d; parent != nil; parent = parent.parent { - n-- - s[n] = parent.GetName() - } - d.typename = s - return s -} - -// EnumDescriptor describes an enum. If it's at top level, its parent will be nil. -// Otherwise it will be the descriptor of the message in which it is defined. -type EnumDescriptor struct { - common - *descriptor.EnumDescriptorProto - parent *Descriptor // The containing message, if any. - typename []string // Cached typename vector. - index int // The index into the container, whether the file or a message. - path string // The SourceCodeInfo path as comma-separated integers. -} - -// TypeName returns the elements of the dotted type name. -// The package name is not part of this name. -func (e *EnumDescriptor) TypeName() (s []string) { - if e.typename != nil { - return e.typename - } - name := e.GetName() - if e.parent == nil { - s = make([]string, 1) - } else { - pname := e.parent.TypeName() - s = make([]string, len(pname)+1) - copy(s, pname) - } - s[len(s)-1] = name - e.typename = s - return s -} - -// Everything but the last element of the full type name, CamelCased. -// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . -func (e *EnumDescriptor) prefix() string { - if e.parent == nil { - // If the enum is not part of a message, the prefix is just the type name. - return CamelCase(*e.Name) + "_" - } - typeName := e.TypeName() - return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" -} - -// The integer value of the named constant in this enumerated type. -func (e *EnumDescriptor) integerValueAsString(name string) string { - for _, c := range e.Value { - if c.GetName() == name { - return fmt.Sprint(c.GetNumber()) - } - } - log.Fatal("cannot find value for enum constant") - return "" -} - -// ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. -// Otherwise it will be the descriptor of the message in which it is defined. -type ExtensionDescriptor struct { - common - *descriptor.FieldDescriptorProto - parent *Descriptor // The containing message, if any. -} - -// TypeName returns the elements of the dotted type name. -// The package name is not part of this name. -func (e *ExtensionDescriptor) TypeName() (s []string) { - name := e.GetName() - if e.parent == nil { - // top-level extension - s = make([]string, 1) - } else { - pname := e.parent.TypeName() - s = make([]string, len(pname)+1) - copy(s, pname) - } - s[len(s)-1] = name - return s -} - -// DescName returns the variable name used for the generated descriptor. -func (e *ExtensionDescriptor) DescName() string { - // The full type name. - typeName := e.TypeName() - // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. - for i, s := range typeName { - typeName[i] = CamelCase(s) - } - return "E_" + strings.Join(typeName, "_") -} - -// ImportedDescriptor describes a type that has been publicly imported from another file. -type ImportedDescriptor struct { - common - o Object -} - -func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() } - -// FileDescriptor describes an protocol buffer descriptor file (.proto). -// It includes slices of all the messages and enums defined within it. -// Those slices are constructed by WrapTypes. -type FileDescriptor struct { - *descriptor.FileDescriptorProto - desc []*Descriptor // All the messages defined in this file. - enum []*EnumDescriptor // All the enums defined in this file. - ext []*ExtensionDescriptor // All the top-level extensions defined in this file. - imp []*ImportedDescriptor // All types defined in files publicly imported by this file. - - // Comments, stored as a map of path (comma-separated integers) to the comment. - comments map[string]*descriptor.SourceCodeInfo_Location - - // The full list of symbols that are exported, - // as a map from the exported object to its symbols. - // This is used for supporting public imports. - exported map[Object][]symbol - - fingerprint string // Fingerprint of this file's contents. - importPath GoImportPath // Import path of this file's package. - packageName GoPackageName // Name of this file's Go package. - - proto3 bool // whether to generate proto3 code for this file -} - -// VarName is the variable name we'll use in the generated code to refer -// to the compressed bytes of this descriptor. It is not exported, so -// it is only valid inside the generated package. -func (d *FileDescriptor) VarName() string { - name := strings.Map(badToUnderscore, baseName(d.GetName())) - return fmt.Sprintf("fileDescriptor_%s_%s", name, d.fingerprint) -} - -// goPackageOption interprets the file's go_package option. -// If there is no go_package, it returns ("", "", false). -// If there's a simple name, it returns ("", pkg, true). -// If the option implies an import path, it returns (impPath, pkg, true). -func (d *FileDescriptor) goPackageOption() (impPath GoImportPath, pkg GoPackageName, ok bool) { - opt := d.GetOptions().GetGoPackage() - if opt == "" { - return "", "", false - } - // A semicolon-delimited suffix delimits the import path and package name. - sc := strings.Index(opt, ";") - if sc >= 0 { - return GoImportPath(opt[:sc]), cleanPackageName(opt[sc+1:]), true - } - // The presence of a slash implies there's an import path. - slash := strings.LastIndex(opt, "/") - if slash >= 0 { - return GoImportPath(opt), cleanPackageName(opt[slash+1:]), true - } - return "", cleanPackageName(opt), true -} - -// goFileName returns the output name for the generated Go file. -func (d *FileDescriptor) goFileName(pathType pathType) string { - name := *d.Name - if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" { - name = name[:len(name)-len(ext)] - } - name += ".pb.go" - - if pathType == pathTypeSourceRelative { - return name - } - - // Does the file have a "go_package" option? - // If it does, it may override the filename. - if impPath, _, ok := d.goPackageOption(); ok && impPath != "" { - // Replace the existing dirname with the declared import path. - _, name = path.Split(name) - name = path.Join(string(impPath), name) - return name - } - - return name -} - -func (d *FileDescriptor) addExport(obj Object, sym symbol) { - d.exported[obj] = append(d.exported[obj], sym) -} - -// symbol is an interface representing an exported Go symbol. -type symbol interface { - // GenerateAlias should generate an appropriate alias - // for the symbol from the named package. - GenerateAlias(g *Generator, pkg GoPackageName) -} - -type messageSymbol struct { - sym string - hasExtensions, isMessageSet bool - oneofTypes []string -} - -type getterSymbol struct { - name string - typ string - typeName string // canonical name in proto world; empty for proto.Message and similar - genType bool // whether typ contains a generated type (message/group/enum) -} - -func (ms *messageSymbol) GenerateAlias(g *Generator, pkg GoPackageName) { - g.P("type ", ms.sym, " = ", pkg, ".", ms.sym) - for _, name := range ms.oneofTypes { - g.P("type ", name, " = ", pkg, ".", name) - } -} - -type enumSymbol struct { - name string - proto3 bool // Whether this came from a proto3 file. -} - -func (es enumSymbol) GenerateAlias(g *Generator, pkg GoPackageName) { - s := es.name - g.P("type ", s, " = ", pkg, ".", s) - g.P("var ", s, "_name = ", pkg, ".", s, "_name") - g.P("var ", s, "_value = ", pkg, ".", s, "_value") -} - -type constOrVarSymbol struct { - sym string - typ string // either "const" or "var" - cast string // if non-empty, a type cast is required (used for enums) -} - -func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg GoPackageName) { - v := string(pkg) + "." + cs.sym - if cs.cast != "" { - v = cs.cast + "(" + v + ")" - } - g.P(cs.typ, " ", cs.sym, " = ", v) -} - -// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects. -type Object interface { - GoImportPath() GoImportPath - TypeName() []string - File() *FileDescriptor -} - -// Generator is the type whose methods generate the output, stored in the associated response structure. -type Generator struct { - *bytes.Buffer - - Request *plugin.CodeGeneratorRequest // The input. - Response *plugin.CodeGeneratorResponse // The output. - - Param map[string]string // Command-line parameters. - PackageImportPath string // Go import path of the package we're generating code for - ImportPrefix string // String to prefix to imported package file names. - ImportMap map[string]string // Mapping from .proto file name to import path - - Pkg map[string]string // The names under which we import support packages - - outputImportPath GoImportPath // Package we're generating code for. - allFiles []*FileDescriptor // All files in the tree - allFilesByName map[string]*FileDescriptor // All files by filename. - genFiles []*FileDescriptor // Those files we will generate output for. - file *FileDescriptor // The file we are compiling now. - packageNames map[GoImportPath]GoPackageName // Imported package names in the current file. - usedPackages map[GoImportPath]bool // Packages used in current file. - usedPackageNames map[GoPackageName]bool // Package names used in the current file. - typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. - init []string // Lines to emit in the init function. - indent string - pathType pathType // How to generate output filenames. - writeOutput bool - annotateCode bool // whether to store annotations - annotations []*descriptor.GeneratedCodeInfo_Annotation // annotations to store -} - -type pathType int - -const ( - pathTypeImport pathType = iota - pathTypeSourceRelative -) - -// New creates a new generator and allocates the request and response protobufs. -func New() *Generator { - g := new(Generator) - g.Buffer = new(bytes.Buffer) - g.Request = new(plugin.CodeGeneratorRequest) - g.Response = new(plugin.CodeGeneratorResponse) - return g -} - -// Error reports a problem, including an error, and exits the program. -func (g *Generator) Error(err error, msgs ...string) { - s := strings.Join(msgs, " ") + ":" + err.Error() - log.Print("protoc-gen-go: error:", s) - os.Exit(1) -} - -// Fail reports a problem and exits the program. -func (g *Generator) Fail(msgs ...string) { - s := strings.Join(msgs, " ") - log.Print("protoc-gen-go: error:", s) - os.Exit(1) -} - -// CommandLineParameters breaks the comma-separated list of key=value pairs -// in the parameter (a member of the request protobuf) into a key/value map. -// It then sets file name mappings defined by those entries. -func (g *Generator) CommandLineParameters(parameter string) { - g.Param = make(map[string]string) - for _, p := range strings.Split(parameter, ",") { - if i := strings.Index(p, "="); i < 0 { - g.Param[p] = "" - } else { - g.Param[p[0:i]] = p[i+1:] - } - } - - g.ImportMap = make(map[string]string) - pluginList := "none" // Default list of plugin names to enable (empty means all). - for k, v := range g.Param { - switch k { - case "import_prefix": - g.ImportPrefix = v - case "import_path": - g.PackageImportPath = v - case "paths": - switch v { - case "import": - g.pathType = pathTypeImport - case "source_relative": - g.pathType = pathTypeSourceRelative - default: - g.Fail(fmt.Sprintf(`Unknown path type %q: want "import" or "source_relative".`, v)) - } - case "plugins": - pluginList = v - case "annotate_code": - if v == "true" { - g.annotateCode = true - } - default: - if len(k) > 0 && k[0] == 'M' { - g.ImportMap[k[1:]] = v - } - } - } - if pluginList != "" { - // Amend the set of plugins. - enabled := make(map[string]bool) - for _, name := range strings.Split(pluginList, "+") { - enabled[name] = true - } - var nplugins []Plugin - for _, p := range plugins { - if enabled[p.Name()] { - nplugins = append(nplugins, p) - } - } - plugins = nplugins - } -} - -// DefaultPackageName returns the package name printed for the object. -// If its file is in a different package, it returns the package name we're using for this file, plus ".". -// Otherwise it returns the empty string. -func (g *Generator) DefaultPackageName(obj Object) string { - importPath := obj.GoImportPath() - if importPath == g.outputImportPath { - return "" - } - return string(g.GoPackageName(importPath)) + "." -} - -// GoPackageName returns the name used for a package. -func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName { - if name, ok := g.packageNames[importPath]; ok { - return name - } - name := cleanPackageName(baseName(string(importPath))) - for i, orig := 1, name; g.usedPackageNames[name]; i++ { - name = orig + GoPackageName(strconv.Itoa(i)) - } - g.packageNames[importPath] = name - g.usedPackageNames[name] = true - return name -} - -var globalPackageNames = map[GoPackageName]bool{ - "fmt": true, - "math": true, - "proto": true, -} - -// Create and remember a guaranteed unique package name. Pkg is the candidate name. -// The FileDescriptor parameter is unused. -func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { - name := cleanPackageName(pkg) - for i, orig := 1, name; globalPackageNames[name]; i++ { - name = orig + GoPackageName(strconv.Itoa(i)) - } - globalPackageNames[name] = true - return string(name) -} - -var isGoKeyword = map[string]bool{ - "break": true, - "case": true, - "chan": true, - "const": true, - "continue": true, - "default": true, - "else": true, - "defer": true, - "fallthrough": true, - "for": true, - "func": true, - "go": true, - "goto": true, - "if": true, - "import": true, - "interface": true, - "map": true, - "package": true, - "range": true, - "return": true, - "select": true, - "struct": true, - "switch": true, - "type": true, - "var": true, -} - -func cleanPackageName(name string) GoPackageName { - name = strings.Map(badToUnderscore, name) - // Identifier must not be keyword: insert _. - if isGoKeyword[name] { - name = "_" + name - } - // Identifier must not begin with digit: insert _. - if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) { - name = "_" + name - } - return GoPackageName(name) -} - -// defaultGoPackage returns the package name to use, -// derived from the import path of the package we're building code for. -func (g *Generator) defaultGoPackage() GoPackageName { - p := g.PackageImportPath - if i := strings.LastIndex(p, "/"); i >= 0 { - p = p[i+1:] - } - return cleanPackageName(p) -} - -// SetPackageNames sets the package name for this run. -// The package name must agree across all files being generated. -// It also defines unique package names for all imported files. -func (g *Generator) SetPackageNames() { - g.outputImportPath = g.genFiles[0].importPath - - defaultPackageNames := make(map[GoImportPath]GoPackageName) - for _, f := range g.genFiles { - if _, p, ok := f.goPackageOption(); ok { - defaultPackageNames[f.importPath] = p - } - } - for _, f := range g.genFiles { - if _, p, ok := f.goPackageOption(); ok { - // Source file: option go_package = "quux/bar"; - f.packageName = p - } else if p, ok := defaultPackageNames[f.importPath]; ok { - // A go_package option in another file in the same package. - // - // This is a poor choice in general, since every source file should - // contain a go_package option. Supported mainly for historical - // compatibility. - f.packageName = p - } else if p := g.defaultGoPackage(); p != "" { - // Command-line: import_path=quux/bar. - // - // The import_path flag sets a package name for files which don't - // contain a go_package option. - f.packageName = p - } else if p := f.GetPackage(); p != "" { - // Source file: package quux.bar; - f.packageName = cleanPackageName(p) - } else { - // Source filename. - f.packageName = cleanPackageName(baseName(f.GetName())) - } - } - - // Check that all files have a consistent package name and import path. - for _, f := range g.genFiles[1:] { - if a, b := g.genFiles[0].importPath, f.importPath; a != b { - g.Fail(fmt.Sprintf("inconsistent package import paths: %v, %v", a, b)) - } - if a, b := g.genFiles[0].packageName, f.packageName; a != b { - g.Fail(fmt.Sprintf("inconsistent package names: %v, %v", a, b)) - } - } - - // Names of support packages. These never vary (if there are conflicts, - // we rename the conflicting package), so this could be removed someday. - g.Pkg = map[string]string{ - "fmt": "fmt", - "math": "math", - "proto": "proto", - } -} - -// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos -// and FileDescriptorProtos into file-referenced objects within the Generator. -// It also creates the list of files to generate and so should be called before GenerateAllFiles. -func (g *Generator) WrapTypes() { - g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile)) - g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles)) - genFileNames := make(map[string]bool) - for _, n := range g.Request.FileToGenerate { - genFileNames[n] = true - } - for _, f := range g.Request.ProtoFile { - fd := &FileDescriptor{ - FileDescriptorProto: f, - exported: make(map[Object][]symbol), - proto3: fileIsProto3(f), - } - // The import path may be set in a number of ways. - if substitution, ok := g.ImportMap[f.GetName()]; ok { - // Command-line: M=foo.proto=quux/bar. - // - // Explicit mapping of source file to import path. - fd.importPath = GoImportPath(substitution) - } else if genFileNames[f.GetName()] && g.PackageImportPath != "" { - // Command-line: import_path=quux/bar. - // - // The import_path flag sets the import path for every file that - // we generate code for. - fd.importPath = GoImportPath(g.PackageImportPath) - } else if p, _, _ := fd.goPackageOption(); p != "" { - // Source file: option go_package = "quux/bar"; - // - // The go_package option sets the import path. Most users should use this. - fd.importPath = p - } else { - // Source filename. - // - // Last resort when nothing else is available. - fd.importPath = GoImportPath(path.Dir(f.GetName())) - } - // We must wrap the descriptors before we wrap the enums - fd.desc = wrapDescriptors(fd) - g.buildNestedDescriptors(fd.desc) - fd.enum = wrapEnumDescriptors(fd, fd.desc) - g.buildNestedEnums(fd.desc, fd.enum) - fd.ext = wrapExtensions(fd) - extractComments(fd) - g.allFiles = append(g.allFiles, fd) - g.allFilesByName[f.GetName()] = fd - } - for _, fd := range g.allFiles { - fd.imp = wrapImported(fd, g) - } - - g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate)) - for _, fileName := range g.Request.FileToGenerate { - fd := g.allFilesByName[fileName] - if fd == nil { - g.Fail("could not find file named", fileName) - } - fingerprint, err := fingerprintProto(fd.FileDescriptorProto) - if err != nil { - g.Error(err) - } - fd.fingerprint = fingerprint - g.genFiles = append(g.genFiles, fd) - } -} - -// fingerprintProto returns a fingerprint for a message. -// The fingerprint is intended to prevent conflicts between generated fileds, -// not to provide cryptographic security. -func fingerprintProto(m proto.Message) (string, error) { - b, err := proto.Marshal(m) - if err != nil { - return "", err - } - h := sha256.Sum256(b) - return hex.EncodeToString(h[:8]), nil -} - -// Scan the descriptors in this file. For each one, build the slice of nested descriptors -func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { - for _, desc := range descs { - if len(desc.NestedType) != 0 { - for _, nest := range descs { - if nest.parent == desc { - desc.nested = append(desc.nested, nest) - } - } - if len(desc.nested) != len(desc.NestedType) { - g.Fail("internal error: nesting failure for", desc.GetName()) - } - } - } -} - -func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) { - for _, desc := range descs { - if len(desc.EnumType) != 0 { - for _, enum := range enums { - if enum.parent == desc { - desc.enums = append(desc.enums, enum) - } - } - if len(desc.enums) != len(desc.EnumType) { - g.Fail("internal error: enum nesting failure for", desc.GetName()) - } - } - } -} - -// Construct the Descriptor -func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *Descriptor { - d := &Descriptor{ - common: common{file}, - DescriptorProto: desc, - parent: parent, - index: index, - } - if parent == nil { - d.path = fmt.Sprintf("%d,%d", messagePath, index) - } else { - d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) - } - - // The only way to distinguish a group from a message is whether - // the containing message has a TYPE_GROUP field that matches. - if parent != nil { - parts := d.TypeName() - if file.Package != nil { - parts = append([]string{*file.Package}, parts...) - } - exp := "." + strings.Join(parts, ".") - for _, field := range parent.Field { - if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp { - d.group = true - break - } - } - } - - for _, field := range desc.Extension { - d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d}) - } - - return d -} - -// Return a slice of all the Descriptors defined within this file -func wrapDescriptors(file *FileDescriptor) []*Descriptor { - sl := make([]*Descriptor, 0, len(file.MessageType)+10) - for i, desc := range file.MessageType { - sl = wrapThisDescriptor(sl, desc, nil, file, i) - } - return sl -} - -// Wrap this Descriptor, recursively -func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) []*Descriptor { - sl = append(sl, newDescriptor(desc, parent, file, index)) - me := sl[len(sl)-1] - for i, nested := range desc.NestedType { - sl = wrapThisDescriptor(sl, nested, me, file, i) - } - return sl -} - -// Construct the EnumDescriptor -func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *EnumDescriptor { - ed := &EnumDescriptor{ - common: common{file}, - EnumDescriptorProto: desc, - parent: parent, - index: index, - } - if parent == nil { - ed.path = fmt.Sprintf("%d,%d", enumPath, index) - } else { - ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) - } - return ed -} - -// Return a slice of all the EnumDescriptors defined within this file -func wrapEnumDescriptors(file *FileDescriptor, descs []*Descriptor) []*EnumDescriptor { - sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) - // Top-level enums. - for i, enum := range file.EnumType { - sl = append(sl, newEnumDescriptor(enum, nil, file, i)) - } - // Enums within messages. Enums within embedded messages appear in the outer-most message. - for _, nested := range descs { - for i, enum := range nested.EnumType { - sl = append(sl, newEnumDescriptor(enum, nested, file, i)) - } - } - return sl -} - -// Return a slice of all the top-level ExtensionDescriptors defined within this file. -func wrapExtensions(file *FileDescriptor) []*ExtensionDescriptor { - var sl []*ExtensionDescriptor - for _, field := range file.Extension { - sl = append(sl, &ExtensionDescriptor{common{file}, field, nil}) - } - return sl -} - -// Return a slice of all the types that are publicly imported into this file. -func wrapImported(file *FileDescriptor, g *Generator) (sl []*ImportedDescriptor) { - for _, index := range file.PublicDependency { - df := g.fileByName(file.Dependency[index]) - for _, d := range df.desc { - if d.GetOptions().GetMapEntry() { - continue - } - sl = append(sl, &ImportedDescriptor{common{file}, d}) - } - for _, e := range df.enum { - sl = append(sl, &ImportedDescriptor{common{file}, e}) - } - for _, ext := range df.ext { - sl = append(sl, &ImportedDescriptor{common{file}, ext}) - } - } - return -} - -func extractComments(file *FileDescriptor) { - file.comments = make(map[string]*descriptor.SourceCodeInfo_Location) - for _, loc := range file.GetSourceCodeInfo().GetLocation() { - if loc.LeadingComments == nil { - continue - } - var p []string - for _, n := range loc.Path { - p = append(p, strconv.Itoa(int(n))) - } - file.comments[strings.Join(p, ",")] = loc - } -} - -// BuildTypeNameMap builds the map from fully qualified type names to objects. -// The key names for the map come from the input data, which puts a period at the beginning. -// It should be called after SetPackageNames and before GenerateAllFiles. -func (g *Generator) BuildTypeNameMap() { - g.typeNameToObject = make(map[string]Object) - for _, f := range g.allFiles { - // The names in this loop are defined by the proto world, not us, so the - // package name may be empty. If so, the dotted package name of X will - // be ".X"; otherwise it will be ".pkg.X". - dottedPkg := "." + f.GetPackage() - if dottedPkg != "." { - dottedPkg += "." - } - for _, enum := range f.enum { - name := dottedPkg + dottedSlice(enum.TypeName()) - g.typeNameToObject[name] = enum - } - for _, desc := range f.desc { - name := dottedPkg + dottedSlice(desc.TypeName()) - g.typeNameToObject[name] = desc - } - } -} - -// ObjectNamed, given a fully-qualified input type name as it appears in the input data, -// returns the descriptor for the message or enum with that name. -func (g *Generator) ObjectNamed(typeName string) Object { - o, ok := g.typeNameToObject[typeName] - if !ok { - g.Fail("can't find object with type", typeName) - } - - // If the file of this object isn't a direct dependency of the current file, - // or in the current file, then this object has been publicly imported into - // a dependency of the current file. - // We should return the ImportedDescriptor object for it instead. - direct := *o.File().Name == *g.file.Name - if !direct { - for _, dep := range g.file.Dependency { - if *g.fileByName(dep).Name == *o.File().Name { - direct = true - break - } - } - } - if !direct { - found := false - Loop: - for _, dep := range g.file.Dependency { - df := g.fileByName(*g.fileByName(dep).Name) - for _, td := range df.imp { - if td.o == o { - // Found it! - o = td - found = true - break Loop - } - } - } - if !found { - log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name) - } - } - - return o -} - -// AnnotatedAtoms is a list of atoms (as consumed by P) that records the file name and proto AST path from which they originated. -type AnnotatedAtoms struct { - source string - path string - atoms []interface{} -} - -// Annotate records the file name and proto AST path of a list of atoms -// so that a later call to P can emit a link from each atom to its origin. -func Annotate(file *FileDescriptor, path string, atoms ...interface{}) *AnnotatedAtoms { - return &AnnotatedAtoms{source: *file.Name, path: path, atoms: atoms} -} - -// printAtom prints the (atomic, non-annotation) argument to the generated output. -func (g *Generator) printAtom(v interface{}) { - switch v := v.(type) { - case string: - g.WriteString(v) - case *string: - g.WriteString(*v) - case bool: - fmt.Fprint(g, v) - case *bool: - fmt.Fprint(g, *v) - case int: - fmt.Fprint(g, v) - case *int32: - fmt.Fprint(g, *v) - case *int64: - fmt.Fprint(g, *v) - case float64: - fmt.Fprint(g, v) - case *float64: - fmt.Fprint(g, *v) - case GoPackageName: - g.WriteString(string(v)) - case GoImportPath: - g.WriteString(strconv.Quote(string(v))) - default: - g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) - } -} - -// P prints the arguments to the generated output. It handles strings and int32s, plus -// handling indirections because they may be *string, etc. Any inputs of type AnnotatedAtoms may emit -// annotations in a .meta file in addition to outputting the atoms themselves (if g.annotateCode -// is true). -func (g *Generator) P(str ...interface{}) { - if !g.writeOutput { - return - } - g.WriteString(g.indent) - for _, v := range str { - switch v := v.(type) { - case *AnnotatedAtoms: - begin := int32(g.Len()) - for _, v := range v.atoms { - g.printAtom(v) - } - if g.annotateCode { - end := int32(g.Len()) - var path []int32 - for _, token := range strings.Split(v.path, ",") { - val, err := strconv.ParseInt(token, 10, 32) - if err != nil { - g.Fail("could not parse proto AST path: ", err.Error()) - } - path = append(path, int32(val)) - } - g.annotations = append(g.annotations, &descriptor.GeneratedCodeInfo_Annotation{ - Path: path, - SourceFile: &v.source, - Begin: &begin, - End: &end, - }) - } - default: - g.printAtom(v) - } - } - g.WriteByte('\n') -} - -// addInitf stores the given statement to be printed inside the file's init function. -// The statement is given as a format specifier and arguments. -func (g *Generator) addInitf(stmt string, a ...interface{}) { - g.init = append(g.init, fmt.Sprintf(stmt, a...)) -} - -// In Indents the output one tab stop. -func (g *Generator) In() { g.indent += "\t" } - -// Out unindents the output one tab stop. -func (g *Generator) Out() { - if len(g.indent) > 0 { - g.indent = g.indent[1:] - } -} - -// GenerateAllFiles generates the output for all the files we're outputting. -func (g *Generator) GenerateAllFiles() { - // Initialize the plugins - for _, p := range plugins { - p.Init(g) - } - // Generate the output. The generator runs for every file, even the files - // that we don't generate output for, so that we can collate the full list - // of exported symbols to support public imports. - genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) - for _, file := range g.genFiles { - genFileMap[file] = true - } - for _, file := range g.allFiles { - g.Reset() - g.annotations = nil - g.writeOutput = genFileMap[file] - g.generate(file) - if !g.writeOutput { - continue - } - fname := file.goFileName(g.pathType) - g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ - Name: proto.String(fname), - Content: proto.String(g.String()), - }) - if g.annotateCode { - // Store the generated code annotations in text, as the protoc plugin protocol requires that - // strings contain valid UTF-8. - g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ - Name: proto.String(file.goFileName(g.pathType) + ".meta"), - Content: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})), - }) - } - } -} - -// Run all the plugins associated with the file. -func (g *Generator) runPlugins(file *FileDescriptor) { - for _, p := range plugins { - p.Generate(file) - } -} - -// Fill the response protocol buffer with the generated output for all the files we're -// supposed to generate. -func (g *Generator) generate(file *FileDescriptor) { - g.file = file - g.usedPackages = make(map[GoImportPath]bool) - g.packageNames = make(map[GoImportPath]GoPackageName) - g.usedPackageNames = make(map[GoPackageName]bool) - for name := range globalPackageNames { - g.usedPackageNames[name] = true - } - - g.P("// This is a compile-time assertion to ensure that this generated file") - g.P("// is compatible with the proto package it is being compiled against.") - g.P("// A compilation error at this line likely means your copy of the") - g.P("// proto package needs to be updated.") - g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion, " // please upgrade the proto package") - g.P() - - for _, td := range g.file.imp { - g.generateImported(td) - } - for _, enum := range g.file.enum { - g.generateEnum(enum) - } - for _, desc := range g.file.desc { - // Don't generate virtual messages for maps. - if desc.GetOptions().GetMapEntry() { - continue - } - g.generateMessage(desc) - } - for _, ext := range g.file.ext { - g.generateExtension(ext) - } - g.generateInitFunction() - - // Run the plugins before the imports so we know which imports are necessary. - g.runPlugins(file) - - g.generateFileDescriptor(file) - - // Generate header and imports last, though they appear first in the output. - rem := g.Buffer - remAnno := g.annotations - g.Buffer = new(bytes.Buffer) - g.annotations = nil - g.generateHeader() - g.generateImports() - if !g.writeOutput { - return - } - // Adjust the offsets for annotations displaced by the header and imports. - for _, anno := range remAnno { - *anno.Begin += int32(g.Len()) - *anno.End += int32(g.Len()) - g.annotations = append(g.annotations, anno) - } - g.Write(rem.Bytes()) - - // Reformat generated code and patch annotation locations. - fset := token.NewFileSet() - original := g.Bytes() - if g.annotateCode { - // make a copy independent of g; we'll need it after Reset. - original = append([]byte(nil), original...) - } - ast, err := parser.ParseFile(fset, "", original, parser.ParseComments) - if err != nil { - // Print out the bad code with line numbers. - // This should never happen in practice, but it can while changing generated code, - // so consider this a debugging aid. - var src bytes.Buffer - s := bufio.NewScanner(bytes.NewReader(original)) - for line := 1; s.Scan(); line++ { - fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) - } - g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String()) - } - g.Reset() - err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) - if err != nil { - g.Fail("generated Go source code could not be reformatted:", err.Error()) - } - if g.annotateCode { - m, err := remap.Compute(original, g.Bytes()) - if err != nil { - g.Fail("formatted generated Go source code could not be mapped back to the original code:", err.Error()) - } - for _, anno := range g.annotations { - new, ok := m.Find(int(*anno.Begin), int(*anno.End)) - if !ok { - g.Fail("span in formatted generated Go source code could not be mapped back to the original code") - } - *anno.Begin = int32(new.Pos) - *anno.End = int32(new.End) - } - } -} - -// Generate the header, including package definition -func (g *Generator) generateHeader() { - g.P("// Code generated by protoc-gen-go. DO NOT EDIT.") - if g.file.GetOptions().GetDeprecated() { - g.P("// ", g.file.Name, " is a deprecated file.") - } else { - g.P("// source: ", g.file.Name) - } - g.P() - - importPath, _, _ := g.file.goPackageOption() - if importPath == "" { - g.P("package ", g.file.packageName) - } else { - g.P("package ", g.file.packageName, " // import ", GoImportPath(g.ImportPrefix)+importPath) - } - g.P() - - if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok { - g.P("/*") - // not using g.PrintComments because this is a /* */ comment block. - text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") - for _, line := range strings.Split(text, "\n") { - line = strings.TrimPrefix(line, " ") - // ensure we don't escape from the block comment - line = strings.Replace(line, "*/", "* /", -1) - g.P(line) - } - g.P("*/") - g.P() - } -} - -// deprecationComment is the standard comment added to deprecated -// messages, fields, enums, and enum values. -var deprecationComment = "// Deprecated: Do not use." - -// PrintComments prints any comments from the source .proto file. -// The path is a comma-separated list of integers. -// It returns an indication of whether any comments were printed. -// See descriptor.proto for its format. -func (g *Generator) PrintComments(path string) bool { - if !g.writeOutput { - return false - } - if loc, ok := g.file.comments[path]; ok { - text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") - for _, line := range strings.Split(text, "\n") { - g.P("// ", strings.TrimPrefix(line, " ")) - } - return true - } - return false -} - -func (g *Generator) fileByName(filename string) *FileDescriptor { - return g.allFilesByName[filename] -} - -// weak returns whether the ith import of the current file is a weak import. -func (g *Generator) weak(i int32) bool { - for _, j := range g.file.WeakDependency { - if j == i { - return true - } - } - return false -} - -// Generate the imports -func (g *Generator) generateImports() { - // We almost always need a proto import. Rather than computing when we - // do, which is tricky when there's a plugin, just import it and - // reference it later. The same argument applies to the fmt and math packages. - g.P("import "+g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto") - g.P("import " + g.Pkg["fmt"] + ` "fmt"`) - g.P("import " + g.Pkg["math"] + ` "math"`) - var ( - imports = make(map[GoImportPath]bool) - strongImports = make(map[GoImportPath]bool) - importPaths []string - ) - for i, s := range g.file.Dependency { - fd := g.fileByName(s) - importPath := fd.importPath - // Do not import our own package. - if importPath == g.file.importPath { - continue - } - if !imports[importPath] { - importPaths = append(importPaths, string(importPath)) - } - imports[importPath] = true - if !g.weak(int32(i)) { - strongImports[importPath] = true - } - } - sort.Strings(importPaths) - for i := range importPaths { - importPath := GoImportPath(importPaths[i]) - packageName := g.GoPackageName(importPath) - fullPath := GoImportPath(g.ImportPrefix) + importPath - // Skip weak imports. - if !strongImports[importPath] { - g.P("// skipping weak import ", packageName, " ", fullPath) - continue - } - // We need to import all the dependencies, even if we don't reference them, - // because other code and tools depend on having the full transitive closure - // of protocol buffer types in the binary. - if _, ok := g.usedPackages[importPath]; !ok { - packageName = "_" - } - g.P("import ", packageName, " ", fullPath) - } - g.P() - // TODO: may need to worry about uniqueness across plugins - for _, p := range plugins { - p.GenerateImports(g.file) - g.P() - } - g.P("// Reference imports to suppress errors if they are not otherwise used.") - g.P("var _ = ", g.Pkg["proto"], ".Marshal") - g.P("var _ = ", g.Pkg["fmt"], ".Errorf") - g.P("var _ = ", g.Pkg["math"], ".Inf") - g.P() -} - -func (g *Generator) generateImported(id *ImportedDescriptor) { - tn := id.TypeName() - sn := tn[len(tn)-1] - df := id.o.File() - filename := *df.Name - if df.importPath == g.file.importPath { - // Don't generate type aliases for files in the same Go package as this one. - g.P("// Ignoring public import of ", sn, " from ", filename) - g.P() - return - } - if !supportTypeAliases { - g.Fail(fmt.Sprintf("%s: public imports require at least go1.9", filename)) - } - g.P("// ", sn, " from public import ", filename) - g.usedPackages[df.importPath] = true - - for _, sym := range df.exported[id.o] { - sym.GenerateAlias(g, g.GoPackageName(df.importPath)) - } - - g.P() -} - -// Generate the enum definitions for this EnumDescriptor. -func (g *Generator) generateEnum(enum *EnumDescriptor) { - // The full type name - typeName := enum.TypeName() - // The full type name, CamelCased. - ccTypeName := CamelCaseSlice(typeName) - ccPrefix := enum.prefix() - - deprecatedEnum := "" - if enum.GetOptions().GetDeprecated() { - deprecatedEnum = deprecationComment - } - g.PrintComments(enum.path) - g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum) - g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()}) - g.P("const (") - g.In() - for i, e := range enum.Value { - etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i) - g.PrintComments(etorPath) - - deprecatedValue := "" - if e.GetOptions().GetDeprecated() { - deprecatedValue = deprecationComment - } - - name := ccPrefix + *e.Name - g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue) - g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName}) - } - g.Out() - g.P(")") - g.P("var ", ccTypeName, "_name = map[int32]string{") - g.In() - generated := make(map[int32]bool) // avoid duplicate values - for _, e := range enum.Value { - duplicate := "" - if _, present := generated[*e.Number]; present { - duplicate = "// Duplicate value: " - } - g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",") - generated[*e.Number] = true - } - g.Out() - g.P("}") - g.P("var ", ccTypeName, "_value = map[string]int32{") - g.In() - for _, e := range enum.Value { - g.P(strconv.Quote(*e.Name), ": ", e.Number, ",") - } - g.Out() - g.P("}") - - if !enum.proto3() { - g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {") - g.In() - g.P("p := new(", ccTypeName, ")") - g.P("*p = x") - g.P("return p") - g.Out() - g.P("}") - } - - g.P("func (x ", ccTypeName, ") String() string {") - g.In() - g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))") - g.Out() - g.P("}") - - if !enum.proto3() { - g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {") - g.In() - g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`) - g.P("if err != nil {") - g.In() - g.P("return err") - g.Out() - g.P("}") - g.P("*x = ", ccTypeName, "(value)") - g.P("return nil") - g.Out() - g.P("}") - } - - var indexes []string - for m := enum.parent; m != nil; m = m.parent { - // XXX: skip groups? - indexes = append([]string{strconv.Itoa(m.index)}, indexes...) - } - indexes = append(indexes, strconv.Itoa(enum.index)) - g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {") - g.In() - g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}") - g.Out() - g.P("}") - if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" { - g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`) - } - - g.P() -} - -// The tag is a string like "varint,2,opt,name=fieldname,def=7" that -// identifies details of the field for the protocol buffer marshaling and unmarshaling -// code. The fields are: -// wire encoding -// protocol tag number -// opt,req,rep for optional, required, or repeated -// packed whether the encoding is "packed" (optional; repeated primitives only) -// name= the original declared name -// enum= the name of the enum type if it is an enum-typed field. -// proto3 if this field is in a proto3 message -// def= string representation of the default value, if any. -// The default value must be in a representation that can be used at run-time -// to generate the default value. Thus bools become 0 and 1, for instance. -func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string { - optrepreq := "" - switch { - case isOptional(field): - optrepreq = "opt" - case isRequired(field): - optrepreq = "req" - case isRepeated(field): - optrepreq = "rep" - } - var defaultValue string - if dv := field.DefaultValue; dv != nil { // set means an explicit default - defaultValue = *dv - // Some types need tweaking. - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_BOOL: - if defaultValue == "true" { - defaultValue = "1" - } else { - defaultValue = "0" - } - case descriptor.FieldDescriptorProto_TYPE_STRING, - descriptor.FieldDescriptorProto_TYPE_BYTES: - // Nothing to do. Quoting is done for the whole tag. - case descriptor.FieldDescriptorProto_TYPE_ENUM: - // For enums we need to provide the integer constant. - obj := g.ObjectNamed(field.GetTypeName()) - if id, ok := obj.(*ImportedDescriptor); ok { - // It is an enum that was publicly imported. - // We need the underlying type. - obj = id.o - } - enum, ok := obj.(*EnumDescriptor) - if !ok { - log.Printf("obj is a %T", obj) - if id, ok := obj.(*ImportedDescriptor); ok { - log.Printf("id.o is a %T", id.o) - } - g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName())) - } - defaultValue = enum.integerValueAsString(defaultValue) - } - defaultValue = ",def=" + defaultValue - } - enum := "" - if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { - // We avoid using obj.GoPackageName(), because we want to use the - // original (proto-world) package name. - obj := g.ObjectNamed(field.GetTypeName()) - if id, ok := obj.(*ImportedDescriptor); ok { - obj = id.o - } - enum = ",enum=" - if pkg := obj.File().GetPackage(); pkg != "" { - enum += pkg + "." - } - enum += CamelCaseSlice(obj.TypeName()) - } - packed := "" - if (field.Options != nil && field.Options.GetPacked()) || - // Per https://developers.google.com/protocol-buffers/docs/proto3#simple: - // "In proto3, repeated fields of scalar numeric types use packed encoding by default." - (message.proto3() && (field.Options == nil || field.Options.Packed == nil) && - isRepeated(field) && isScalar(field)) { - packed = ",packed" - } - fieldName := field.GetName() - name := fieldName - if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { - // We must use the type name for groups instead of - // the field name to preserve capitalization. - // type_name in FieldDescriptorProto is fully-qualified, - // but we only want the local part. - name = *field.TypeName - if i := strings.LastIndex(name, "."); i >= 0 { - name = name[i+1:] - } - } - if json := field.GetJsonName(); json != "" && json != name { - // TODO: escaping might be needed, in which case - // perhaps this should be in its own "json" tag. - name += ",json=" + json - } - name = ",name=" + name - if message.proto3() { - // We only need the extra tag for []byte fields; - // no need to add noise for the others. - if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES { - name += ",proto3" - } - - } - oneof := "" - if field.OneofIndex != nil { - oneof = ",oneof" - } - return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s", - wiretype, - field.GetNumber(), - optrepreq, - packed, - name, - enum, - oneof, - defaultValue)) -} - -func needsStar(typ descriptor.FieldDescriptorProto_Type) bool { - switch typ { - case descriptor.FieldDescriptorProto_TYPE_GROUP: - return false - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - return false - case descriptor.FieldDescriptorProto_TYPE_BYTES: - return false - } - return true -} - -// TypeName is the printed name appropriate for an item. If the object is in the current file, -// TypeName drops the package name and underscores the rest. -// Otherwise the object is from another package; and the result is the underscored -// package name followed by the item name. -// The result always has an initial capital. -func (g *Generator) TypeName(obj Object) string { - return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) -} - -// GoType returns a string representing the type name, and the wire type -func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { - // TODO: Options. - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_DOUBLE: - typ, wire = "float64", "fixed64" - case descriptor.FieldDescriptorProto_TYPE_FLOAT: - typ, wire = "float32", "fixed32" - case descriptor.FieldDescriptorProto_TYPE_INT64: - typ, wire = "int64", "varint" - case descriptor.FieldDescriptorProto_TYPE_UINT64: - typ, wire = "uint64", "varint" - case descriptor.FieldDescriptorProto_TYPE_INT32: - typ, wire = "int32", "varint" - case descriptor.FieldDescriptorProto_TYPE_UINT32: - typ, wire = "uint32", "varint" - case descriptor.FieldDescriptorProto_TYPE_FIXED64: - typ, wire = "uint64", "fixed64" - case descriptor.FieldDescriptorProto_TYPE_FIXED32: - typ, wire = "uint32", "fixed32" - case descriptor.FieldDescriptorProto_TYPE_BOOL: - typ, wire = "bool", "varint" - case descriptor.FieldDescriptorProto_TYPE_STRING: - typ, wire = "string", "bytes" - case descriptor.FieldDescriptorProto_TYPE_GROUP: - desc := g.ObjectNamed(field.GetTypeName()) - typ, wire = "*"+g.TypeName(desc), "group" - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - desc := g.ObjectNamed(field.GetTypeName()) - typ, wire = "*"+g.TypeName(desc), "bytes" - case descriptor.FieldDescriptorProto_TYPE_BYTES: - typ, wire = "[]byte", "bytes" - case descriptor.FieldDescriptorProto_TYPE_ENUM: - desc := g.ObjectNamed(field.GetTypeName()) - typ, wire = g.TypeName(desc), "varint" - case descriptor.FieldDescriptorProto_TYPE_SFIXED32: - typ, wire = "int32", "fixed32" - case descriptor.FieldDescriptorProto_TYPE_SFIXED64: - typ, wire = "int64", "fixed64" - case descriptor.FieldDescriptorProto_TYPE_SINT32: - typ, wire = "int32", "zigzag32" - case descriptor.FieldDescriptorProto_TYPE_SINT64: - typ, wire = "int64", "zigzag64" - default: - g.Fail("unknown type for", field.GetName()) - } - if isRepeated(field) { - typ = "[]" + typ - } else if message != nil && message.proto3() { - return - } else if field.OneofIndex != nil && message != nil { - return - } else if needsStar(*field.Type) { - typ = "*" + typ - } - return -} - -func (g *Generator) RecordTypeUse(t string) { - if _, ok := g.typeNameToObject[t]; ok { - // Call ObjectNamed to get the true object to record the use. - obj := g.ObjectNamed(t) - g.usedPackages[obj.GoImportPath()] = true - } -} - -// Method names that may be generated. Fields with these names get an -// underscore appended. Any change to this set is a potential incompatible -// API change because it changes generated field names. -var methodNames = [...]string{ - "Reset", - "String", - "ProtoMessage", - "Marshal", - "Unmarshal", - "ExtensionRangeArray", - "ExtensionMap", - "Descriptor", -} - -// Names of messages in the `google.protobuf` package for which -// we will generate XXX_WellKnownType methods. -var wellKnownTypes = map[string]bool{ - "Any": true, - "Duration": true, - "Empty": true, - "Struct": true, - "Timestamp": true, - - "Value": true, - "ListValue": true, - "DoubleValue": true, - "FloatValue": true, - "Int64Value": true, - "UInt64Value": true, - "Int32Value": true, - "UInt32Value": true, - "BoolValue": true, - "StringValue": true, - "BytesValue": true, -} - -// Generate the type and default constant definitions for this Descriptor. -func (g *Generator) generateMessage(message *Descriptor) { - // The full type name - typeName := message.TypeName() - // The full type name, CamelCased. - ccTypeName := CamelCaseSlice(typeName) - - usedNames := make(map[string]bool) - for _, n := range methodNames { - usedNames[n] = true - } - fieldNames := make(map[*descriptor.FieldDescriptorProto]string) - fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string) - fieldTypes := make(map[*descriptor.FieldDescriptorProto]string) - mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) - - oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto - oneofDisc := make(map[int32]string) // name of discriminator method - oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star - oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer - - comments := g.PrintComments(message.path) - - // Guarantee deprecation comments appear after user-provided comments. - if message.GetOptions().GetDeprecated() { - if comments { - // Convention: Separate deprecation comments from original - // comments with an empty line. - g.P("//") - } - g.P(deprecationComment) - } - - g.P("type ", Annotate(message.file, message.path, ccTypeName), " struct {") - g.In() - - // allocNames finds a conflict-free variation of the given strings, - // consistently mutating their suffixes. - // It returns the same number of strings. - allocNames := func(ns ...string) []string { - Loop: - for { - for _, n := range ns { - if usedNames[n] { - for i := range ns { - ns[i] += "_" - } - continue Loop - } - } - for _, n := range ns { - usedNames[n] = true - } - return ns - } - } - - for i, field := range message.Field { - // Allocate the getter and the field at the same time so name - // collisions create field/method consistent names. - // TODO: This allocation occurs based on the order of the fields - // in the proto file, meaning that a change in the field - // ordering can change generated Method/Field names. - base := CamelCase(*field.Name) - ns := allocNames(base, "Get"+base) - fieldName, fieldGetterName := ns[0], ns[1] - typename, wiretype := g.GoType(message, field) - jsonName := *field.Name - tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty") - - fieldNames[field] = fieldName - fieldGetterNames[field] = fieldGetterName - - oneof := field.OneofIndex != nil - if oneof && oneofFieldName[*field.OneofIndex] == "" { - odp := message.OneofDecl[int(*field.OneofIndex)] - fname := allocNames(CamelCase(odp.GetName()))[0] - - // This is the first field of a oneof we haven't seen before. - // Generate the union field. - oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex) - com := g.PrintComments(oneofFullPath) - if com { - g.P("//") - } - g.P("// Types that are valid to be assigned to ", fname, ":") - // Generate the rest of this comment later, - // when we've computed any disambiguation. - oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len() - - dname := "is" + ccTypeName + "_" + fname - oneofFieldName[*field.OneofIndex] = fname - oneofDisc[*field.OneofIndex] = dname - tag := `protobuf_oneof:"` + odp.GetName() + `"` - g.P(Annotate(message.file, oneofFullPath, fname), " ", dname, " `", tag, "`") - } - - if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE { - desc := g.ObjectNamed(field.GetTypeName()) - if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() { - // Figure out the Go types and tags for the key and value types. - keyField, valField := d.Field[0], d.Field[1] - keyType, keyWire := g.GoType(d, keyField) - valType, valWire := g.GoType(d, valField) - keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire) - - // We don't use stars, except for message-typed values. - // Message and enum types are the only two possibly foreign types used in maps, - // so record their use. They are not permitted as map keys. - keyType = strings.TrimPrefix(keyType, "*") - switch *valField.Type { - case descriptor.FieldDescriptorProto_TYPE_ENUM: - valType = strings.TrimPrefix(valType, "*") - g.RecordTypeUse(valField.GetTypeName()) - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - g.RecordTypeUse(valField.GetTypeName()) - default: - valType = strings.TrimPrefix(valType, "*") - } - - typename = fmt.Sprintf("map[%s]%s", keyType, valType) - mapFieldTypes[field] = typename // record for the getter generation - - tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag) - } - } - - fieldTypes[field] = typename - - if oneof { - tname := ccTypeName + "_" + fieldName - // It is possible for this to collide with a message or enum - // nested in this message. Check for collisions. - for { - ok := true - for _, desc := range message.nested { - if CamelCaseSlice(desc.TypeName()) == tname { - ok = false - break - } - } - for _, enum := range message.enums { - if CamelCaseSlice(enum.TypeName()) == tname { - ok = false - break - } - } - if !ok { - tname += "_" - continue - } - break - } - - oneofTypeName[field] = tname - continue - } - - fieldDeprecated := "" - if field.GetOptions().GetDeprecated() { - fieldDeprecated = deprecationComment - } - - fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i) - g.PrintComments(fieldFullPath) - g.P(Annotate(message.file, fieldFullPath, fieldName), "\t", typename, "\t`", tag, "`", fieldDeprecated) - g.RecordTypeUse(field.GetTypeName()) - } - g.P("XXX_NoUnkeyedLiteral\tstruct{} `json:\"-\"`") // prevent unkeyed struct literals - if len(message.ExtensionRange) > 0 { - messageset := "" - if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() { - messageset = "protobuf_messageset:\"1\" " - } - g.P(g.Pkg["proto"], ".XXX_InternalExtensions `", messageset, "json:\"-\"`") - } - g.P("XXX_unrecognized\t[]byte `json:\"-\"`") - g.P("XXX_sizecache\tint32 `json:\"-\"`") - g.Out() - g.P("}") - - // Update g.Buffer to list valid oneof types. - // We do this down here, after we've disambiguated the oneof type names. - // We go in reverse order of insertion point to avoid invalidating offsets. - for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- { - ip := oneofInsertPoints[oi] - all := g.Buffer.Bytes() - rem := all[ip:] - g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem - oldLen := g.Buffer.Len() - for _, field := range message.Field { - if field.OneofIndex == nil || *field.OneofIndex != oi { - continue - } - g.P("//\t*", oneofTypeName[field]) - } - // If we've inserted text, we also need to fix up affected annotations (as - // they contain offsets that may need to be changed). - offset := int32(g.Buffer.Len() - oldLen) - ip32 := int32(ip) - for _, anno := range g.annotations { - if *anno.Begin >= ip32 { - *anno.Begin += offset - } - if *anno.End >= ip32 { - *anno.End += offset - } - } - g.Buffer.Write(rem) - } - - // Reset, String and ProtoMessage methods. - g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }") - g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }") - g.P("func (*", ccTypeName, ") ProtoMessage() {}") - var indexes []string - for m := message; m != nil; m = m.parent { - indexes = append([]string{strconv.Itoa(m.index)}, indexes...) - } - g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) {") - g.In() - g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}") - g.Out() - g.P("}") - // TODO: Revisit the decision to use a XXX_WellKnownType method - // if we change proto.MessageName to work with multiple equivalents. - if message.file.GetPackage() == "google.protobuf" && wellKnownTypes[message.GetName()] { - g.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, message.GetName(), `" }`) - } - - // Extension support methods - var hasExtensions, isMessageSet bool - if len(message.ExtensionRange) > 0 { - hasExtensions = true - // message_set_wire_format only makes sense when extensions are defined. - if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() { - isMessageSet = true - g.P() - g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {") - g.In() - g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(&m.XXX_InternalExtensions)") - g.Out() - g.P("}") - g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {") - g.In() - g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)") - g.Out() - g.P("}") - } - - g.P() - g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{") - g.In() - for _, r := range message.ExtensionRange { - end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends - g.P("{Start: ", r.Start, ", End: ", end, "},") - } - g.Out() - g.P("}") - g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {") - g.In() - g.P("return extRange_", ccTypeName) - g.Out() - g.P("}") - } - - // TODO: It does not scale to keep adding another method for every - // operation on protos that we want to switch over to using the - // table-driven approach. Instead, we should only add a single method - // that allows getting access to the *InternalMessageInfo struct and then - // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that. - - // Wrapper for table-driven marshaling and unmarshaling. - g.P("func (m *", ccTypeName, ") XXX_Unmarshal(b []byte) error {") - g.In() - g.P("return xxx_messageInfo_", ccTypeName, ".Unmarshal(m, b)") - g.Out() - g.P("}") - - g.P("func (m *", ccTypeName, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {") - g.In() - g.P("return xxx_messageInfo_", ccTypeName, ".Marshal(b, m, deterministic)") - g.Out() - g.P("}") - - g.P("func (dst *", ccTypeName, ") XXX_Merge(src ", g.Pkg["proto"], ".Message) {") - g.In() - g.P("xxx_messageInfo_", ccTypeName, ".Merge(dst, src)") - g.Out() - g.P("}") - - g.P("func (m *", ccTypeName, ") XXX_Size() int {") // avoid name clash with "Size" field in some message - g.In() - g.P("return xxx_messageInfo_", ccTypeName, ".Size(m)") - g.Out() - g.P("}") - - g.P("func (m *", ccTypeName, ") XXX_DiscardUnknown() {") - g.In() - g.P("xxx_messageInfo_", ccTypeName, ".DiscardUnknown(m)") - g.Out() - g.P("}") - - g.P("var xxx_messageInfo_", ccTypeName, " ", g.Pkg["proto"], ".InternalMessageInfo") - - // Default constants - defNames := make(map[*descriptor.FieldDescriptorProto]string) - for _, field := range message.Field { - def := field.GetDefaultValue() - if def == "" { - continue - } - fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name) - defNames[field] = fieldname - typename, _ := g.GoType(message, field) - if typename[0] == '*' { - typename = typename[1:] - } - kind := "const " - switch { - case typename == "bool": - case typename == "string": - def = strconv.Quote(def) - case typename == "[]byte": - def = "[]byte(" + strconv.Quote(unescape(def)) + ")" - kind = "var " - case def == "inf", def == "-inf", def == "nan": - // These names are known to, and defined by, the protocol language. - switch def { - case "inf": - def = "math.Inf(1)" - case "-inf": - def = "math.Inf(-1)" - case "nan": - def = "math.NaN()" - } - if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT { - def = "float32(" + def + ")" - } - kind = "var " - case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM: - // Must be an enum. Need to construct the prefixed name. - obj := g.ObjectNamed(field.GetTypeName()) - var enum *EnumDescriptor - if id, ok := obj.(*ImportedDescriptor); ok { - // The enum type has been publicly imported. - enum, _ = id.o.(*EnumDescriptor) - } else { - enum, _ = obj.(*EnumDescriptor) - } - if enum == nil { - log.Printf("don't know how to generate constant for %s", fieldname) - continue - } - def = g.DefaultPackageName(obj) + enum.prefix() + def - } - g.P(kind, fieldname, " ", typename, " = ", def) - g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""}) - } - g.P() - - // Oneof per-field types, discriminants and getters. - // - // Generate unexported named types for the discriminant interfaces. - // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug - // that was triggered by using anonymous interfaces here. - // TODO: Revisit this and consider reverting back to anonymous interfaces. - for oi := range message.OneofDecl { - dname := oneofDisc[int32(oi)] - g.P("type ", dname, " interface {") - g.In() - g.P(dname, "()") - g.Out() - g.P("}") - } - g.P() - var oneofTypes []string - for i, field := range message.Field { - if field.OneofIndex == nil { - continue - } - _, wiretype := g.GoType(message, field) - tag := "protobuf:" + g.goTag(message, field, wiretype) - fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i) - g.P("type ", Annotate(message.file, fieldFullPath, oneofTypeName[field]), " struct{ ", Annotate(message.file, fieldFullPath, fieldNames[field]), " ", fieldTypes[field], " `", tag, "` }") - g.RecordTypeUse(field.GetTypeName()) - oneofTypes = append(oneofTypes, oneofTypeName[field]) - } - g.P() - for _, field := range message.Field { - if field.OneofIndex == nil { - continue - } - g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}") - } - g.P() - for oi := range message.OneofDecl { - fname := oneofFieldName[int32(oi)] - oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, oi) - g.P("func (m *", ccTypeName, ") ", Annotate(message.file, oneofFullPath, "Get"+fname), "() ", oneofDisc[int32(oi)], " {") - g.P("if m != nil { return m.", fname, " }") - g.P("return nil") - g.P("}") - } - g.P() - - // Field getters - for i, field := range message.Field { - oneof := field.OneofIndex != nil - - fname := fieldNames[field] - typename, _ := g.GoType(message, field) - if t, ok := mapFieldTypes[field]; ok { - typename = t - } - mname := fieldGetterNames[field] - star := "" - if needsStar(*field.Type) && typename[0] == '*' { - typename = typename[1:] - star = "*" - } - fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i) - - if field.GetOptions().GetDeprecated() { - g.P(deprecationComment) - } - - g.P("func (m *", ccTypeName, ") ", Annotate(message.file, fieldFullPath, mname), "() "+typename+" {") - g.In() - def, hasDef := defNames[field] - typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_BYTES: - typeDefaultIsNil = !hasDef - case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: - typeDefaultIsNil = true - } - if isRepeated(field) { - typeDefaultIsNil = true - } - if typeDefaultIsNil && !oneof { - // A bytes field with no explicit default needs less generated code, - // as does a message or group field, or a repeated field. - g.P("if m != nil {") - g.In() - g.P("return m." + fname) - g.Out() - g.P("}") - g.P("return nil") - g.Out() - g.P("}") - g.P() - continue - } - if !oneof { - if message.proto3() { - g.P("if m != nil {") - } else { - g.P("if m != nil && m." + fname + " != nil {") - } - g.In() - g.P("return " + star + "m." + fname) - g.Out() - g.P("}") - } else { - uname := oneofFieldName[*field.OneofIndex] - tname := oneofTypeName[field] - g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {") - g.P("return x.", fname) - g.P("}") - } - if hasDef { - if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES { - g.P("return " + def) - } else { - // The default is a []byte var. - // Make a copy when returning it to be safe. - g.P("return append([]byte(nil), ", def, "...)") - } - } else { - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_BOOL: - g.P("return false") - case descriptor.FieldDescriptorProto_TYPE_STRING: - g.P(`return ""`) - case descriptor.FieldDescriptorProto_TYPE_GROUP, - descriptor.FieldDescriptorProto_TYPE_MESSAGE, - descriptor.FieldDescriptorProto_TYPE_BYTES: - // This is only possible for oneof fields. - g.P("return nil") - case descriptor.FieldDescriptorProto_TYPE_ENUM: - // The default default for an enum is the first value in the enum, - // not zero. - obj := g.ObjectNamed(field.GetTypeName()) - var enum *EnumDescriptor - if id, ok := obj.(*ImportedDescriptor); ok { - // The enum type has been publicly imported. - enum, _ = id.o.(*EnumDescriptor) - } else { - enum, _ = obj.(*EnumDescriptor) - } - if enum == nil { - log.Printf("don't know how to generate getter for %s", field.GetName()) - continue - } - if len(enum.Value) == 0 { - g.P("return 0 // empty enum") - } else { - first := enum.Value[0].GetName() - g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first) - } - default: - g.P("return 0") - } - } - g.Out() - g.P("}") - g.P() - } - - if !message.group { - ms := &messageSymbol{ - sym: ccTypeName, - hasExtensions: hasExtensions, - isMessageSet: isMessageSet, - oneofTypes: oneofTypes, - } - g.file.addExport(message, ms) - } - - // Oneof functions - if len(message.OneofDecl) > 0 { - fieldWire := make(map[*descriptor.FieldDescriptorProto]string) - - // method - enc := "_" + ccTypeName + "_OneofMarshaler" - dec := "_" + ccTypeName + "_OneofUnmarshaler" - size := "_" + ccTypeName + "_OneofSizer" - encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" - decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" - sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)" - - g.P("// XXX_OneofFuncs is for the internal use of the proto package.") - g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") - g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{") - for _, field := range message.Field { - if field.OneofIndex == nil { - continue - } - g.P("(*", oneofTypeName[field], ")(nil),") - } - g.P("}") - g.P("}") - g.P() - - // marshaler - g.P("func ", enc, encSig, " {") - g.P("m := msg.(*", ccTypeName, ")") - for oi, odp := range message.OneofDecl { - g.P("// ", odp.GetName()) - fname := oneofFieldName[int32(oi)] - g.P("switch x := m.", fname, ".(type) {") - for _, field := range message.Field { - if field.OneofIndex == nil || int(*field.OneofIndex) != oi { - continue - } - g.P("case *", oneofTypeName[field], ":") - var wire, pre, post string - val := "x." + fieldNames[field] // overridden for TYPE_BOOL - canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_DOUBLE: - wire = "WireFixed64" - pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits(" - post = "))" - case descriptor.FieldDescriptorProto_TYPE_FLOAT: - wire = "WireFixed32" - pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits(" - post = ")))" - case descriptor.FieldDescriptorProto_TYPE_INT64, - descriptor.FieldDescriptorProto_TYPE_UINT64: - wire = "WireVarint" - pre, post = "b.EncodeVarint(uint64(", "))" - case descriptor.FieldDescriptorProto_TYPE_INT32, - descriptor.FieldDescriptorProto_TYPE_UINT32, - descriptor.FieldDescriptorProto_TYPE_ENUM: - wire = "WireVarint" - pre, post = "b.EncodeVarint(uint64(", "))" - case descriptor.FieldDescriptorProto_TYPE_FIXED64, - descriptor.FieldDescriptorProto_TYPE_SFIXED64: - wire = "WireFixed64" - pre, post = "b.EncodeFixed64(uint64(", "))" - case descriptor.FieldDescriptorProto_TYPE_FIXED32, - descriptor.FieldDescriptorProto_TYPE_SFIXED32: - wire = "WireFixed32" - pre, post = "b.EncodeFixed32(uint64(", "))" - case descriptor.FieldDescriptorProto_TYPE_BOOL: - // bool needs special handling. - g.P("t := uint64(0)") - g.P("if ", val, " { t = 1 }") - val = "t" - wire = "WireVarint" - pre, post = "b.EncodeVarint(", ")" - case descriptor.FieldDescriptorProto_TYPE_STRING: - wire = "WireBytes" - pre, post = "b.EncodeStringBytes(", ")" - case descriptor.FieldDescriptorProto_TYPE_GROUP: - wire = "WireStartGroup" - pre, post = "b.Marshal(", ")" - canFail = true - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - wire = "WireBytes" - pre, post = "b.EncodeMessage(", ")" - canFail = true - case descriptor.FieldDescriptorProto_TYPE_BYTES: - wire = "WireBytes" - pre, post = "b.EncodeRawBytes(", ")" - case descriptor.FieldDescriptorProto_TYPE_SINT32: - wire = "WireVarint" - pre, post = "b.EncodeZigzag32(uint64(", "))" - case descriptor.FieldDescriptorProto_TYPE_SINT64: - wire = "WireVarint" - pre, post = "b.EncodeZigzag64(uint64(", "))" - default: - g.Fail("unhandled oneof field type ", field.Type.String()) - } - fieldWire[field] = wire - g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") - if !canFail { - g.P(pre, val, post) - } else { - g.P("if err := ", pre, val, post, "; err != nil {") - g.P("return err") - g.P("}") - } - if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { - g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") - } - } - g.P("case nil:") - g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`) - g.P("}") - } - g.P("return nil") - g.P("}") - g.P() - - // unmarshaler - g.P("func ", dec, decSig, " {") - g.P("m := msg.(*", ccTypeName, ")") - g.P("switch tag {") - for _, field := range message.Field { - if field.OneofIndex == nil { - continue - } - odp := message.OneofDecl[int(*field.OneofIndex)] - g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name) - g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {") - g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType") - g.P("}") - lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP - var dec, cast, cast2 string - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_DOUBLE: - dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits" - case descriptor.FieldDescriptorProto_TYPE_FLOAT: - dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits" - case descriptor.FieldDescriptorProto_TYPE_INT64: - dec, cast = "b.DecodeVarint()", "int64" - case descriptor.FieldDescriptorProto_TYPE_UINT64: - dec = "b.DecodeVarint()" - case descriptor.FieldDescriptorProto_TYPE_INT32: - dec, cast = "b.DecodeVarint()", "int32" - case descriptor.FieldDescriptorProto_TYPE_FIXED64: - dec = "b.DecodeFixed64()" - case descriptor.FieldDescriptorProto_TYPE_FIXED32: - dec, cast = "b.DecodeFixed32()", "uint32" - case descriptor.FieldDescriptorProto_TYPE_BOOL: - dec = "b.DecodeVarint()" - // handled specially below - case descriptor.FieldDescriptorProto_TYPE_STRING: - dec = "b.DecodeStringBytes()" - case descriptor.FieldDescriptorProto_TYPE_GROUP: - g.P("msg := new(", fieldTypes[field][1:], ")") // drop star - lhs = "err" - dec = "b.DecodeGroup(msg)" - // handled specially below - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - g.P("msg := new(", fieldTypes[field][1:], ")") // drop star - lhs = "err" - dec = "b.DecodeMessage(msg)" - // handled specially below - case descriptor.FieldDescriptorProto_TYPE_BYTES: - dec = "b.DecodeRawBytes(true)" - case descriptor.FieldDescriptorProto_TYPE_UINT32: - dec, cast = "b.DecodeVarint()", "uint32" - case descriptor.FieldDescriptorProto_TYPE_ENUM: - dec, cast = "b.DecodeVarint()", fieldTypes[field] - case descriptor.FieldDescriptorProto_TYPE_SFIXED32: - dec, cast = "b.DecodeFixed32()", "int32" - case descriptor.FieldDescriptorProto_TYPE_SFIXED64: - dec, cast = "b.DecodeFixed64()", "int64" - case descriptor.FieldDescriptorProto_TYPE_SINT32: - dec, cast = "b.DecodeZigzag32()", "int32" - case descriptor.FieldDescriptorProto_TYPE_SINT64: - dec, cast = "b.DecodeZigzag64()", "int64" - default: - g.Fail("unhandled oneof field type ", field.Type.String()) - } - g.P(lhs, " := ", dec) - val := "x" - if cast != "" { - val = cast + "(" + val + ")" - } - if cast2 != "" { - val = cast2 + "(" + val + ")" - } - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_BOOL: - val += " != 0" - case descriptor.FieldDescriptorProto_TYPE_GROUP, - descriptor.FieldDescriptorProto_TYPE_MESSAGE: - val = "msg" - } - g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}") - g.P("return true, err") - } - g.P("default: return false, nil") - g.P("}") - g.P("}") - g.P() - - // sizer - g.P("func ", size, sizeSig, " {") - g.P("m := msg.(*", ccTypeName, ")") - for oi, odp := range message.OneofDecl { - g.P("// ", odp.GetName()) - fname := oneofFieldName[int32(oi)] - g.P("switch x := m.", fname, ".(type) {") - for _, field := range message.Field { - if field.OneofIndex == nil || int(*field.OneofIndex) != oi { - continue - } - g.P("case *", oneofTypeName[field], ":") - val := "x." + fieldNames[field] - var varint, fixed string - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_DOUBLE: - fixed = "8" - case descriptor.FieldDescriptorProto_TYPE_FLOAT: - fixed = "4" - case descriptor.FieldDescriptorProto_TYPE_INT64, - descriptor.FieldDescriptorProto_TYPE_UINT64, - descriptor.FieldDescriptorProto_TYPE_INT32, - descriptor.FieldDescriptorProto_TYPE_UINT32, - descriptor.FieldDescriptorProto_TYPE_ENUM: - varint = val - case descriptor.FieldDescriptorProto_TYPE_FIXED64, - descriptor.FieldDescriptorProto_TYPE_SFIXED64: - fixed = "8" - case descriptor.FieldDescriptorProto_TYPE_FIXED32, - descriptor.FieldDescriptorProto_TYPE_SFIXED32: - fixed = "4" - case descriptor.FieldDescriptorProto_TYPE_BOOL: - fixed = "1" - case descriptor.FieldDescriptorProto_TYPE_STRING: - fixed = "len(" + val + ")" - varint = fixed - case descriptor.FieldDescriptorProto_TYPE_GROUP: - fixed = g.Pkg["proto"] + ".Size(" + val + ")" - case descriptor.FieldDescriptorProto_TYPE_MESSAGE: - g.P("s := ", g.Pkg["proto"], ".Size(", val, ")") - fixed = "s" - varint = fixed - case descriptor.FieldDescriptorProto_TYPE_BYTES: - fixed = "len(" + val + ")" - varint = fixed - case descriptor.FieldDescriptorProto_TYPE_SINT32: - varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))" - case descriptor.FieldDescriptorProto_TYPE_SINT64: - varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))" - default: - g.Fail("unhandled oneof field type ", field.Type.String()) - } - // Tag and wire varint is known statically, - // so don't generate code for that part of the size computation. - tagAndWireSize := proto.SizeVarint(uint64(*field.Number << 3)) // wire doesn't affect varint size - g.P("n += ", tagAndWireSize, " // tag and wire") - if varint != "" { - g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))") - } - if fixed != "" { - g.P("n += ", fixed) - } - if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { - g.P("n += ", tagAndWireSize, " // tag and wire") - } - } - g.P("case nil:") - g.P("default:") - g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))") - g.P("}") - } - g.P("return n") - g.P("}") - g.P() - } - - for _, ext := range message.ext { - g.generateExtension(ext) - } - - fullName := strings.Join(message.TypeName(), ".") - if g.file.Package != nil { - fullName = *g.file.Package + "." + fullName - } - - g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], ccTypeName, fullName) - // Register types for native map types. - for _, k := range mapFieldKeys(mapFieldTypes) { - fullName := strings.TrimPrefix(*k.TypeName, ".") - g.addInitf("%s.RegisterMapType((%s)(nil), %q)", g.Pkg["proto"], mapFieldTypes[k], fullName) - } -} - -type byTypeName []*descriptor.FieldDescriptorProto - -func (a byTypeName) Len() int { return len(a) } -func (a byTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTypeName) Less(i, j int) bool { return *a[i].TypeName < *a[j].TypeName } - -// mapFieldKeys returns the keys of m in a consistent order. -func mapFieldKeys(m map[*descriptor.FieldDescriptorProto]string) []*descriptor.FieldDescriptorProto { - keys := make([]*descriptor.FieldDescriptorProto, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Sort(byTypeName(keys)) - return keys -} - -var escapeChars = [256]byte{ - 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?', -} - -// unescape reverses the "C" escaping that protoc does for default values of bytes fields. -// It is best effort in that it effectively ignores malformed input. Seemingly invalid escape -// sequences are conveyed, unmodified, into the decoded result. -func unescape(s string) string { - // NB: Sadly, we can't use strconv.Unquote because protoc will escape both - // single and double quotes, but strconv.Unquote only allows one or the - // other (based on actual surrounding quotes of its input argument). - - var out []byte - for len(s) > 0 { - // regular character, or too short to be valid escape - if s[0] != '\\' || len(s) < 2 { - out = append(out, s[0]) - s = s[1:] - } else if c := escapeChars[s[1]]; c != 0 { - // escape sequence - out = append(out, c) - s = s[2:] - } else if s[1] == 'x' || s[1] == 'X' { - // hex escape, e.g. "\x80 - if len(s) < 4 { - // too short to be valid - out = append(out, s[:2]...) - s = s[2:] - continue - } - v, err := strconv.ParseUint(s[2:4], 16, 8) - if err != nil { - out = append(out, s[:4]...) - } else { - out = append(out, byte(v)) - } - s = s[4:] - } else if '0' <= s[1] && s[1] <= '7' { - // octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164" - // so consume up to 2 more bytes or up to end-of-string - n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567")) - if n > 3 { - n = 3 - } - v, err := strconv.ParseUint(s[1:1+n], 8, 8) - if err != nil { - out = append(out, s[:1+n]...) - } else { - out = append(out, byte(v)) - } - s = s[1+n:] - } else { - // bad escape, just propagate the slash as-is - out = append(out, s[0]) - s = s[1:] - } - } - - return string(out) -} - -func (g *Generator) generateExtension(ext *ExtensionDescriptor) { - ccTypeName := ext.DescName() - - extObj := g.ObjectNamed(*ext.Extendee) - var extDesc *Descriptor - if id, ok := extObj.(*ImportedDescriptor); ok { - // This is extending a publicly imported message. - // We need the underlying type for goTag. - extDesc = id.o.(*Descriptor) - } else { - extDesc = extObj.(*Descriptor) - } - extendedType := "*" + g.TypeName(extObj) // always use the original - field := ext.FieldDescriptorProto - fieldType, wireType := g.GoType(ext.parent, field) - tag := g.goTag(extDesc, field, wireType) - g.RecordTypeUse(*ext.Extendee) - if n := ext.FieldDescriptorProto.TypeName; n != nil { - // foreign extension type - g.RecordTypeUse(*n) - } - - typeName := ext.TypeName() - - // Special case for proto2 message sets: If this extension is extending - // proto2.bridge.MessageSet, and its final name component is "message_set_extension", - // then drop that last component. - // - // TODO: This should be implemented in the text formatter rather than the generator. - // In addition, the situation for when to apply this special case is implemented - // differently in other languages: - // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560 - mset := false - if extDesc.GetOptions().GetMessageSetWireFormat() && typeName[len(typeName)-1] == "message_set_extension" { - typeName = typeName[:len(typeName)-1] - mset = true - } - - // For text formatting, the package must be exactly what the .proto file declares, - // ignoring overrides such as the go_package option, and with no dot/underscore mapping. - extName := strings.Join(typeName, ".") - if g.file.Package != nil { - extName = *g.file.Package + "." + extName - } - - g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{") - g.In() - g.P("ExtendedType: (", extendedType, ")(nil),") - g.P("ExtensionType: (", fieldType, ")(nil),") - g.P("Field: ", field.Number, ",") - g.P(`Name: "`, extName, `",`) - g.P("Tag: ", tag, ",") - g.P(`Filename: "`, g.file.GetName(), `",`) - - g.Out() - g.P("}") - g.P() - - if mset { - // Generate a bit more code to register with message_set.go. - g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName) - } - - g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""}) -} - -func (g *Generator) generateInitFunction() { - for _, enum := range g.file.enum { - g.generateEnumRegistration(enum) - } - for _, d := range g.file.desc { - for _, ext := range d.ext { - g.generateExtensionRegistration(ext) - } - } - for _, ext := range g.file.ext { - g.generateExtensionRegistration(ext) - } - if len(g.init) == 0 { - return - } - g.P("func init() {") - g.In() - for _, l := range g.init { - g.P(l) - } - g.Out() - g.P("}") - g.init = nil -} - -func (g *Generator) generateFileDescriptor(file *FileDescriptor) { - // Make a copy and trim source_code_info data. - // TODO: Trim this more when we know exactly what we need. - pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto) - pb.SourceCodeInfo = nil - - b, err := proto.Marshal(pb) - if err != nil { - g.Fail(err.Error()) - } - - var buf bytes.Buffer - w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) - w.Write(b) - w.Close() - b = buf.Bytes() - - v := file.VarName() - g.P() - g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }") - g.P("var ", v, " = []byte{") - g.In() - g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto") - for len(b) > 0 { - n := 16 - if n > len(b) { - n = len(b) - } - - s := "" - for _, c := range b[:n] { - s += fmt.Sprintf("0x%02x,", c) - } - g.P(s) - - b = b[n:] - } - g.Out() - g.P("}") -} - -func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) { - // // We always print the full (proto-world) package name here. - pkg := enum.File().GetPackage() - if pkg != "" { - pkg += "." - } - // The full type name - typeName := enum.TypeName() - // The full type name, CamelCased. - ccTypeName := CamelCaseSlice(typeName) - g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName) -} - -func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) { - g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName()) -} - -// And now lots of helper functions. - -// Is c an ASCII lower-case letter? -func isASCIILower(c byte) bool { - return 'a' <= c && c <= 'z' -} - -// Is c an ASCII digit? -func isASCIIDigit(c byte) bool { - return '0' <= c && c <= '9' -} - -// CamelCase returns the CamelCased name. -// If there is an interior underscore followed by a lower case letter, -// drop the underscore and convert the letter to upper case. -// There is a remote possibility of this rewrite causing a name collision, -// but it's so remote we're prepared to pretend it's nonexistent - since the -// C++ generator lowercases names, it's extremely unlikely to have two fields -// with different capitalizations. -// In short, _my_field_name_2 becomes XMyFieldName_2. -func CamelCase(s string) string { - if s == "" { - return "" - } - t := make([]byte, 0, 32) - i := 0 - if s[0] == '_' { - // Need a capital letter; drop the '_'. - t = append(t, 'X') - i++ - } - // Invariant: if the next letter is lower case, it must be converted - // to upper case. - // That is, we process a word at a time, where words are marked by _ or - // upper case letter. Digits are treated as words. - for ; i < len(s); i++ { - c := s[i] - if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { - continue // Skip the underscore in s. - } - if isASCIIDigit(c) { - t = append(t, c) - continue - } - // Assume we have a letter now - if not, it's a bogus identifier. - // The next word is a sequence of characters that must start upper case. - if isASCIILower(c) { - c ^= ' ' // Make it a capital letter. - } - t = append(t, c) // Guaranteed not lower case. - // Accept lower case sequence that follows. - for i+1 < len(s) && isASCIILower(s[i+1]) { - i++ - t = append(t, s[i]) - } - } - return string(t) -} - -// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to -// be joined with "_". -func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } - -// dottedSlice turns a sliced name into a dotted name. -func dottedSlice(elem []string) string { return strings.Join(elem, ".") } - -// Is this field optional? -func isOptional(field *descriptor.FieldDescriptorProto) bool { - return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL -} - -// Is this field required? -func isRequired(field *descriptor.FieldDescriptorProto) bool { - return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED -} - -// Is this field repeated? -func isRepeated(field *descriptor.FieldDescriptorProto) bool { - return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED -} - -// Is this field a scalar numeric type? -func isScalar(field *descriptor.FieldDescriptorProto) bool { - if field.Type == nil { - return false - } - switch *field.Type { - case descriptor.FieldDescriptorProto_TYPE_DOUBLE, - descriptor.FieldDescriptorProto_TYPE_FLOAT, - descriptor.FieldDescriptorProto_TYPE_INT64, - descriptor.FieldDescriptorProto_TYPE_UINT64, - descriptor.FieldDescriptorProto_TYPE_INT32, - descriptor.FieldDescriptorProto_TYPE_FIXED64, - descriptor.FieldDescriptorProto_TYPE_FIXED32, - descriptor.FieldDescriptorProto_TYPE_BOOL, - descriptor.FieldDescriptorProto_TYPE_UINT32, - descriptor.FieldDescriptorProto_TYPE_ENUM, - descriptor.FieldDescriptorProto_TYPE_SFIXED32, - descriptor.FieldDescriptorProto_TYPE_SFIXED64, - descriptor.FieldDescriptorProto_TYPE_SINT32, - descriptor.FieldDescriptorProto_TYPE_SINT64: - return true - default: - return false - } -} - -// badToUnderscore is the mapping function used to generate Go names from package names, -// which can be dotted in the input .proto file. It replaces non-identifier characters such as -// dot or dash with underscore. -func badToUnderscore(r rune) rune { - if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { - return r - } - return '_' -} - -// baseName returns the last path element of the name, with the last dotted suffix removed. -func baseName(name string) string { - // First, find the last element - if i := strings.LastIndex(name, "/"); i >= 0 { - name = name[i+1:] - } - // Now drop the suffix - if i := strings.LastIndex(name, "."); i >= 0 { - name = name[0:i] - } - return name -} - -// The SourceCodeInfo message describes the location of elements of a parsed -// .proto file by way of a "path", which is a sequence of integers that -// describe the route from a FileDescriptorProto to the relevant submessage. -// The path alternates between a field number of a repeated field, and an index -// into that repeated field. The constants below define the field numbers that -// are used. -// -// See descriptor.proto for more information about this. -const ( - // tag numbers in FileDescriptorProto - packagePath = 2 // package - messagePath = 4 // message_type - enumPath = 5 // enum_type - // tag numbers in DescriptorProto - messageFieldPath = 2 // field - messageMessagePath = 3 // nested_type - messageEnumPath = 4 // enum_type - messageOneofPath = 8 // oneof_decl - // tag numbers in EnumDescriptorProto - enumValuePath = 2 // value -) - -var supportTypeAliases bool - -func init() { - for _, tag := range build.Default.ReleaseTags { - if tag == "go1.9" { - supportTypeAliases = true - return - } - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go b/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go deleted file mode 100755 index a9b6103..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go +++ /dev/null @@ -1,117 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package remap handles tracking the locations of Go tokens in a source text -across a rewrite by the Go formatter. -*/ -package remap - -import ( - "fmt" - "go/scanner" - "go/token" -) - -// A Location represents a span of byte offsets in the source text. -type Location struct { - Pos, End int // End is exclusive -} - -// A Map represents a mapping between token locations in an input source text -// and locations in the correspnding output text. -type Map map[Location]Location - -// Find reports whether the specified span is recorded by m, and if so returns -// the new location it was mapped to. If the input span was not found, the -// returned location is the same as the input. -func (m Map) Find(pos, end int) (Location, bool) { - key := Location{ - Pos: pos, - End: end, - } - if loc, ok := m[key]; ok { - return loc, true - } - return key, false -} - -func (m Map) add(opos, oend, npos, nend int) { - m[Location{Pos: opos, End: oend}] = Location{Pos: npos, End: nend} -} - -// Compute constructs a location mapping from input to output. An error is -// reported if any of the tokens of output cannot be mapped. -func Compute(input, output []byte) (Map, error) { - itok := tokenize(input) - otok := tokenize(output) - if len(itok) != len(otok) { - return nil, fmt.Errorf("wrong number of tokens, %d ≠ %d", len(itok), len(otok)) - } - m := make(Map) - for i, ti := range itok { - to := otok[i] - if ti.Token != to.Token { - return nil, fmt.Errorf("token %d type mismatch: %s ≠ %s", i+1, ti, to) - } - m.add(ti.pos, ti.end, to.pos, to.end) - } - return m, nil -} - -// tokinfo records the span and type of a source token. -type tokinfo struct { - pos, end int - token.Token -} - -func tokenize(src []byte) []tokinfo { - fs := token.NewFileSet() - var s scanner.Scanner - s.Init(fs.AddFile("src", fs.Base(), len(src)), src, nil, scanner.ScanComments) - var info []tokinfo - for { - pos, next, lit := s.Scan() - switch next { - case token.SEMICOLON: - continue - } - info = append(info, tokinfo{ - pos: int(pos - 1), - end: int(pos + token.Pos(len(lit)) - 1), - Token: next, - }) - if next == token.EOF { - break - } - } - return info -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go deleted file mode 100755 index ccc7fca..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package remap - -import ( - "go/format" - "testing" -) - -func TestErrors(t *testing.T) { - tests := []struct { - in, out string - }{ - {"", "x"}, - {"x", ""}, - {"var x int = 5\n", "var x = 5\n"}, - {"these are \"one\" thing", "those are 'another' thing"}, - } - for _, test := range tests { - m, err := Compute([]byte(test.in), []byte(test.out)) - if err != nil { - t.Logf("Got expected error: %v", err) - continue - } - t.Errorf("Compute(%q, %q): got %+v, wanted error", test.in, test.out, m) - } -} - -func TestMatching(t *testing.T) { - // The input is a source text that will be rearranged by the formatter. - const input = `package foo -var s int -func main(){} -` - - output, err := format.Source([]byte(input)) - if err != nil { - t.Fatalf("Formatting failed: %v", err) - } - m, err := Compute([]byte(input), output) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Verify that the mapped locations have the same text. - for key, val := range m { - want := input[key.Pos:key.End] - got := string(output[val.Pos:val.End]) - if got != want { - t.Errorf("Token at %d:%d: got %q, want %q", key.Pos, key.End, got, want) - } - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go deleted file mode 100755 index 571147c..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2013 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package generator - -import ( - "testing" - - "github.com/golang/protobuf/protoc-gen-go/descriptor" -) - -func TestCamelCase(t *testing.T) { - tests := []struct { - in, want string - }{ - {"one", "One"}, - {"one_two", "OneTwo"}, - {"_my_field_name_2", "XMyFieldName_2"}, - {"Something_Capped", "Something_Capped"}, - {"my_Name", "My_Name"}, - {"OneTwo", "OneTwo"}, - {"_", "X"}, - {"_a_", "XA_"}, - } - for _, tc := range tests { - if got := CamelCase(tc.in); got != tc.want { - t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) - } - } -} - -func TestGoPackageOption(t *testing.T) { - tests := []struct { - in string - impPath GoImportPath - pkg GoPackageName - ok bool - }{ - {"", "", "", false}, - {"foo", "", "foo", true}, - {"github.com/golang/bar", "github.com/golang/bar", "bar", true}, - {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true}, - } - for _, tc := range tests { - d := &FileDescriptor{ - FileDescriptorProto: &descriptor.FileDescriptorProto{ - Options: &descriptor.FileOptions{ - GoPackage: &tc.in, - }, - }, - } - impPath, pkg, ok := d.goPackageOption() - if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok { - t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in, - impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok) - } - } -} - -func TestUnescape(t *testing.T) { - tests := []struct { - in string - out string - }{ - // successful cases, including all kinds of escapes - {"", ""}, - {"foo bar baz frob nitz", "foo bar baz frob nitz"}, - {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})}, - {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})}, - {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})}, - // variable length octal escapes - {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})}, - // malformed escape sequences left as is - {"foo \\g bar", "foo \\g bar"}, - {"foo \\xg0 bar", "foo \\xg0 bar"}, - {"\\", "\\"}, - {"\\x", "\\x"}, - {"\\xf", "\\xf"}, - {"\\777", "\\777"}, // overflows byte - } - for _, tc := range tests { - s := unescape(tc.in) - if s != tc.out { - t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out) - } - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/golden_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/golden_test.go deleted file mode 100755 index 2630de6..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/golden_test.go +++ /dev/null @@ -1,422 +0,0 @@ -package main - -import ( - "bytes" - "flag" - "fmt" - "go/build" - "go/parser" - "go/token" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strings" - "testing" -) - -// Set --regenerate to regenerate the golden files. -var regenerate = flag.Bool("regenerate", false, "regenerate golden files") - -// When the environment variable RUN_AS_PROTOC_GEN_GO is set, we skip running -// tests and instead act as protoc-gen-go. This allows the test binary to -// pass itself to protoc. -func init() { - if os.Getenv("RUN_AS_PROTOC_GEN_GO") != "" { - main() - os.Exit(0) - } -} - -func TestGolden(t *testing.T) { - workdir, err := ioutil.TempDir("", "proto-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(workdir) - - // Find all the proto files we need to compile. We assume that each directory - // contains the files for a single package. - supportTypeAliases := hasReleaseTag("go1.9") - packages := map[string][]string{} - err = filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error { - if filepath.Base(path) == "import_public" && !supportTypeAliases { - // Public imports require type alias support. - return filepath.SkipDir - } - if !strings.HasSuffix(path, ".proto") { - return nil - } - dir := filepath.Dir(path) - packages[dir] = append(packages[dir], path) - return nil - }) - if err != nil { - t.Fatal(err) - } - - // Compile each package, using this binary as protoc-gen-go. - for _, sources := range packages { - args := []string{"-Itestdata", "--go_out=plugins=grpc,paths=source_relative:" + workdir} - args = append(args, sources...) - protoc(t, args) - } - - // Compare each generated file to the golden version. - filepath.Walk(workdir, func(genPath string, info os.FileInfo, _ error) error { - if info.IsDir() { - return nil - } - - // For each generated file, figure out the path to the corresponding - // golden file in the testdata directory. - relPath, err := filepath.Rel(workdir, genPath) - if err != nil { - t.Errorf("filepath.Rel(%q, %q): %v", workdir, genPath, err) - return nil - } - if filepath.SplitList(relPath)[0] == ".." { - t.Errorf("generated file %q is not relative to %q", genPath, workdir) - } - goldenPath := filepath.Join("testdata", relPath) - - got, err := ioutil.ReadFile(genPath) - if err != nil { - t.Error(err) - return nil - } - if *regenerate { - // If --regenerate set, just rewrite the golden files. - err := ioutil.WriteFile(goldenPath, got, 0666) - if err != nil { - t.Error(err) - } - return nil - } - - want, err := ioutil.ReadFile(goldenPath) - if err != nil { - t.Error(err) - return nil - } - - want = fdescRE.ReplaceAll(want, nil) - got = fdescRE.ReplaceAll(got, nil) - if bytes.Equal(got, want) { - return nil - } - - cmd := exec.Command("diff", "-u", goldenPath, genPath) - out, _ := cmd.CombinedOutput() - t.Errorf("golden file differs: %v\n%v", relPath, string(out)) - return nil - }) -} - -var fdescRE = regexp.MustCompile(`(?ms)^var fileDescriptor.*}`) - -// Source files used by TestParameters. -const ( - aProto = ` -syntax = "proto3"; -package test.alpha; -option go_package = "package/alpha"; -import "beta/b.proto"; -message M { test.beta.M field = 1; }` - - bProto = ` -syntax = "proto3"; -package test.beta; -// no go_package option -message M {}` -) - -func TestParameters(t *testing.T) { - for _, test := range []struct { - parameters string - wantFiles map[string]bool - wantImportsA map[string]bool - wantPackageA string - wantPackageB string - }{{ - parameters: "", - wantFiles: map[string]bool{ - "package/alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - wantImportsA: map[string]bool{ - "github.com/golang/protobuf/proto": true, - "beta": true, - }, - }, { - parameters: "import_prefix=prefix", - wantFiles: map[string]bool{ - "package/alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - wantImportsA: map[string]bool{ - // This really doesn't seem like useful behavior. - "prefixgithub.com/golang/protobuf/proto": true, - "prefixbeta": true, - }, - }, { - // import_path only affects the 'package' line. - parameters: "import_path=import/path/of/pkg", - wantPackageA: "alpha", - wantPackageB: "pkg", - wantFiles: map[string]bool{ - "package/alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - }, { - parameters: "Mbeta/b.proto=package/gamma", - wantFiles: map[string]bool{ - "package/alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - wantImportsA: map[string]bool{ - "github.com/golang/protobuf/proto": true, - // Rewritten by the M parameter. - "package/gamma": true, - }, - }, { - parameters: "import_prefix=prefix,Mbeta/b.proto=package/gamma", - wantFiles: map[string]bool{ - "package/alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - wantImportsA: map[string]bool{ - // import_prefix applies after M. - "prefixpackage/gamma": true, - }, - }, { - parameters: "paths=source_relative", - wantFiles: map[string]bool{ - "alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - }, { - parameters: "paths=source_relative,import_prefix=prefix", - wantFiles: map[string]bool{ - // import_prefix doesn't affect filenames. - "alpha/a.pb.go": true, - "beta/b.pb.go": true, - }, - wantPackageA: "alpha", - wantPackageB: "test_beta", - }} { - name := test.parameters - if name == "" { - name = "defaults" - } - // TODO: Switch to t.Run when we no longer support Go 1.6. - t.Logf("TEST: %v", name) - workdir, err := ioutil.TempDir("", "proto-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(workdir) - - for _, dir := range []string{"alpha", "beta", "out"} { - if err := os.MkdirAll(filepath.Join(workdir, dir), 0777); err != nil { - t.Fatal(err) - } - } - - if err := ioutil.WriteFile(filepath.Join(workdir, "alpha", "a.proto"), []byte(aProto), 0666); err != nil { - t.Fatal(err) - } - - if err := ioutil.WriteFile(filepath.Join(workdir, "beta", "b.proto"), []byte(bProto), 0666); err != nil { - t.Fatal(err) - } - - protoc(t, []string{ - "-I" + workdir, - "--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"), - filepath.Join(workdir, "alpha", "a.proto"), - }) - protoc(t, []string{ - "-I" + workdir, - "--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"), - filepath.Join(workdir, "beta", "b.proto"), - }) - - contents := make(map[string]string) - gotFiles := make(map[string]bool) - outdir := filepath.Join(workdir, "out") - filepath.Walk(outdir, func(p string, info os.FileInfo, _ error) error { - if info.IsDir() { - return nil - } - base := filepath.Base(p) - if base == "a.pb.go" || base == "b.pb.go" { - b, err := ioutil.ReadFile(p) - if err != nil { - t.Fatal(err) - } - contents[base] = string(b) - } - relPath, _ := filepath.Rel(outdir, p) - gotFiles[relPath] = true - return nil - }) - for got := range gotFiles { - if runtime.GOOS == "windows" { - got = filepath.ToSlash(got) - } - if !test.wantFiles[got] { - t.Errorf("unexpected output file: %v", got) - } - } - for want := range test.wantFiles { - if runtime.GOOS == "windows" { - want = filepath.FromSlash(want) - } - if !gotFiles[want] { - t.Errorf("missing output file: %v", want) - } - } - gotPackageA, gotImports, err := parseFile(contents["a.pb.go"]) - if err != nil { - t.Fatal(err) - } - gotPackageB, _, err := parseFile(contents["b.pb.go"]) - if err != nil { - t.Fatal(err) - } - if got, want := gotPackageA, test.wantPackageA; want != got { - t.Errorf("output file a.pb.go is package %q, want %q", got, want) - } - if got, want := gotPackageB, test.wantPackageB; want != got { - t.Errorf("output file b.pb.go is package %q, want %q", got, want) - } - missingImport := false - WantImport: - for want := range test.wantImportsA { - for _, imp := range gotImports { - if `"`+want+`"` == imp { - continue WantImport - } - } - t.Errorf("output file a.pb.go does not contain expected import %q", want) - missingImport = true - } - if missingImport { - t.Error("got imports:") - for _, imp := range gotImports { - t.Errorf(" %v", imp) - } - } - } -} - -func TestPackageComment(t *testing.T) { - workdir, err := ioutil.TempDir("", "proto-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(workdir) - - var packageRE = regexp.MustCompile(`(?m)^package .*`) - - for i, test := range []struct { - goPackageOption string - wantPackage string - }{{ - goPackageOption: ``, - wantPackage: `package proto_package`, - }, { - goPackageOption: `option go_package = "go_package";`, - wantPackage: `package go_package`, - }, { - goPackageOption: `option go_package = "import/path/of/go_package";`, - wantPackage: `package go_package // import "import/path/of/go_package"`, - }, { - goPackageOption: `option go_package = "import/path/of/something;go_package";`, - wantPackage: `package go_package // import "import/path/of/something"`, - }, { - goPackageOption: `option go_package = "import_path;go_package";`, - wantPackage: `package go_package // import "import_path"`, - }} { - srcName := filepath.Join(workdir, fmt.Sprintf("%d.proto", i)) - tgtName := filepath.Join(workdir, fmt.Sprintf("%d.pb.go", i)) - - buf := &bytes.Buffer{} - fmt.Fprintln(buf, `syntax = "proto3";`) - fmt.Fprintln(buf, `package proto_package;`) - fmt.Fprintln(buf, test.goPackageOption) - if err := ioutil.WriteFile(srcName, buf.Bytes(), 0666); err != nil { - t.Fatal(err) - } - - protoc(t, []string{"-I" + workdir, "--go_out=paths=source_relative:" + workdir, srcName}) - - out, err := ioutil.ReadFile(tgtName) - if err != nil { - t.Fatal(err) - } - - pkg := packageRE.Find(out) - if pkg == nil { - t.Errorf("generated .pb.go contains no package line\n\nsource:\n%v\n\noutput:\n%v", buf.String(), string(out)) - continue - } - - if got, want := string(pkg), test.wantPackage; got != want { - t.Errorf("unexpected package statement with go_package = %q\n got: %v\nwant: %v", test.goPackageOption, got, want) - } - } -} - -// parseFile returns a file's package name and a list of all packages it imports. -func parseFile(source string) (packageName string, imports []string, err error) { - fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "", source, parser.ImportsOnly) - if err != nil { - return "", nil, err - } - for _, imp := range f.Imports { - imports = append(imports, imp.Path.Value) - } - return f.Name.Name, imports, nil -} - -func protoc(t *testing.T, args []string) { - cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0]) - cmd.Args = append(cmd.Args, args...) - // We set the RUN_AS_PROTOC_GEN_GO environment variable to indicate that - // the subprocess should act as a proto compiler rather than a test. - cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_GEN_GO=1") - out, err := cmd.CombinedOutput() - if len(out) > 0 || err != nil { - t.Log("RUNNING: ", strings.Join(cmd.Args, " ")) - } - if len(out) > 0 { - t.Log(string(out)) - } - if err != nil { - t.Fatalf("protoc: %v", err) - } -} - -func hasReleaseTag(want string) bool { - for _, tag := range build.Default.ReleaseTags { - if tag == want { - return true - } - } - return false -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go b/examples/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go deleted file mode 100755 index 1723680..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go +++ /dev/null @@ -1,483 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Package grpc outputs gRPC service descriptions in Go code. -// It runs as a plugin for the Go protocol buffer compiler plugin. -// It is linked in to protoc-gen-go. -package grpc - -import ( - "fmt" - "path" - "strconv" - "strings" - - pb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/golang/protobuf/protoc-gen-go/generator" -) - -// generatedCodeVersion indicates a version of the generated code. -// It is incremented whenever an incompatibility between the generated code and -// the grpc package is introduced; the generated code references -// a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion). -const generatedCodeVersion = 4 - -// Paths for packages used by code generated in this file, -// relative to the import_prefix of the generator.Generator. -const ( - contextPkgPath = "golang.org/x/net/context" - grpcPkgPath = "google.golang.org/grpc" -) - -func init() { - generator.RegisterPlugin(new(grpc)) -} - -// grpc is an implementation of the Go protocol buffer compiler's -// plugin architecture. It generates bindings for gRPC support. -type grpc struct { - gen *generator.Generator -} - -// Name returns the name of this plugin, "grpc". -func (g *grpc) Name() string { - return "grpc" -} - -// The names for packages imported in the generated code. -// They may vary from the final path component of the import path -// if the name is used by other packages. -var ( - contextPkg string - grpcPkg string -) - -// Init initializes the plugin. -func (g *grpc) Init(gen *generator.Generator) { - g.gen = gen - contextPkg = generator.RegisterUniquePackageName("context", nil) - grpcPkg = generator.RegisterUniquePackageName("grpc", nil) -} - -// Given a type name defined in a .proto, return its object. -// Also record that we're using it, to guarantee the associated import. -func (g *grpc) objectNamed(name string) generator.Object { - g.gen.RecordTypeUse(name) - return g.gen.ObjectNamed(name) -} - -// Given a type name defined in a .proto, return its name as we will print it. -func (g *grpc) typeName(str string) string { - return g.gen.TypeName(g.objectNamed(str)) -} - -// P forwards to g.gen.P. -func (g *grpc) P(args ...interface{}) { g.gen.P(args...) } - -// Generate generates code for the services in the given file. -func (g *grpc) Generate(file *generator.FileDescriptor) { - if len(file.FileDescriptorProto.Service) == 0 { - return - } - - g.P("// Reference imports to suppress errors if they are not otherwise used.") - g.P("var _ ", contextPkg, ".Context") - g.P("var _ ", grpcPkg, ".ClientConn") - g.P() - - // Assert version compatibility. - g.P("// This is a compile-time assertion to ensure that this generated file") - g.P("// is compatible with the grpc package it is being compiled against.") - g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion) - g.P() - - for i, service := range file.FileDescriptorProto.Service { - g.generateService(file, service, i) - } -} - -// GenerateImports generates the import declaration for this file. -func (g *grpc) GenerateImports(file *generator.FileDescriptor) { - if len(file.FileDescriptorProto.Service) == 0 { - return - } - g.P("import (") - g.P(contextPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), contextPkgPath))) - g.P(grpcPkg, " ", generator.GoImportPath(path.Join(string(g.gen.ImportPrefix), grpcPkgPath))) - g.P(")") - g.P() -} - -// reservedClientName records whether a client name is reserved on the client side. -var reservedClientName = map[string]bool{ - // TODO: do we need any in gRPC? -} - -func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } - -// deprecationComment is the standard comment added to deprecated -// messages, fields, enums, and enum values. -var deprecationComment = "// Deprecated: Do not use." - -// generateService generates all the code for the named service. -func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { - path := fmt.Sprintf("6,%d", index) // 6 means service. - - origServName := service.GetName() - fullServName := origServName - if pkg := file.GetPackage(); pkg != "" { - fullServName = pkg + "." + fullServName - } - servName := generator.CamelCase(origServName) - deprecated := service.GetOptions().GetDeprecated() - - g.P() - g.P("// Client API for ", servName, " service") - g.P() - - // Client interface. - if deprecated { - g.P(deprecationComment) - } - g.P("type ", servName, "Client interface {") - for i, method := range service.Method { - g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. - g.P(g.generateClientSignature(servName, method)) - } - g.P("}") - g.P() - - // Client structure. - g.P("type ", unexport(servName), "Client struct {") - g.P("cc *", grpcPkg, ".ClientConn") - g.P("}") - g.P() - - // NewClient factory. - if deprecated { - g.P(deprecationComment) - } - g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") - g.P("return &", unexport(servName), "Client{cc}") - g.P("}") - g.P() - - var methodIndex, streamIndex int - serviceDescVar := "_" + servName + "_serviceDesc" - // Client method implementations. - for _, method := range service.Method { - var descExpr string - if !method.GetServerStreaming() && !method.GetClientStreaming() { - // Unary RPC method - descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) - methodIndex++ - } else { - // Streaming RPC method - descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) - streamIndex++ - } - g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) - } - - g.P("// Server API for ", servName, " service") - g.P() - - // Server interface. - if deprecated { - g.P(deprecationComment) - } - serverType := servName + "Server" - g.P("type ", serverType, " interface {") - for i, method := range service.Method { - g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. - g.P(g.generateServerSignature(servName, method)) - } - g.P("}") - g.P() - - // Server registration. - if deprecated { - g.P(deprecationComment) - } - g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") - g.P("s.RegisterService(&", serviceDescVar, `, srv)`) - g.P("}") - g.P() - - // Server handler implementations. - var handlerNames []string - for _, method := range service.Method { - hname := g.generateServerMethod(servName, fullServName, method) - handlerNames = append(handlerNames, hname) - } - - // Service descriptor. - g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") - g.P("ServiceName: ", strconv.Quote(fullServName), ",") - g.P("HandlerType: (*", serverType, ")(nil),") - g.P("Methods: []", grpcPkg, ".MethodDesc{") - for i, method := range service.Method { - if method.GetServerStreaming() || method.GetClientStreaming() { - continue - } - g.P("{") - g.P("MethodName: ", strconv.Quote(method.GetName()), ",") - g.P("Handler: ", handlerNames[i], ",") - g.P("},") - } - g.P("},") - g.P("Streams: []", grpcPkg, ".StreamDesc{") - for i, method := range service.Method { - if !method.GetServerStreaming() && !method.GetClientStreaming() { - continue - } - g.P("{") - g.P("StreamName: ", strconv.Quote(method.GetName()), ",") - g.P("Handler: ", handlerNames[i], ",") - if method.GetServerStreaming() { - g.P("ServerStreams: true,") - } - if method.GetClientStreaming() { - g.P("ClientStreams: true,") - } - g.P("},") - } - g.P("},") - g.P("Metadata: \"", file.GetName(), "\",") - g.P("}") - g.P() -} - -// generateClientSignature returns the client-side signature for a method. -func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { - origMethName := method.GetName() - methName := generator.CamelCase(origMethName) - if reservedClientName[methName] { - methName += "_" - } - reqArg := ", in *" + g.typeName(method.GetInputType()) - if method.GetClientStreaming() { - reqArg = "" - } - respName := "*" + g.typeName(method.GetOutputType()) - if method.GetServerStreaming() || method.GetClientStreaming() { - respName = servName + "_" + generator.CamelCase(origMethName) + "Client" - } - return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) -} - -func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { - sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) - methName := generator.CamelCase(method.GetName()) - inType := g.typeName(method.GetInputType()) - outType := g.typeName(method.GetOutputType()) - - if method.GetOptions().GetDeprecated() { - g.P(deprecationComment) - } - g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") - if !method.GetServerStreaming() && !method.GetClientStreaming() { - g.P("out := new(", outType, ")") - // TODO: Pass descExpr to Invoke. - g.P("err := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, opts...)`) - g.P("if err != nil { return nil, err }") - g.P("return out, nil") - g.P("}") - g.P() - return - } - streamType := unexport(servName) + methName + "Client" - g.P("stream, err := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, sname, `", opts...)`) - g.P("if err != nil { return nil, err }") - g.P("x := &", streamType, "{stream}") - if !method.GetClientStreaming() { - g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") - g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") - } - g.P("return x, nil") - g.P("}") - g.P() - - genSend := method.GetClientStreaming() - genRecv := method.GetServerStreaming() - genCloseAndRecv := !method.GetServerStreaming() - - // Stream auxiliary types and methods. - g.P("type ", servName, "_", methName, "Client interface {") - if genSend { - g.P("Send(*", inType, ") error") - } - if genRecv { - g.P("Recv() (*", outType, ", error)") - } - if genCloseAndRecv { - g.P("CloseAndRecv() (*", outType, ", error)") - } - g.P(grpcPkg, ".ClientStream") - g.P("}") - g.P() - - g.P("type ", streamType, " struct {") - g.P(grpcPkg, ".ClientStream") - g.P("}") - g.P() - - if genSend { - g.P("func (x *", streamType, ") Send(m *", inType, ") error {") - g.P("return x.ClientStream.SendMsg(m)") - g.P("}") - g.P() - } - if genRecv { - g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") - g.P("m := new(", outType, ")") - g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } - if genCloseAndRecv { - g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") - g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") - g.P("m := new(", outType, ")") - g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } -} - -// generateServerSignature returns the server-side signature for a method. -func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { - origMethName := method.GetName() - methName := generator.CamelCase(origMethName) - if reservedClientName[methName] { - methName += "_" - } - - var reqArgs []string - ret := "error" - if !method.GetServerStreaming() && !method.GetClientStreaming() { - reqArgs = append(reqArgs, contextPkg+".Context") - ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" - } - if !method.GetClientStreaming() { - reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) - } - if method.GetServerStreaming() || method.GetClientStreaming() { - reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") - } - - return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret -} - -func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { - methName := generator.CamelCase(method.GetName()) - hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) - inType := g.typeName(method.GetInputType()) - outType := g.typeName(method.GetOutputType()) - - if !method.GetServerStreaming() && !method.GetClientStreaming() { - g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {") - g.P("in := new(", inType, ")") - g.P("if err := dec(in); err != nil { return nil, err }") - g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }") - g.P("info := &", grpcPkg, ".UnaryServerInfo{") - g.P("Server: srv,") - g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",") - g.P("}") - g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {") - g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))") - g.P("}") - g.P("return interceptor(ctx, in, info, handler)") - g.P("}") - g.P() - return hname - } - streamType := unexport(servName) + methName + "Server" - g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") - if !method.GetClientStreaming() { - g.P("m := new(", inType, ")") - g.P("if err := stream.RecvMsg(m); err != nil { return err }") - g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") - } else { - g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") - } - g.P("}") - g.P() - - genSend := method.GetServerStreaming() - genSendAndClose := !method.GetServerStreaming() - genRecv := method.GetClientStreaming() - - // Stream auxiliary types and methods. - g.P("type ", servName, "_", methName, "Server interface {") - if genSend { - g.P("Send(*", outType, ") error") - } - if genSendAndClose { - g.P("SendAndClose(*", outType, ") error") - } - if genRecv { - g.P("Recv() (*", inType, ", error)") - } - g.P(grpcPkg, ".ServerStream") - g.P("}") - g.P() - - g.P("type ", streamType, " struct {") - g.P(grpcPkg, ".ServerStream") - g.P("}") - g.P() - - if genSend { - g.P("func (x *", streamType, ") Send(m *", outType, ") error {") - g.P("return x.ServerStream.SendMsg(m)") - g.P("}") - g.P() - } - if genSendAndClose { - g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") - g.P("return x.ServerStream.SendMsg(m)") - g.P("}") - g.P() - } - if genRecv { - g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") - g.P("m := new(", inType, ")") - g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } - - return hname -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/link_grpc.go b/examples/github.com/golang/protobuf/protoc-gen-go/link_grpc.go deleted file mode 100755 index 532a550..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/link_grpc.go +++ /dev/null @@ -1,34 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package main - -import _ "github.com/golang/protobuf/protoc-gen-go/grpc" diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/main.go b/examples/github.com/golang/protobuf/protoc-gen-go/main.go deleted file mode 100755 index 8e2486d..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/main.go +++ /dev/null @@ -1,98 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate -// Go code. Run it by building this program and putting it in your path with -// the name -// protoc-gen-go -// That word 'go' at the end becomes part of the option string set for the -// protocol compiler, so once the protocol compiler (protoc) is installed -// you can run -// protoc --go_out=output_directory input_directory/file.proto -// to generate Go bindings for the protocol defined by file.proto. -// With that input, the output will be written to -// output_directory/file.pb.go -// -// The generated code is documented in the package comment for -// the library. -// -// See the README and documentation for protocol buffers to learn more: -// https://developers.google.com/protocol-buffers/ -package main - -import ( - "io/ioutil" - "os" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/protoc-gen-go/generator" -) - -func main() { - // Begin by allocating a generator. The request and response structures are stored there - // so we can do error handling easily - the response structure contains the field to - // report failure. - g := generator.New() - - data, err := ioutil.ReadAll(os.Stdin) - if err != nil { - g.Error(err, "reading input") - } - - if err := proto.Unmarshal(data, g.Request); err != nil { - g.Error(err, "parsing input proto") - } - - if len(g.Request.FileToGenerate) == 0 { - g.Fail("no files to generate") - } - - g.CommandLineParameters(g.Request.GetParameter()) - - // Create a wrapped version of the Descriptors and EnumDescriptors that - // point to the file that defines them. - g.WrapTypes() - - g.SetPackageNames() - g.BuildTypeNameMap() - - g.GenerateAllFiles() - - // Send back the results. - data, err = proto.Marshal(g.Response) - if err != nil { - g.Error(err, "failed to marshal output proto") - } - _, err = os.Stdout.Write(data) - if err != nil { - g.Error(err, "failed to write output proto") - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go deleted file mode 100755 index 61bfc10..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go +++ /dev/null @@ -1,369 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/compiler/plugin.proto - -/* -Package plugin_go is a generated protocol buffer package. - -It is generated from these files: - google/protobuf/compiler/plugin.proto - -It has these top-level messages: - Version - CodeGeneratorRequest - CodeGeneratorResponse -*/ -package plugin_go - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The version number of protocol compiler. -type Version struct { - Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"` - Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"` - Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"` - // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should - // be empty for mainline stable releases. - Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Version) Reset() { *m = Version{} } -func (m *Version) String() string { return proto.CompactTextString(m) } -func (*Version) ProtoMessage() {} -func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } -func (m *Version) Unmarshal(b []byte) error { - return xxx_messageInfo_Version.Unmarshal(m, b) -} -func (m *Version) Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Version.Marshal(b, m, deterministic) -} -func (dst *Version) XXX_Merge(src proto.Message) { - xxx_messageInfo_Version.Merge(dst, src) -} -func (m *Version) XXX_Size() int { - return xxx_messageInfo_Version.Size(m) -} -func (m *Version) XXX_DiscardUnknown() { - xxx_messageInfo_Version.DiscardUnknown(m) -} - -var xxx_messageInfo_Version proto.InternalMessageInfo - -func (m *Version) GetMajor() int32 { - if m != nil && m.Major != nil { - return *m.Major - } - return 0 -} - -func (m *Version) GetMinor() int32 { - if m != nil && m.Minor != nil { - return *m.Minor - } - return 0 -} - -func (m *Version) GetPatch() int32 { - if m != nil && m.Patch != nil { - return *m.Patch - } - return 0 -} - -func (m *Version) GetSuffix() string { - if m != nil && m.Suffix != nil { - return *m.Suffix - } - return "" -} - -// An encoded CodeGeneratorRequest is written to the plugin's stdin. -type CodeGeneratorRequest struct { - // The .proto files that were explicitly listed on the command-line. The - // code generator should generate code only for these files. Each file's - // descriptor will be included in proto_file, below. - FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"` - // The generator parameter passed on the command-line. - Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` - // FileDescriptorProtos for all files in files_to_generate and everything - // they import. The files will appear in topological order, so each file - // appears before any file that imports it. - // - // protoc guarantees that all proto_files will be written after - // the fields above, even though this is not technically guaranteed by the - // protobuf wire format. This theoretically could allow a plugin to stream - // in the FileDescriptorProtos and handle them one by one rather than read - // the entire set into memory at once. However, as of this writing, this - // is not similarly optimized on protoc's end -- it will store all fields in - // memory at once before sending them to the plugin. - // - // Type names of fields and extensions in the FileDescriptorProto are always - // fully qualified. - ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"` - // The version number of protocol compiler. - CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} } -func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) } -func (*CodeGeneratorRequest) ProtoMessage() {} -func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } -func (m *CodeGeneratorRequest) Unmarshal(b []byte) error { - return xxx_messageInfo_CodeGeneratorRequest.Unmarshal(m, b) -} -func (m *CodeGeneratorRequest) Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CodeGeneratorRequest.Marshal(b, m, deterministic) -} -func (dst *CodeGeneratorRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeGeneratorRequest.Merge(dst, src) -} -func (m *CodeGeneratorRequest) XXX_Size() int { - return xxx_messageInfo_CodeGeneratorRequest.Size(m) -} -func (m *CodeGeneratorRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CodeGeneratorRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeGeneratorRequest proto.InternalMessageInfo - -func (m *CodeGeneratorRequest) GetFileToGenerate() []string { - if m != nil { - return m.FileToGenerate - } - return nil -} - -func (m *CodeGeneratorRequest) GetParameter() string { - if m != nil && m.Parameter != nil { - return *m.Parameter - } - return "" -} - -func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto { - if m != nil { - return m.ProtoFile - } - return nil -} - -func (m *CodeGeneratorRequest) GetCompilerVersion() *Version { - if m != nil { - return m.CompilerVersion - } - return nil -} - -// The plugin writes an encoded CodeGeneratorResponse to stdout. -type CodeGeneratorResponse struct { - // Error message. If non-empty, code generation failed. The plugin process - // should exit with status code zero even if it reports an error in this way. - // - // This should be used to indicate errors in .proto files which prevent the - // code generator from generating correct code. Errors which indicate a - // problem in protoc itself -- such as the input CodeGeneratorRequest being - // unparseable -- should be reported by writing a message to stderr and - // exiting with a non-zero status code. - Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` - File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} } -func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) } -func (*CodeGeneratorResponse) ProtoMessage() {} -func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } -func (m *CodeGeneratorResponse) Unmarshal(b []byte) error { - return xxx_messageInfo_CodeGeneratorResponse.Unmarshal(m, b) -} -func (m *CodeGeneratorResponse) Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CodeGeneratorResponse.Marshal(b, m, deterministic) -} -func (dst *CodeGeneratorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeGeneratorResponse.Merge(dst, src) -} -func (m *CodeGeneratorResponse) XXX_Size() int { - return xxx_messageInfo_CodeGeneratorResponse.Size(m) -} -func (m *CodeGeneratorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CodeGeneratorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeGeneratorResponse proto.InternalMessageInfo - -func (m *CodeGeneratorResponse) GetError() string { - if m != nil && m.Error != nil { - return *m.Error - } - return "" -} - -func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File { - if m != nil { - return m.File - } - return nil -} - -// Represents a single generated file. -type CodeGeneratorResponse_File struct { - // The file name, relative to the output directory. The name must not - // contain "." or ".." components and must be relative, not be absolute (so, - // the file cannot lie outside the output directory). "/" must be used as - // the path separator, not "\". - // - // If the name is omitted, the content will be appended to the previous - // file. This allows the generator to break large files into small chunks, - // and allows the generated text to be streamed back to protoc so that large - // files need not reside completely in memory at one time. Note that as of - // this writing protoc does not optimize for this -- it will read the entire - // CodeGeneratorResponse before writing files to disk. - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // If non-empty, indicates that the named file should already exist, and the - // content here is to be inserted into that file at a defined insertion - // point. This feature allows a code generator to extend the output - // produced by another code generator. The original generator may provide - // insertion points by placing special annotations in the file that look - // like: - // @@protoc_insertion_point(NAME) - // The annotation can have arbitrary text before and after it on the line, - // which allows it to be placed in a comment. NAME should be replaced with - // an identifier naming the point -- this is what other generators will use - // as the insertion_point. Code inserted at this point will be placed - // immediately above the line containing the insertion point (thus multiple - // insertions to the same point will come out in the order they were added). - // The double-@ is intended to make it unlikely that the generated code - // could contain things that look like insertion points by accident. - // - // For example, the C++ code generator places the following line in the - // .pb.h files that it generates: - // // @@protoc_insertion_point(namespace_scope) - // This line appears within the scope of the file's package namespace, but - // outside of any particular class. Another plugin can then specify the - // insertion_point "namespace_scope" to generate additional classes or - // other declarations that should be placed in this scope. - // - // Note that if the line containing the insertion point begins with - // whitespace, the same whitespace will be added to every line of the - // inserted text. This is useful for languages like Python, where - // indentation matters. In these languages, the insertion point comment - // should be indented the same amount as any inserted code will need to be - // in order to work correctly in that context. - // - // The code generator that generates the initial file and the one which - // inserts into it must both run as part of a single invocation of protoc. - // Code generators are executed in the order in which they appear on the - // command line. - // - // If |insertion_point| is present, |name| must also be present. - InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"` - // The file contents. - Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} } -func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) } -func (*CodeGeneratorResponse_File) ProtoMessage() {} -func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } -func (m *CodeGeneratorResponse_File) Unmarshal(b []byte) error { - return xxx_messageInfo_CodeGeneratorResponse_File.Unmarshal(m, b) -} -func (m *CodeGeneratorResponse_File) Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CodeGeneratorResponse_File.Marshal(b, m, deterministic) -} -func (dst *CodeGeneratorResponse_File) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeGeneratorResponse_File.Merge(dst, src) -} -func (m *CodeGeneratorResponse_File) XXX_Size() int { - return xxx_messageInfo_CodeGeneratorResponse_File.Size(m) -} -func (m *CodeGeneratorResponse_File) XXX_DiscardUnknown() { - xxx_messageInfo_CodeGeneratorResponse_File.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeGeneratorResponse_File proto.InternalMessageInfo - -func (m *CodeGeneratorResponse_File) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *CodeGeneratorResponse_File) GetInsertionPoint() string { - if m != nil && m.InsertionPoint != nil { - return *m.InsertionPoint - } - return "" -} - -func (m *CodeGeneratorResponse_File) GetContent() string { - if m != nil && m.Content != nil { - return *m.Content - } - return "" -} - -func init() { - proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version") - proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest") - proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse") - proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File") -} - -func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 417 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41, - 0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2, - 0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30, - 0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa, - 0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91, - 0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63, - 0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb, - 0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55, - 0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8, - 0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1, - 0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f, - 0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d, - 0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2, - 0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a, - 0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2, - 0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d, - 0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda, - 0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed, - 0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34, - 0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79, - 0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45, - 0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4, - 0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e, - 0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92, - 0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d, - 0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00, - 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden b/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden deleted file mode 100755 index 8953d0f..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google/protobuf/compiler/plugin.proto -// DO NOT EDIT! - -package google_protobuf_compiler - -import proto "github.com/golang/protobuf/proto" -import "math" -import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" - -// Reference proto and math imports to suppress error if they are not otherwise used. -var _ = proto.GetString -var _ = math.Inf - -type CodeGeneratorRequest struct { - FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"` - Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` - ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} } -func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) } -func (*CodeGeneratorRequest) ProtoMessage() {} - -func (this *CodeGeneratorRequest) GetParameter() string { - if this != nil && this.Parameter != nil { - return *this.Parameter - } - return "" -} - -type CodeGeneratorResponse struct { - Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` - File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} } -func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) } -func (*CodeGeneratorResponse) ProtoMessage() {} - -func (this *CodeGeneratorResponse) GetError() string { - if this != nil && this.Error != nil { - return *this.Error - } - return "" -} - -type CodeGeneratorResponse_File struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"` - Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} } -func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) } -func (*CodeGeneratorResponse_File) ProtoMessage() {} - -func (this *CodeGeneratorResponse_File) GetName() string { - if this != nil && this.Name != nil { - return *this.Name - } - return "" -} - -func (this *CodeGeneratorResponse_File) GetInsertionPoint() string { - if this != nil && this.InsertionPoint != nil { - return *this.InsertionPoint - } - return "" -} - -func (this *CodeGeneratorResponse_File) GetContent() string { - if this != nil && this.Content != nil { - return *this.Content - } - return "" -} - -func init() { -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto b/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto deleted file mode 100755 index 5b55745..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto +++ /dev/null @@ -1,167 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// -// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to -// change. -// -// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is -// just a program that reads a CodeGeneratorRequest from stdin and writes a -// CodeGeneratorResponse to stdout. -// -// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead -// of dealing with the raw protocol defined here. -// -// A plugin executable needs only to be placed somewhere in the path. The -// plugin should be named "protoc-gen-$NAME", and will then be used when the -// flag "--${NAME}_out" is passed to protoc. - -syntax = "proto2"; -package google.protobuf.compiler; -option java_package = "com.google.protobuf.compiler"; -option java_outer_classname = "PluginProtos"; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go"; - -import "google/protobuf/descriptor.proto"; - -// The version number of protocol compiler. -message Version { - optional int32 major = 1; - optional int32 minor = 2; - optional int32 patch = 3; - // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should - // be empty for mainline stable releases. - optional string suffix = 4; -} - -// An encoded CodeGeneratorRequest is written to the plugin's stdin. -message CodeGeneratorRequest { - // The .proto files that were explicitly listed on the command-line. The - // code generator should generate code only for these files. Each file's - // descriptor will be included in proto_file, below. - repeated string file_to_generate = 1; - - // The generator parameter passed on the command-line. - optional string parameter = 2; - - // FileDescriptorProtos for all files in files_to_generate and everything - // they import. The files will appear in topological order, so each file - // appears before any file that imports it. - // - // protoc guarantees that all proto_files will be written after - // the fields above, even though this is not technically guaranteed by the - // protobuf wire format. This theoretically could allow a plugin to stream - // in the FileDescriptorProtos and handle them one by one rather than read - // the entire set into memory at once. However, as of this writing, this - // is not similarly optimized on protoc's end -- it will store all fields in - // memory at once before sending them to the plugin. - // - // Type names of fields and extensions in the FileDescriptorProto are always - // fully qualified. - repeated FileDescriptorProto proto_file = 15; - - // The version number of protocol compiler. - optional Version compiler_version = 3; - -} - -// The plugin writes an encoded CodeGeneratorResponse to stdout. -message CodeGeneratorResponse { - // Error message. If non-empty, code generation failed. The plugin process - // should exit with status code zero even if it reports an error in this way. - // - // This should be used to indicate errors in .proto files which prevent the - // code generator from generating correct code. Errors which indicate a - // problem in protoc itself -- such as the input CodeGeneratorRequest being - // unparseable -- should be reported by writing a message to stderr and - // exiting with a non-zero status code. - optional string error = 1; - - // Represents a single generated file. - message File { - // The file name, relative to the output directory. The name must not - // contain "." or ".." components and must be relative, not be absolute (so, - // the file cannot lie outside the output directory). "/" must be used as - // the path separator, not "\". - // - // If the name is omitted, the content will be appended to the previous - // file. This allows the generator to break large files into small chunks, - // and allows the generated text to be streamed back to protoc so that large - // files need not reside completely in memory at one time. Note that as of - // this writing protoc does not optimize for this -- it will read the entire - // CodeGeneratorResponse before writing files to disk. - optional string name = 1; - - // If non-empty, indicates that the named file should already exist, and the - // content here is to be inserted into that file at a defined insertion - // point. This feature allows a code generator to extend the output - // produced by another code generator. The original generator may provide - // insertion points by placing special annotations in the file that look - // like: - // @@protoc_insertion_point(NAME) - // The annotation can have arbitrary text before and after it on the line, - // which allows it to be placed in a comment. NAME should be replaced with - // an identifier naming the point -- this is what other generators will use - // as the insertion_point. Code inserted at this point will be placed - // immediately above the line containing the insertion point (thus multiple - // insertions to the same point will come out in the order they were added). - // The double-@ is intended to make it unlikely that the generated code - // could contain things that look like insertion points by accident. - // - // For example, the C++ code generator places the following line in the - // .pb.h files that it generates: - // // @@protoc_insertion_point(namespace_scope) - // This line appears within the scope of the file's package namespace, but - // outside of any particular class. Another plugin can then specify the - // insertion_point "namespace_scope" to generate additional classes or - // other declarations that should be placed in this scope. - // - // Note that if the line containing the insertion point begins with - // whitespace, the same whitespace will be added to every line of the - // inserted text. This is useful for languages like Python, where - // indentation matters. In these languages, the insertion point comment - // should be indented the same amount as any inserted code will need to be - // in order to work correctly in that context. - // - // The code generator that generates the initial file and the one which - // inserts into it must both run as part of a single invocation of protoc. - // Code generators are executed in the order in which they appear on the - // command line. - // - // If |insertion_point| is present, |name| must also be present. - optional string insertion_point = 2; - - // The file contents. - optional string content = 15; - } - repeated File file = 15; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go deleted file mode 100755 index 6ebae9d..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.pb.go +++ /dev/null @@ -1,232 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// deprecated/deprecated.proto is a deprecated file. - -package deprecated // import "github.com/golang/protobuf/protoc-gen-go/testdata/deprecated" - -/* -package deprecated contains only deprecated messages and services. -*/ - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// DeprecatedEnum contains deprecated values. -type DeprecatedEnum int32 // Deprecated: Do not use. -const ( - // DEPRECATED is the iota value of this enum. - DeprecatedEnum_DEPRECATED DeprecatedEnum = 0 // Deprecated: Do not use. -) - -var DeprecatedEnum_name = map[int32]string{ - 0: "DEPRECATED", -} -var DeprecatedEnum_value = map[string]int32{ - "DEPRECATED": 0, -} - -func (x DeprecatedEnum) String() string { - return proto.EnumName(DeprecatedEnum_name, int32(x)) -} -func (DeprecatedEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_deprecated_9e1889ba21817fad, []int{0} -} - -// DeprecatedRequest is a request to DeprecatedCall. -// -// Deprecated: Do not use. -type DeprecatedRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeprecatedRequest) Reset() { *m = DeprecatedRequest{} } -func (m *DeprecatedRequest) String() string { return proto.CompactTextString(m) } -func (*DeprecatedRequest) ProtoMessage() {} -func (*DeprecatedRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_deprecated_9e1889ba21817fad, []int{0} -} -func (m *DeprecatedRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeprecatedRequest.Unmarshal(m, b) -} -func (m *DeprecatedRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeprecatedRequest.Marshal(b, m, deterministic) -} -func (dst *DeprecatedRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeprecatedRequest.Merge(dst, src) -} -func (m *DeprecatedRequest) XXX_Size() int { - return xxx_messageInfo_DeprecatedRequest.Size(m) -} -func (m *DeprecatedRequest) XXX_DiscardUnknown() { - xxx_messageInfo_DeprecatedRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_DeprecatedRequest proto.InternalMessageInfo - -// Deprecated: Do not use. -type DeprecatedResponse struct { - // DeprecatedField contains a DeprecatedEnum. - DeprecatedField DeprecatedEnum `protobuf:"varint,1,opt,name=deprecated_field,json=deprecatedField,enum=deprecated.DeprecatedEnum" json:"deprecated_field,omitempty"` // Deprecated: Do not use. - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeprecatedResponse) Reset() { *m = DeprecatedResponse{} } -func (m *DeprecatedResponse) String() string { return proto.CompactTextString(m) } -func (*DeprecatedResponse) ProtoMessage() {} -func (*DeprecatedResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_deprecated_9e1889ba21817fad, []int{1} -} -func (m *DeprecatedResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeprecatedResponse.Unmarshal(m, b) -} -func (m *DeprecatedResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeprecatedResponse.Marshal(b, m, deterministic) -} -func (dst *DeprecatedResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeprecatedResponse.Merge(dst, src) -} -func (m *DeprecatedResponse) XXX_Size() int { - return xxx_messageInfo_DeprecatedResponse.Size(m) -} -func (m *DeprecatedResponse) XXX_DiscardUnknown() { - xxx_messageInfo_DeprecatedResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_DeprecatedResponse proto.InternalMessageInfo - -// Deprecated: Do not use. -func (m *DeprecatedResponse) GetDeprecatedField() DeprecatedEnum { - if m != nil { - return m.DeprecatedField - } - return DeprecatedEnum_DEPRECATED -} - -func init() { - proto.RegisterType((*DeprecatedRequest)(nil), "deprecated.DeprecatedRequest") - proto.RegisterType((*DeprecatedResponse)(nil), "deprecated.DeprecatedResponse") - proto.RegisterEnum("deprecated.DeprecatedEnum", DeprecatedEnum_name, DeprecatedEnum_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for DeprecatedService service - -// Deprecated: Do not use. -type DeprecatedServiceClient interface { - // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse. - DeprecatedCall(ctx context.Context, in *DeprecatedRequest, opts ...grpc.CallOption) (*DeprecatedResponse, error) -} - -type deprecatedServiceClient struct { - cc *grpc.ClientConn -} - -// Deprecated: Do not use. -func NewDeprecatedServiceClient(cc *grpc.ClientConn) DeprecatedServiceClient { - return &deprecatedServiceClient{cc} -} - -// Deprecated: Do not use. -func (c *deprecatedServiceClient) DeprecatedCall(ctx context.Context, in *DeprecatedRequest, opts ...grpc.CallOption) (*DeprecatedResponse, error) { - out := new(DeprecatedResponse) - err := grpc.Invoke(ctx, "/deprecated.DeprecatedService/DeprecatedCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for DeprecatedService service - -// Deprecated: Do not use. -type DeprecatedServiceServer interface { - // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse. - DeprecatedCall(context.Context, *DeprecatedRequest) (*DeprecatedResponse, error) -} - -// Deprecated: Do not use. -func RegisterDeprecatedServiceServer(s *grpc.Server, srv DeprecatedServiceServer) { - s.RegisterService(&_DeprecatedService_serviceDesc, srv) -} - -func _DeprecatedService_DeprecatedCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeprecatedRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(DeprecatedServiceServer).DeprecatedCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/deprecated.DeprecatedService/DeprecatedCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(DeprecatedServiceServer).DeprecatedCall(ctx, req.(*DeprecatedRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _DeprecatedService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "deprecated.DeprecatedService", - HandlerType: (*DeprecatedServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "DeprecatedCall", - Handler: _DeprecatedService_DeprecatedCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "deprecated/deprecated.proto", -} - -func init() { - proto.RegisterFile("deprecated/deprecated.proto", fileDescriptor_deprecated_9e1889ba21817fad) -} - -var fileDescriptor_deprecated_9e1889ba21817fad = []byte{ - // 248 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0x49, 0x2d, 0x28, - 0x4a, 0x4d, 0x4e, 0x2c, 0x49, 0x4d, 0xd1, 0x47, 0x30, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, - 0xb8, 0x10, 0x22, 0x4a, 0xe2, 0x5c, 0x82, 0x2e, 0x70, 0x5e, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, - 0x89, 0x15, 0x93, 0x04, 0xa3, 0x52, 0x32, 0x97, 0x10, 0xb2, 0x44, 0x71, 0x41, 0x7e, 0x5e, 0x71, - 0xaa, 0x90, 0x27, 0x97, 0x00, 0x42, 0x73, 0x7c, 0x5a, 0x66, 0x6a, 0x4e, 0x8a, 0x04, 0xa3, 0x02, - 0xa3, 0x06, 0x9f, 0x91, 0x94, 0x1e, 0x92, 0x3d, 0x08, 0x9d, 0xae, 0x79, 0xa5, 0xb9, 0x4e, 0x4c, - 0x12, 0x8c, 0x41, 0xfc, 0x08, 0x69, 0x37, 0x90, 0x36, 0x90, 0x25, 0x5a, 0x1a, 0x5c, 0x7c, 0xa8, - 0x4a, 0x85, 0x84, 0xb8, 0xb8, 0x5c, 0x5c, 0x03, 0x82, 0x5c, 0x9d, 0x1d, 0x43, 0x5c, 0x5d, 0x04, - 0x18, 0xa4, 0x98, 0x38, 0x18, 0xa5, 0x98, 0x24, 0x18, 0x8d, 0xf2, 0x90, 0xdd, 0x19, 0x9c, 0x5a, - 0x54, 0x96, 0x99, 0x9c, 0x2a, 0x14, 0x82, 0xac, 0xdd, 0x39, 0x31, 0x27, 0x47, 0x48, 0x16, 0xbb, - 0x2b, 0xa0, 0x1e, 0x93, 0x92, 0xc3, 0x25, 0x0d, 0xf1, 0x9e, 0x12, 0x73, 0x07, 0x13, 0xa3, 0x14, - 0x88, 0x70, 0x72, 0x8c, 0xb2, 0x49, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, - 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07, 0x07, 0x5f, 0x52, 0x69, 0x1a, 0x84, 0x91, 0xac, - 0x9b, 0x9e, 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x5f, 0x92, 0x5a, 0x5c, 0x92, 0x92, 0x58, 0x92, 0x88, - 0x14, 0xd2, 0x3b, 0x18, 0x19, 0x93, 0xd8, 0xc0, 0xaa, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, - 0x0e, 0xf5, 0x6c, 0x87, 0x8c, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto deleted file mode 100755 index b314166..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/deprecated/deprecated.proto +++ /dev/null @@ -1,69 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -// package deprecated contains only deprecated messages and services. -package deprecated; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/deprecated"; - -option deprecated = true; // file-level deprecation - -// DeprecatedRequest is a request to DeprecatedCall. -message DeprecatedRequest { - option deprecated = true; -} - -message DeprecatedResponse { - // comment for DeprecatedResponse is omitted to guarantee deprecation - // message doesn't append unnecessary comments. - option deprecated = true; - // DeprecatedField contains a DeprecatedEnum. - DeprecatedEnum deprecated_field = 1 [deprecated=true]; -} - -// DeprecatedEnum contains deprecated values. -enum DeprecatedEnum { - option deprecated = true; - // DEPRECATED is the iota value of this enum. - DEPRECATED = 0 [deprecated=true]; -} - -// DeprecatedService is for making DeprecatedCalls -service DeprecatedService { - option deprecated = true; - - // DeprecatedCall takes a DeprecatedRequest and returns a DeprecatedResponse. - rpc DeprecatedCall(DeprecatedRequest) returns (DeprecatedResponse) { - option deprecated = true; - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go deleted file mode 100755 index a08e8ed..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.pb.go +++ /dev/null @@ -1,139 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: extension_base/extension_base.proto - -package extension_base // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type BaseMessage struct { - Height *int32 `protobuf:"varint,1,opt,name=height" json:"height,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BaseMessage) Reset() { *m = BaseMessage{} } -func (m *BaseMessage) String() string { return proto.CompactTextString(m) } -func (*BaseMessage) ProtoMessage() {} -func (*BaseMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_base_41d3c712c9fc37fc, []int{0} -} - -var extRange_BaseMessage = []proto.ExtensionRange{ - {Start: 4, End: 9}, - {Start: 16, End: 536870911}, -} - -func (*BaseMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_BaseMessage -} -func (m *BaseMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BaseMessage.Unmarshal(m, b) -} -func (m *BaseMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BaseMessage.Marshal(b, m, deterministic) -} -func (dst *BaseMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_BaseMessage.Merge(dst, src) -} -func (m *BaseMessage) XXX_Size() int { - return xxx_messageInfo_BaseMessage.Size(m) -} -func (m *BaseMessage) XXX_DiscardUnknown() { - xxx_messageInfo_BaseMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_BaseMessage proto.InternalMessageInfo - -func (m *BaseMessage) GetHeight() int32 { - if m != nil && m.Height != nil { - return *m.Height - } - return 0 -} - -// Another message that may be extended, using message_set_wire_format. -type OldStyleMessage struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OldStyleMessage) Reset() { *m = OldStyleMessage{} } -func (m *OldStyleMessage) String() string { return proto.CompactTextString(m) } -func (*OldStyleMessage) ProtoMessage() {} -func (*OldStyleMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_base_41d3c712c9fc37fc, []int{1} -} - -func (m *OldStyleMessage) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) -} -func (m *OldStyleMessage) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) -} - -var extRange_OldStyleMessage = []proto.ExtensionRange{ - {Start: 100, End: 2147483646}, -} - -func (*OldStyleMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OldStyleMessage -} -func (m *OldStyleMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OldStyleMessage.Unmarshal(m, b) -} -func (m *OldStyleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OldStyleMessage.Marshal(b, m, deterministic) -} -func (dst *OldStyleMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_OldStyleMessage.Merge(dst, src) -} -func (m *OldStyleMessage) XXX_Size() int { - return xxx_messageInfo_OldStyleMessage.Size(m) -} -func (m *OldStyleMessage) XXX_DiscardUnknown() { - xxx_messageInfo_OldStyleMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_OldStyleMessage proto.InternalMessageInfo - -func init() { - proto.RegisterType((*BaseMessage)(nil), "extension_base.BaseMessage") - proto.RegisterType((*OldStyleMessage)(nil), "extension_base.OldStyleMessage") -} - -func init() { - proto.RegisterFile("extension_base/extension_base.proto", fileDescriptor_extension_base_41d3c712c9fc37fc) -} - -var fileDescriptor_extension_base_41d3c712c9fc37fc = []byte{ - // 179 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4e, 0xad, 0x28, 0x49, - 0xcd, 0x2b, 0xce, 0xcc, 0xcf, 0x8b, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x47, 0xe5, 0xea, 0x15, 0x14, - 0xe5, 0x97, 0xe4, 0x0b, 0xf1, 0xa1, 0x8a, 0x2a, 0x99, 0x72, 0x71, 0x3b, 0x25, 0x16, 0xa7, 0xfa, - 0xa6, 0x16, 0x17, 0x27, 0xa6, 0xa7, 0x0a, 0x89, 0x71, 0xb1, 0x65, 0xa4, 0x66, 0xa6, 0x67, 0x94, - 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xb0, 0x06, 0x41, 0x79, 0x5a, 0x2c, 0x1c, 0x2c, 0x02, 0x5c, 0x5a, - 0x1c, 0x1c, 0x02, 0x02, 0x0d, 0x0d, 0x0d, 0x0d, 0x4c, 0x4a, 0xf2, 0x5c, 0xfc, 0xfe, 0x39, 0x29, - 0xc1, 0x25, 0x95, 0x39, 0x30, 0xad, 0x5a, 0x1c, 0x1c, 0x29, 0x02, 0xff, 0xff, 0xff, 0xff, 0xcf, - 0x6e, 0xc5, 0xc4, 0xc1, 0xe8, 0xe4, 0x14, 0xe5, 0x90, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, - 0x9c, 0x9f, 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0xae, 0x0f, 0x76, 0x42, 0x52, 0x69, 0x1a, - 0x84, 0x91, 0xac, 0x9b, 0x9e, 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x5f, 0x92, 0x5a, 0x5c, 0x92, 0x92, - 0x58, 0x92, 0x88, 0xe6, 0x62, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x7a, 0x7f, 0xb7, 0x2a, 0xd1, - 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto deleted file mode 100755 index 0ba74de..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base/extension_base.proto +++ /dev/null @@ -1,48 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -package extension_base; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base"; - -message BaseMessage { - optional int32 height = 1; - extensions 4 to 9; - extensions 16 to max; -} - -// Another message that may be extended, using message_set_wire_format. -message OldStyleMessage { - option message_set_wire_format = true; - extensions 100 to max; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go deleted file mode 100755 index b373216..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.pb.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: extension_extra/extension_extra.proto - -package extension_extra // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ExtraMessage struct { - Width *int32 `protobuf:"varint,1,opt,name=width" json:"width,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtraMessage) Reset() { *m = ExtraMessage{} } -func (m *ExtraMessage) String() string { return proto.CompactTextString(m) } -func (*ExtraMessage) ProtoMessage() {} -func (*ExtraMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_extra_83adf2410f49f816, []int{0} -} -func (m *ExtraMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtraMessage.Unmarshal(m, b) -} -func (m *ExtraMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtraMessage.Marshal(b, m, deterministic) -} -func (dst *ExtraMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtraMessage.Merge(dst, src) -} -func (m *ExtraMessage) XXX_Size() int { - return xxx_messageInfo_ExtraMessage.Size(m) -} -func (m *ExtraMessage) XXX_DiscardUnknown() { - xxx_messageInfo_ExtraMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtraMessage proto.InternalMessageInfo - -func (m *ExtraMessage) GetWidth() int32 { - if m != nil && m.Width != nil { - return *m.Width - } - return 0 -} - -func init() { - proto.RegisterType((*ExtraMessage)(nil), "extension_extra.ExtraMessage") -} - -func init() { - proto.RegisterFile("extension_extra/extension_extra.proto", fileDescriptor_extension_extra_83adf2410f49f816) -} - -var fileDescriptor_extension_extra_83adf2410f49f816 = []byte{ - // 133 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xad, 0x28, 0x49, - 0xcd, 0x2b, 0xce, 0xcc, 0xcf, 0x8b, 0x4f, 0xad, 0x28, 0x29, 0x4a, 0xd4, 0x47, 0xe3, 0xeb, 0x15, - 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0xf1, 0xa3, 0x09, 0x2b, 0xa9, 0x70, 0xf1, 0xb8, 0x82, 0x18, 0xbe, - 0xa9, 0xc5, 0xc5, 0x89, 0xe9, 0xa9, 0x42, 0x22, 0x5c, 0xac, 0xe5, 0x99, 0x29, 0x25, 0x19, 0x12, - 0x8c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x93, 0x73, 0x94, 0x63, 0x7a, 0x66, 0x49, 0x46, - 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0xba, 0x3e, 0xd8, 0xc4, - 0xa4, 0xd2, 0x34, 0x08, 0x23, 0x59, 0x37, 0x3d, 0x35, 0x4f, 0x37, 0x3d, 0x5f, 0xbf, 0x24, 0xb5, - 0xb8, 0x24, 0x25, 0xb1, 0x04, 0xc3, 0x05, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf1, 0xec, 0xe3, - 0xb7, 0xa3, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto deleted file mode 100755 index 1dd03e7..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra/extension_extra.proto +++ /dev/null @@ -1,40 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -package extension_extra; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra"; - -message ExtraMessage { - optional int32 width = 1; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go deleted file mode 100755 index 0524729..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go +++ /dev/null @@ -1,206 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Test that we can use protocol buffers that use extensions. - -package testdata - -import ( - "bytes" - "regexp" - "testing" - - "github.com/golang/protobuf/proto" - base "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base" - user "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user" -) - -func TestSingleFieldExtension(t *testing.T) { - bm := &base.BaseMessage{ - Height: proto.Int32(178), - } - - // Use extension within scope of another type. - vol := proto.Uint32(11) - err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol) - if err != nil { - t.Fatal("Failed setting extension:", err) - } - buf, err := proto.Marshal(bm) - if err != nil { - t.Fatal("Failed encoding message with extension:", err) - } - bm_new := new(base.BaseMessage) - if err := proto.Unmarshal(buf, bm_new); err != nil { - t.Fatal("Failed decoding message with extension:", err) - } - if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { - t.Fatal("Decoded message didn't contain extension.") - } - vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume) - if err != nil { - t.Fatal("Failed getting extension:", err) - } - if v := vol_out.(*uint32); *v != *vol { - t.Errorf("vol_out = %v, expected %v", *v, *vol) - } - proto.ClearExtension(bm_new, user.E_LoudMessage_Volume) - if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { - t.Fatal("Failed clearing extension.") - } -} - -func TestMessageExtension(t *testing.T) { - bm := &base.BaseMessage{ - Height: proto.Int32(179), - } - - // Use extension that is itself a message. - um := &user.UserMessage{ - Name: proto.String("Dave"), - Rank: proto.String("Major"), - } - err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um) - if err != nil { - t.Fatal("Failed setting extension:", err) - } - buf, err := proto.Marshal(bm) - if err != nil { - t.Fatal("Failed encoding message with extension:", err) - } - bm_new := new(base.BaseMessage) - if err := proto.Unmarshal(buf, bm_new); err != nil { - t.Fatal("Failed decoding message with extension:", err) - } - if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { - t.Fatal("Decoded message didn't contain extension.") - } - um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage) - if err != nil { - t.Fatal("Failed getting extension:", err) - } - if n := um_out.(*user.UserMessage).Name; *n != *um.Name { - t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name) - } - if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank { - t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank) - } - proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage) - if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { - t.Fatal("Failed clearing extension.") - } -} - -func TestTopLevelExtension(t *testing.T) { - bm := &base.BaseMessage{ - Height: proto.Int32(179), - } - - width := proto.Int32(17) - err := proto.SetExtension(bm, user.E_Width, width) - if err != nil { - t.Fatal("Failed setting extension:", err) - } - buf, err := proto.Marshal(bm) - if err != nil { - t.Fatal("Failed encoding message with extension:", err) - } - bm_new := new(base.BaseMessage) - if err := proto.Unmarshal(buf, bm_new); err != nil { - t.Fatal("Failed decoding message with extension:", err) - } - if !proto.HasExtension(bm_new, user.E_Width) { - t.Fatal("Decoded message didn't contain extension.") - } - width_out, err := proto.GetExtension(bm_new, user.E_Width) - if err != nil { - t.Fatal("Failed getting extension:", err) - } - if w := width_out.(*int32); *w != *width { - t.Errorf("width_out = %v, expected %v", *w, *width) - } - proto.ClearExtension(bm_new, user.E_Width) - if proto.HasExtension(bm_new, user.E_Width) { - t.Fatal("Failed clearing extension.") - } -} - -func TestMessageSetWireFormat(t *testing.T) { - osm := new(base.OldStyleMessage) - osp := &user.OldStyleParcel{ - Name: proto.String("Dave"), - Height: proto.Int32(178), - } - - err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp) - if err != nil { - t.Fatal("Failed setting extension:", err) - } - - buf, err := proto.Marshal(osm) - if err != nil { - t.Fatal("Failed encoding message:", err) - } - - // Data generated from Python implementation. - expected := []byte{ - 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12, - } - - if !bytes.Equal(expected, buf) { - t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf) - } - - // Check that it is restored correctly. - osm = new(base.OldStyleMessage) - if err := proto.Unmarshal(buf, osm); err != nil { - t.Fatal("Failed decoding message:", err) - } - osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension) - if err != nil { - t.Fatal("Failed getting extension:", err) - } - osp = osp_out.(*user.OldStyleParcel) - if *osp.Name != "Dave" || *osp.Height != 178 { - t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp) - } -} - -func main() { - // simpler than rigging up gotest - testing.Main(regexp.MatchString, []testing.InternalTest{ - {"TestSingleFieldExtension", TestSingleFieldExtension}, - {"TestMessageExtension", TestMessageExtension}, - {"TestTopLevelExtension", TestTopLevelExtension}, - }, - []testing.InternalBenchmark{}, - []testing.InternalExample{}) -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go deleted file mode 100755 index c718792..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.pb.go +++ /dev/null @@ -1,401 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: extension_user/extension_user.proto - -package extension_user // import "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import extension_base "github.com/golang/protobuf/protoc-gen-go/testdata/extension_base" -import extension_extra "github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type UserMessage struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Rank *string `protobuf:"bytes,2,opt,name=rank" json:"rank,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UserMessage) Reset() { *m = UserMessage{} } -func (m *UserMessage) String() string { return proto.CompactTextString(m) } -func (*UserMessage) ProtoMessage() {} -func (*UserMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{0} -} -func (m *UserMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UserMessage.Unmarshal(m, b) -} -func (m *UserMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UserMessage.Marshal(b, m, deterministic) -} -func (dst *UserMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_UserMessage.Merge(dst, src) -} -func (m *UserMessage) XXX_Size() int { - return xxx_messageInfo_UserMessage.Size(m) -} -func (m *UserMessage) XXX_DiscardUnknown() { - xxx_messageInfo_UserMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_UserMessage proto.InternalMessageInfo - -func (m *UserMessage) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *UserMessage) GetRank() string { - if m != nil && m.Rank != nil { - return *m.Rank - } - return "" -} - -// Extend inside the scope of another type -type LoudMessage struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoudMessage) Reset() { *m = LoudMessage{} } -func (m *LoudMessage) String() string { return proto.CompactTextString(m) } -func (*LoudMessage) ProtoMessage() {} -func (*LoudMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{1} -} - -var extRange_LoudMessage = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*LoudMessage) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_LoudMessage -} -func (m *LoudMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoudMessage.Unmarshal(m, b) -} -func (m *LoudMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoudMessage.Marshal(b, m, deterministic) -} -func (dst *LoudMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoudMessage.Merge(dst, src) -} -func (m *LoudMessage) XXX_Size() int { - return xxx_messageInfo_LoudMessage.Size(m) -} -func (m *LoudMessage) XXX_DiscardUnknown() { - xxx_messageInfo_LoudMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_LoudMessage proto.InternalMessageInfo - -var E_LoudMessage_Volume = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*uint32)(nil), - Field: 8, - Name: "extension_user.LoudMessage.volume", - Tag: "varint,8,opt,name=volume", - Filename: "extension_user/extension_user.proto", -} - -// Extend inside the scope of another type, using a message. -type LoginMessage struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoginMessage) Reset() { *m = LoginMessage{} } -func (m *LoginMessage) String() string { return proto.CompactTextString(m) } -func (*LoginMessage) ProtoMessage() {} -func (*LoginMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{2} -} -func (m *LoginMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoginMessage.Unmarshal(m, b) -} -func (m *LoginMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoginMessage.Marshal(b, m, deterministic) -} -func (dst *LoginMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoginMessage.Merge(dst, src) -} -func (m *LoginMessage) XXX_Size() int { - return xxx_messageInfo_LoginMessage.Size(m) -} -func (m *LoginMessage) XXX_DiscardUnknown() { - xxx_messageInfo_LoginMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_LoginMessage proto.InternalMessageInfo - -var E_LoginMessage_UserMessage = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*UserMessage)(nil), - Field: 16, - Name: "extension_user.LoginMessage.user_message", - Tag: "bytes,16,opt,name=user_message,json=userMessage", - Filename: "extension_user/extension_user.proto", -} - -type Detail struct { - Color *string `protobuf:"bytes,1,opt,name=color" json:"color,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Detail) Reset() { *m = Detail{} } -func (m *Detail) String() string { return proto.CompactTextString(m) } -func (*Detail) ProtoMessage() {} -func (*Detail) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{3} -} -func (m *Detail) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Detail.Unmarshal(m, b) -} -func (m *Detail) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Detail.Marshal(b, m, deterministic) -} -func (dst *Detail) XXX_Merge(src proto.Message) { - xxx_messageInfo_Detail.Merge(dst, src) -} -func (m *Detail) XXX_Size() int { - return xxx_messageInfo_Detail.Size(m) -} -func (m *Detail) XXX_DiscardUnknown() { - xxx_messageInfo_Detail.DiscardUnknown(m) -} - -var xxx_messageInfo_Detail proto.InternalMessageInfo - -func (m *Detail) GetColor() string { - if m != nil && m.Color != nil { - return *m.Color - } - return "" -} - -// An extension of an extension -type Announcement struct { - Words *string `protobuf:"bytes,1,opt,name=words" json:"words,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Announcement) Reset() { *m = Announcement{} } -func (m *Announcement) String() string { return proto.CompactTextString(m) } -func (*Announcement) ProtoMessage() {} -func (*Announcement) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{4} -} -func (m *Announcement) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Announcement.Unmarshal(m, b) -} -func (m *Announcement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Announcement.Marshal(b, m, deterministic) -} -func (dst *Announcement) XXX_Merge(src proto.Message) { - xxx_messageInfo_Announcement.Merge(dst, src) -} -func (m *Announcement) XXX_Size() int { - return xxx_messageInfo_Announcement.Size(m) -} -func (m *Announcement) XXX_DiscardUnknown() { - xxx_messageInfo_Announcement.DiscardUnknown(m) -} - -var xxx_messageInfo_Announcement proto.InternalMessageInfo - -func (m *Announcement) GetWords() string { - if m != nil && m.Words != nil { - return *m.Words - } - return "" -} - -var E_Announcement_LoudExt = &proto.ExtensionDesc{ - ExtendedType: (*LoudMessage)(nil), - ExtensionType: (*Announcement)(nil), - Field: 100, - Name: "extension_user.Announcement.loud_ext", - Tag: "bytes,100,opt,name=loud_ext,json=loudExt", - Filename: "extension_user/extension_user.proto", -} - -// Something that can be put in a message set. -type OldStyleParcel struct { - Name *string `protobuf:"bytes,1,req,name=name" json:"name,omitempty"` - Height *int32 `protobuf:"varint,2,opt,name=height" json:"height,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OldStyleParcel) Reset() { *m = OldStyleParcel{} } -func (m *OldStyleParcel) String() string { return proto.CompactTextString(m) } -func (*OldStyleParcel) ProtoMessage() {} -func (*OldStyleParcel) Descriptor() ([]byte, []int) { - return fileDescriptor_extension_user_af41b5e0bdfb7846, []int{5} -} -func (m *OldStyleParcel) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OldStyleParcel.Unmarshal(m, b) -} -func (m *OldStyleParcel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OldStyleParcel.Marshal(b, m, deterministic) -} -func (dst *OldStyleParcel) XXX_Merge(src proto.Message) { - xxx_messageInfo_OldStyleParcel.Merge(dst, src) -} -func (m *OldStyleParcel) XXX_Size() int { - return xxx_messageInfo_OldStyleParcel.Size(m) -} -func (m *OldStyleParcel) XXX_DiscardUnknown() { - xxx_messageInfo_OldStyleParcel.DiscardUnknown(m) -} - -var xxx_messageInfo_OldStyleParcel proto.InternalMessageInfo - -func (m *OldStyleParcel) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OldStyleParcel) GetHeight() int32 { - if m != nil && m.Height != nil { - return *m.Height - } - return 0 -} - -var E_OldStyleParcel_MessageSetExtension = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.OldStyleMessage)(nil), - ExtensionType: (*OldStyleParcel)(nil), - Field: 2001, - Name: "extension_user.OldStyleParcel", - Tag: "bytes,2001,opt,name=message_set_extension,json=messageSetExtension", - Filename: "extension_user/extension_user.proto", -} - -var E_UserMessage = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*UserMessage)(nil), - Field: 5, - Name: "extension_user.user_message", - Tag: "bytes,5,opt,name=user_message,json=userMessage", - Filename: "extension_user/extension_user.proto", -} - -var E_ExtraMessage = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*extension_extra.ExtraMessage)(nil), - Field: 9, - Name: "extension_user.extra_message", - Tag: "bytes,9,opt,name=extra_message,json=extraMessage", - Filename: "extension_user/extension_user.proto", -} - -var E_Width = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*int32)(nil), - Field: 6, - Name: "extension_user.width", - Tag: "varint,6,opt,name=width", - Filename: "extension_user/extension_user.proto", -} - -var E_Area = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: (*int64)(nil), - Field: 7, - Name: "extension_user.area", - Tag: "varint,7,opt,name=area", - Filename: "extension_user/extension_user.proto", -} - -var E_Detail = &proto.ExtensionDesc{ - ExtendedType: (*extension_base.BaseMessage)(nil), - ExtensionType: ([]*Detail)(nil), - Field: 17, - Name: "extension_user.detail", - Tag: "bytes,17,rep,name=detail", - Filename: "extension_user/extension_user.proto", -} - -func init() { - proto.RegisterType((*UserMessage)(nil), "extension_user.UserMessage") - proto.RegisterType((*LoudMessage)(nil), "extension_user.LoudMessage") - proto.RegisterType((*LoginMessage)(nil), "extension_user.LoginMessage") - proto.RegisterType((*Detail)(nil), "extension_user.Detail") - proto.RegisterType((*Announcement)(nil), "extension_user.Announcement") - proto.RegisterMessageSetType((*OldStyleParcel)(nil), 2001, "extension_user.OldStyleParcel") - proto.RegisterType((*OldStyleParcel)(nil), "extension_user.OldStyleParcel") - proto.RegisterExtension(E_LoudMessage_Volume) - proto.RegisterExtension(E_LoginMessage_UserMessage) - proto.RegisterExtension(E_Announcement_LoudExt) - proto.RegisterExtension(E_OldStyleParcel_MessageSetExtension) - proto.RegisterExtension(E_UserMessage) - proto.RegisterExtension(E_ExtraMessage) - proto.RegisterExtension(E_Width) - proto.RegisterExtension(E_Area) - proto.RegisterExtension(E_Detail) -} - -func init() { - proto.RegisterFile("extension_user/extension_user.proto", fileDescriptor_extension_user_af41b5e0bdfb7846) -} - -var fileDescriptor_extension_user_af41b5e0bdfb7846 = []byte{ - // 492 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x51, 0x6f, 0x94, 0x40, - 0x10, 0x0e, 0x6d, 0x8f, 0x5e, 0x87, 0x6b, 0xad, 0xa8, 0xcd, 0xa5, 0x6a, 0x25, 0x18, 0x13, 0x62, - 0xd2, 0x23, 0x62, 0x7c, 0xe1, 0x49, 0x2f, 0xde, 0x93, 0x67, 0x34, 0x54, 0x5f, 0xf4, 0x81, 0xec, - 0xc1, 0xc8, 0x91, 0xc2, 0xae, 0xd9, 0x5d, 0xec, 0xe9, 0xd3, 0xfd, 0x26, 0xff, 0x89, 0xff, 0xc8, - 0xb0, 0x2c, 0x2d, 0x87, 0xc9, 0xc5, 0xbe, 0x90, 0xfd, 0x86, 0x6f, 0xbe, 0x99, 0xfd, 0x66, 0x00, - 0x9e, 0xe2, 0x4a, 0x22, 0x15, 0x39, 0xa3, 0x71, 0x25, 0x90, 0xfb, 0x9b, 0x70, 0xf2, 0x9d, 0x33, - 0xc9, 0xec, 0xa3, 0xcd, 0xe8, 0x69, 0x27, 0x69, 0x41, 0x04, 0xfa, 0x9b, 0xb0, 0x49, 0x3a, 0x7d, - 0x76, 0x13, 0xc5, 0x95, 0xe4, 0xc4, 0xef, 0xe1, 0x86, 0xe6, 0xbe, 0x02, 0xeb, 0xb3, 0x40, 0xfe, - 0x1e, 0x85, 0x20, 0x19, 0xda, 0x36, 0xec, 0x51, 0x52, 0xe2, 0xd8, 0x70, 0x0c, 0xef, 0x20, 0x52, - 0xe7, 0x3a, 0xc6, 0x09, 0xbd, 0x1c, 0xef, 0x34, 0xb1, 0xfa, 0xec, 0xce, 0xc1, 0x9a, 0xb3, 0x2a, - 0xd5, 0x69, 0xcf, 0x87, 0xc3, 0xf4, 0x78, 0xbd, 0x5e, 0xaf, 0x77, 0x82, 0x97, 0x60, 0xfe, 0x60, - 0x45, 0x55, 0xa2, 0xfd, 0x70, 0xd2, 0xeb, 0x6b, 0x4a, 0x04, 0xea, 0x84, 0xf1, 0xd0, 0x31, 0xbc, - 0xc3, 0x48, 0x53, 0xdd, 0x4b, 0x18, 0xcd, 0x59, 0x96, 0x53, 0xfd, 0x36, 0xf8, 0x0a, 0xa3, 0xfa, - 0xa2, 0x71, 0xa9, 0xbb, 0xda, 0x2a, 0x75, 0xec, 0x18, 0x9e, 0x15, 0x74, 0x29, 0xca, 0xba, 0xce, - 0xad, 0x22, 0xab, 0xba, 0x01, 0xee, 0x19, 0x98, 0x6f, 0x51, 0x92, 0xbc, 0xb0, 0xef, 0xc3, 0x20, - 0x61, 0x05, 0xe3, 0xfa, 0xb6, 0x0d, 0x70, 0x7f, 0xc1, 0xe8, 0x0d, 0xa5, 0xac, 0xa2, 0x09, 0x96, - 0x48, 0x65, 0xcd, 0xba, 0x62, 0x3c, 0x15, 0x2d, 0x4b, 0x81, 0xe0, 0x13, 0x0c, 0x0b, 0x56, 0xa5, - 0xb5, 0x97, 0xf6, 0x3f, 0xb5, 0x3b, 0xd6, 0x8c, 0x53, 0xd5, 0xde, 0xa3, 0x3e, 0xa5, 0x5b, 0x22, - 0xda, 0xaf, 0xa5, 0x66, 0x2b, 0xe9, 0xfe, 0x36, 0xe0, 0xe8, 0x43, 0x91, 0x5e, 0xc8, 0x9f, 0x05, - 0x7e, 0x24, 0x3c, 0xc1, 0xa2, 0x33, 0x91, 0x9d, 0xeb, 0x89, 0x9c, 0x80, 0xb9, 0xc4, 0x3c, 0x5b, - 0x4a, 0x35, 0x93, 0x41, 0xa4, 0x51, 0x20, 0xe1, 0x81, 0xb6, 0x2c, 0x16, 0x28, 0xe3, 0xeb, 0x92, - 0xf6, 0x93, 0xbe, 0x81, 0x6d, 0x91, 0xb6, 0xcb, 0x3f, 0x77, 0x54, 0x9b, 0x67, 0xfd, 0x36, 0x37, - 0x9b, 0x89, 0xee, 0x69, 0xf9, 0x0b, 0x94, 0xb3, 0x96, 0x18, 0xde, 0x6a, 0x5a, 0x83, 0xdb, 0x4d, - 0x2b, 0x8c, 0xe1, 0x50, 0xad, 0xeb, 0xff, 0xa9, 0x1f, 0x28, 0xf5, 0xc7, 0x93, 0xfe, 0xae, 0xcf, - 0xea, 0x67, 0xab, 0x3f, 0xc2, 0x0e, 0x0a, 0x5f, 0xc0, 0xe0, 0x2a, 0x4f, 0xe5, 0x72, 0xbb, 0xb0, - 0xa9, 0x7c, 0x6e, 0x98, 0xa1, 0x0f, 0x7b, 0x84, 0x23, 0xd9, 0x9e, 0xb1, 0xef, 0x18, 0xde, 0x6e, - 0xa4, 0x88, 0xe1, 0x3b, 0x30, 0xd3, 0x66, 0xe5, 0xb6, 0xa6, 0xdc, 0x75, 0x76, 0x3d, 0x2b, 0x38, - 0xe9, 0x7b, 0xd3, 0x6c, 0x6b, 0xa4, 0x25, 0xa6, 0xd3, 0x2f, 0xaf, 0xb3, 0x5c, 0x2e, 0xab, 0xc5, - 0x24, 0x61, 0xa5, 0x9f, 0xb1, 0x82, 0xd0, 0xcc, 0x57, 0x1f, 0xf3, 0xa2, 0xfa, 0xd6, 0x1c, 0x92, - 0xf3, 0x0c, 0xe9, 0x79, 0xc6, 0x7c, 0x89, 0x42, 0xa6, 0x44, 0x92, 0xde, 0x7f, 0xe5, 0x6f, 0x00, - 0x00, 0x00, 0xff, 0xff, 0xdf, 0x18, 0x64, 0x15, 0x77, 0x04, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto deleted file mode 100755 index 033c186..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user/extension_user.proto +++ /dev/null @@ -1,102 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -import "extension_base/extension_base.proto"; -import "extension_extra/extension_extra.proto"; - -package extension_user; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/extension_user"; - -message UserMessage { - optional string name = 1; - optional string rank = 2; -} - -// Extend with a message -extend extension_base.BaseMessage { - optional UserMessage user_message = 5; -} - -// Extend with a foreign message -extend extension_base.BaseMessage { - optional extension_extra.ExtraMessage extra_message = 9; -} - -// Extend with some primitive types -extend extension_base.BaseMessage { - optional int32 width = 6; - optional int64 area = 7; -} - -// Extend inside the scope of another type -message LoudMessage { - extend extension_base.BaseMessage { - optional uint32 volume = 8; - } - extensions 100 to max; -} - -// Extend inside the scope of another type, using a message. -message LoginMessage { - extend extension_base.BaseMessage { - optional UserMessage user_message = 16; - } -} - -// Extend with a repeated field -extend extension_base.BaseMessage { - repeated Detail detail = 17; -} - -message Detail { - optional string color = 1; -} - -// An extension of an extension -message Announcement { - optional string words = 1; - extend LoudMessage { - optional Announcement loud_ext = 100; - } -} - -// Something that can be put in a message set. -message OldStyleParcel { - extend extension_base.OldStyleMessage { - optional OldStyleParcel message_set_extension = 2001; - } - - required string name = 1; - optional int32 height = 2; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go deleted file mode 100755 index 0bb4cbf..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.pb.go +++ /dev/null @@ -1,444 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/grpc.proto - -package testing // import "github.com/golang/protobuf/protoc-gen-go/testdata/grpc" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SimpleRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_65bf3902e49ee873, []int{0} -} -func (m *SimpleRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleRequest.Unmarshal(m, b) -} -func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic) -} -func (dst *SimpleRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleRequest.Merge(dst, src) -} -func (m *SimpleRequest) XXX_Size() int { - return xxx_messageInfo_SimpleRequest.Size(m) -} -func (m *SimpleRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo - -type SimpleResponse struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_65bf3902e49ee873, []int{1} -} -func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) -} -func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) -} -func (dst *SimpleResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleResponse.Merge(dst, src) -} -func (m *SimpleResponse) XXX_Size() int { - return xxx_messageInfo_SimpleResponse.Size(m) -} -func (m *SimpleResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo - -type StreamMsg struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamMsg) Reset() { *m = StreamMsg{} } -func (m *StreamMsg) String() string { return proto.CompactTextString(m) } -func (*StreamMsg) ProtoMessage() {} -func (*StreamMsg) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_65bf3902e49ee873, []int{2} -} -func (m *StreamMsg) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamMsg.Unmarshal(m, b) -} -func (m *StreamMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamMsg.Marshal(b, m, deterministic) -} -func (dst *StreamMsg) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamMsg.Merge(dst, src) -} -func (m *StreamMsg) XXX_Size() int { - return xxx_messageInfo_StreamMsg.Size(m) -} -func (m *StreamMsg) XXX_DiscardUnknown() { - xxx_messageInfo_StreamMsg.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamMsg proto.InternalMessageInfo - -type StreamMsg2 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamMsg2) Reset() { *m = StreamMsg2{} } -func (m *StreamMsg2) String() string { return proto.CompactTextString(m) } -func (*StreamMsg2) ProtoMessage() {} -func (*StreamMsg2) Descriptor() ([]byte, []int) { - return fileDescriptor_grpc_65bf3902e49ee873, []int{3} -} -func (m *StreamMsg2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamMsg2.Unmarshal(m, b) -} -func (m *StreamMsg2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamMsg2.Marshal(b, m, deterministic) -} -func (dst *StreamMsg2) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamMsg2.Merge(dst, src) -} -func (m *StreamMsg2) XXX_Size() int { - return xxx_messageInfo_StreamMsg2.Size(m) -} -func (m *StreamMsg2) XXX_DiscardUnknown() { - xxx_messageInfo_StreamMsg2.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamMsg2 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamMsg)(nil), "grpc.testing.StreamMsg") - proto.RegisterType((*StreamMsg2)(nil), "grpc.testing.StreamMsg2") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Test service - -type TestClient interface { - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // This RPC streams from the server only. - Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error) - // This RPC streams from the client. - Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error) - // This one streams in both directions. - Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error) -} - -type testClient struct { - cc *grpc.ClientConn -} - -func NewTestClient(cc *grpc.ClientConn) TestClient { - return &testClient{cc} -} - -func (c *testClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := grpc.Invoke(ctx, "/grpc.testing.Test/UnaryCall", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testClient) Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error) { - stream, err := grpc.NewClientStream(ctx, &_Test_serviceDesc.Streams[0], c.cc, "/grpc.testing.Test/Downstream", opts...) - if err != nil { - return nil, err - } - x := &testDownstreamClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Test_DownstreamClient interface { - Recv() (*StreamMsg, error) - grpc.ClientStream -} - -type testDownstreamClient struct { - grpc.ClientStream -} - -func (x *testDownstreamClient) Recv() (*StreamMsg, error) { - m := new(StreamMsg) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testClient) Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error) { - stream, err := grpc.NewClientStream(ctx, &_Test_serviceDesc.Streams[1], c.cc, "/grpc.testing.Test/Upstream", opts...) - if err != nil { - return nil, err - } - x := &testUpstreamClient{stream} - return x, nil -} - -type Test_UpstreamClient interface { - Send(*StreamMsg) error - CloseAndRecv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testUpstreamClient struct { - grpc.ClientStream -} - -func (x *testUpstreamClient) Send(m *StreamMsg) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testUpstreamClient) CloseAndRecv() (*SimpleResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testClient) Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error) { - stream, err := grpc.NewClientStream(ctx, &_Test_serviceDesc.Streams[2], c.cc, "/grpc.testing.Test/Bidi", opts...) - if err != nil { - return nil, err - } - x := &testBidiClient{stream} - return x, nil -} - -type Test_BidiClient interface { - Send(*StreamMsg) error - Recv() (*StreamMsg2, error) - grpc.ClientStream -} - -type testBidiClient struct { - grpc.ClientStream -} - -func (x *testBidiClient) Send(m *StreamMsg) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testBidiClient) Recv() (*StreamMsg2, error) { - m := new(StreamMsg2) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for Test service - -type TestServer interface { - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // This RPC streams from the server only. - Downstream(*SimpleRequest, Test_DownstreamServer) error - // This RPC streams from the client. - Upstream(Test_UpstreamServer) error - // This one streams in both directions. - Bidi(Test_BidiServer) error -} - -func RegisterTestServer(s *grpc.Server, srv TestServer) { - s.RegisterService(&_Test_serviceDesc, srv) -} - -func _Test_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.Test/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Test_Downstream_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(SimpleRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServer).Downstream(m, &testDownstreamServer{stream}) -} - -type Test_DownstreamServer interface { - Send(*StreamMsg) error - grpc.ServerStream -} - -type testDownstreamServer struct { - grpc.ServerStream -} - -func (x *testDownstreamServer) Send(m *StreamMsg) error { - return x.ServerStream.SendMsg(m) -} - -func _Test_Upstream_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServer).Upstream(&testUpstreamServer{stream}) -} - -type Test_UpstreamServer interface { - SendAndClose(*SimpleResponse) error - Recv() (*StreamMsg, error) - grpc.ServerStream -} - -type testUpstreamServer struct { - grpc.ServerStream -} - -func (x *testUpstreamServer) SendAndClose(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testUpstreamServer) Recv() (*StreamMsg, error) { - m := new(StreamMsg) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _Test_Bidi_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServer).Bidi(&testBidiServer{stream}) -} - -type Test_BidiServer interface { - Send(*StreamMsg2) error - Recv() (*StreamMsg, error) - grpc.ServerStream -} - -type testBidiServer struct { - grpc.ServerStream -} - -func (x *testBidiServer) Send(m *StreamMsg2) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testBidiServer) Recv() (*StreamMsg, error) { - m := new(StreamMsg) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _Test_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.Test", - HandlerType: (*TestServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: _Test_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Downstream", - Handler: _Test_Downstream_Handler, - ServerStreams: true, - }, - { - StreamName: "Upstream", - Handler: _Test_Upstream_Handler, - ClientStreams: true, - }, - { - StreamName: "Bidi", - Handler: _Test_Bidi_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc/grpc.proto", -} - -func init() { proto.RegisterFile("grpc/grpc.proto", fileDescriptor_grpc_65bf3902e49ee873) } - -var fileDescriptor_grpc_65bf3902e49ee873 = []byte{ - // 244 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4f, 0x2f, 0x2a, 0x48, - 0xd6, 0x07, 0x11, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x3c, 0x60, 0x76, 0x49, 0x6a, 0x71, - 0x49, 0x66, 0x5e, 0xba, 0x12, 0x3f, 0x17, 0x6f, 0x70, 0x66, 0x6e, 0x41, 0x4e, 0x6a, 0x50, 0x6a, - 0x61, 0x69, 0x6a, 0x71, 0x89, 0x92, 0x00, 0x17, 0x1f, 0x4c, 0xa0, 0xb8, 0x20, 0x3f, 0xaf, 0x38, - 0x55, 0x89, 0x9b, 0x8b, 0x33, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0xd7, 0xb7, 0x38, 0x5d, 0x89, 0x87, - 0x8b, 0x0b, 0xce, 0x31, 0x32, 0x9a, 0xc1, 0xc4, 0xc5, 0x12, 0x92, 0x5a, 0x5c, 0x22, 0xe4, 0xc6, - 0xc5, 0x19, 0x9a, 0x97, 0x58, 0x54, 0xe9, 0x9c, 0x98, 0x93, 0x23, 0x24, 0xad, 0x87, 0x6c, 0x85, - 0x1e, 0x8a, 0xf9, 0x52, 0x32, 0xd8, 0x25, 0x21, 0x76, 0x09, 0xb9, 0x70, 0x71, 0xb9, 0xe4, 0x97, - 0xe7, 0x15, 0x83, 0xad, 0xc0, 0x6f, 0x90, 0x38, 0x9a, 0x24, 0xcc, 0x55, 0x06, 0x8c, 0x42, 0xce, - 0x5c, 0x1c, 0xa1, 0x05, 0x50, 0x33, 0x70, 0x29, 0xc3, 0xef, 0x10, 0x0d, 0x46, 0x21, 0x5b, 0x2e, - 0x16, 0xa7, 0xcc, 0x94, 0x4c, 0xdc, 0x06, 0x48, 0xe0, 0x90, 0x30, 0xd2, 0x60, 0x34, 0x60, 0x74, - 0x72, 0x88, 0xb2, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, - 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07, 0xc7, 0x40, 0x52, 0x69, 0x1a, 0x84, 0x91, 0xac, 0x9b, 0x9e, - 0x9a, 0xa7, 0x9b, 0x9e, 0xaf, 0x0f, 0x32, 0x22, 0x25, 0xb1, 0x24, 0x11, 0x1c, 0x4d, 0xd6, 0x50, - 0x03, 0x93, 0xd8, 0xc0, 0x8a, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x90, 0xb9, 0x95, 0x42, - 0xc2, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto deleted file mode 100755 index 0e5c64a..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/grpc/grpc.proto +++ /dev/null @@ -1,61 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2015 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package grpc.testing; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/grpc;testing"; - -message SimpleRequest { -} - -message SimpleResponse { -} - -message StreamMsg { -} - -message StreamMsg2 { -} - -service Test { - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // This RPC streams from the server only. - rpc Downstream(SimpleRequest) returns (stream StreamMsg); - - // This RPC streams from the client. - rpc Upstream(stream StreamMsg) returns (SimpleResponse); - - // This one streams in both directions. - rpc Bidi(stream StreamMsg) returns (stream StreamMsg2); -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go deleted file mode 100755 index 5b780fd..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.pb.go +++ /dev/null @@ -1,110 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: import_public/a.proto - -package import_public // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import sub "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// M from public import import_public/sub/a.proto -type M = sub.M - -// E from public import import_public/sub/a.proto -type E = sub.E - -var E_name = sub.E_name -var E_value = sub.E_value - -const E_ZERO = E(sub.E_ZERO) - -// Ignoring public import of Local from import_public/b.proto - -type Public struct { - M *sub.M `protobuf:"bytes,1,opt,name=m" json:"m,omitempty"` - E sub.E `protobuf:"varint,2,opt,name=e,enum=goproto.test.import_public.sub.E" json:"e,omitempty"` - Local *Local `protobuf:"bytes,3,opt,name=local" json:"local,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Public) Reset() { *m = Public{} } -func (m *Public) String() string { return proto.CompactTextString(m) } -func (*Public) ProtoMessage() {} -func (*Public) Descriptor() ([]byte, []int) { - return fileDescriptor_a_c0314c022b7c17d8, []int{0} -} -func (m *Public) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Public.Unmarshal(m, b) -} -func (m *Public) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Public.Marshal(b, m, deterministic) -} -func (dst *Public) XXX_Merge(src proto.Message) { - xxx_messageInfo_Public.Merge(dst, src) -} -func (m *Public) XXX_Size() int { - return xxx_messageInfo_Public.Size(m) -} -func (m *Public) XXX_DiscardUnknown() { - xxx_messageInfo_Public.DiscardUnknown(m) -} - -var xxx_messageInfo_Public proto.InternalMessageInfo - -func (m *Public) GetM() *sub.M { - if m != nil { - return m.M - } - return nil -} - -func (m *Public) GetE() sub.E { - if m != nil { - return m.E - } - return sub.E_ZERO -} - -func (m *Public) GetLocal() *Local { - if m != nil { - return m.Local - } - return nil -} - -func init() { - proto.RegisterType((*Public)(nil), "goproto.test.import_public.Public") -} - -func init() { proto.RegisterFile("import_public/a.proto", fileDescriptor_a_c0314c022b7c17d8) } - -var fileDescriptor_a_c0314c022b7c17d8 = []byte{ - // 200 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xcd, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x4f, 0xd4, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x92, 0x4a, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, 0xf4, 0x50, 0xd4, 0x48, - 0x49, 0xa2, 0x6a, 0x29, 0x2e, 0x4d, 0x82, 0x69, 0x93, 0x42, 0x33, 0x2d, 0x09, 0x22, 0xac, 0xb4, - 0x98, 0x91, 0x8b, 0x2d, 0x00, 0x2c, 0x24, 0xa4, 0xcf, 0xc5, 0x98, 0x2b, 0xc1, 0xa8, 0xc0, 0xa8, - 0xc1, 0x6d, 0xa4, 0xa8, 0x87, 0xdb, 0x12, 0xbd, 0xe2, 0xd2, 0x24, 0x3d, 0xdf, 0x20, 0xc6, 0x5c, - 0x90, 0x86, 0x54, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x3e, 0xc2, 0x1a, 0x5c, 0x83, 0x18, 0x53, 0x85, - 0xcc, 0xb9, 0x58, 0x73, 0xf2, 0x93, 0x13, 0x73, 0x24, 0x98, 0x09, 0xdb, 0xe2, 0x03, 0x52, 0x18, - 0x04, 0x51, 0xef, 0xe4, 0x18, 0x65, 0x9f, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, - 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0xae, 0x0f, 0xd6, 0x9a, 0x54, 0x9a, 0x06, 0x61, 0x24, - 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7, 0xeb, 0x83, 0xcc, 0x4a, 0x49, 0x2c, 0x49, 0xd4, 0x47, - 0x31, 0x2f, 0x80, 0x21, 0x80, 0x31, 0x89, 0x0d, 0xac, 0xd2, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, - 0x70, 0xc5, 0xc3, 0x79, 0x5a, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto deleted file mode 100755 index 957ad89..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/a.proto +++ /dev/null @@ -1,45 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package goproto.test.import_public; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public"; - -import public "import_public/sub/a.proto"; // Different Go package. -import public "import_public/b.proto"; // Same Go package. - -message Public { - goproto.test.import_public.sub.M m = 1; - goproto.test.import_public.sub.E e = 2; - Local local = 3; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go deleted file mode 100755 index 427aa4f..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.pb.go +++ /dev/null @@ -1,87 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: import_public/b.proto - -package import_public // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import sub "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Local struct { - M *sub.M `protobuf:"bytes,1,opt,name=m" json:"m,omitempty"` - E sub.E `protobuf:"varint,2,opt,name=e,enum=goproto.test.import_public.sub.E" json:"e,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Local) Reset() { *m = Local{} } -func (m *Local) String() string { return proto.CompactTextString(m) } -func (*Local) ProtoMessage() {} -func (*Local) Descriptor() ([]byte, []int) { - return fileDescriptor_b_7f20a805fad67bd0, []int{0} -} -func (m *Local) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Local.Unmarshal(m, b) -} -func (m *Local) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Local.Marshal(b, m, deterministic) -} -func (dst *Local) XXX_Merge(src proto.Message) { - xxx_messageInfo_Local.Merge(dst, src) -} -func (m *Local) XXX_Size() int { - return xxx_messageInfo_Local.Size(m) -} -func (m *Local) XXX_DiscardUnknown() { - xxx_messageInfo_Local.DiscardUnknown(m) -} - -var xxx_messageInfo_Local proto.InternalMessageInfo - -func (m *Local) GetM() *sub.M { - if m != nil { - return m.M - } - return nil -} - -func (m *Local) GetE() sub.E { - if m != nil { - return m.E - } - return sub.E_ZERO -} - -func init() { - proto.RegisterType((*Local)(nil), "goproto.test.import_public.Local") -} - -func init() { proto.RegisterFile("import_public/b.proto", fileDescriptor_b_7f20a805fad67bd0) } - -var fileDescriptor_b_7f20a805fad67bd0 = []byte{ - // 174 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xcd, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x4f, 0xd2, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x92, 0x4a, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, 0xf4, 0x50, 0xd4, 0x48, - 0x49, 0xa2, 0x6a, 0x29, 0x2e, 0x4d, 0xd2, 0x4f, 0x84, 0x68, 0x53, 0xca, 0xe4, 0x62, 0xf5, 0xc9, - 0x4f, 0x4e, 0xcc, 0x11, 0xd2, 0xe7, 0x62, 0xcc, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0x52, - 0xd4, 0xc3, 0x6d, 0x96, 0x5e, 0x71, 0x69, 0x92, 0x9e, 0x6f, 0x10, 0x63, 0x2e, 0x48, 0x43, 0xaa, - 0x04, 0x93, 0x02, 0xa3, 0x06, 0x1f, 0x61, 0x0d, 0xae, 0x41, 0x8c, 0xa9, 0x4e, 0x8e, 0x51, 0xf6, - 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, 0x79, - 0xe9, 0xfa, 0x60, 0x6d, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a, - 0xbe, 0x3e, 0xc8, 0x9c, 0x94, 0xc4, 0x92, 0x44, 0x7d, 0x14, 0xb3, 0x92, 0xd8, 0xc0, 0xaa, 0x8c, - 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x2b, 0x5f, 0x8e, 0x04, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto deleted file mode 100755 index 1dbca3e..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/b.proto +++ /dev/null @@ -1,43 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package goproto.test.import_public; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public"; - -import "import_public/sub/a.proto"; - -message Local { - goproto.test.import_public.sub.M m = 1; - goproto.test.import_public.sub.E e = 2; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go deleted file mode 100755 index 4f8f6d2..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.pb.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: import_public/sub/a.proto - -package sub // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type E int32 - -const ( - E_ZERO E = 0 -) - -var E_name = map[int32]string{ - 0: "ZERO", -} -var E_value = map[string]int32{ - "ZERO": 0, -} - -func (x E) String() string { - return proto.EnumName(E_name, int32(x)) -} -func (E) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a_91ca0264a534463a, []int{0} -} - -type M struct { - // Field using a type in the same Go package, but a different source file. - M2 *M2 `protobuf:"bytes,1,opt,name=m2" json:"m2,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M) Reset() { *m = M{} } -func (m *M) String() string { return proto.CompactTextString(m) } -func (*M) ProtoMessage() {} -func (*M) Descriptor() ([]byte, []int) { - return fileDescriptor_a_91ca0264a534463a, []int{0} -} -func (m *M) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M.Unmarshal(m, b) -} -func (m *M) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M.Marshal(b, m, deterministic) -} -func (dst *M) XXX_Merge(src proto.Message) { - xxx_messageInfo_M.Merge(dst, src) -} -func (m *M) XXX_Size() int { - return xxx_messageInfo_M.Size(m) -} -func (m *M) XXX_DiscardUnknown() { - xxx_messageInfo_M.DiscardUnknown(m) -} - -var xxx_messageInfo_M proto.InternalMessageInfo - -func (m *M) GetM2() *M2 { - if m != nil { - return m.M2 - } - return nil -} - -func init() { - proto.RegisterType((*M)(nil), "goproto.test.import_public.sub.M") - proto.RegisterEnum("goproto.test.import_public.sub.E", E_name, E_value) -} - -func init() { proto.RegisterFile("import_public/sub/a.proto", fileDescriptor_a_91ca0264a534463a) } - -var fileDescriptor_a_91ca0264a534463a = []byte{ - // 172 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x2f, 0x2e, 0x4d, 0xd2, 0x4f, 0xd4, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4b, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, - 0xf4, 0x50, 0xd4, 0xe9, 0x15, 0x97, 0x26, 0x49, 0x61, 0xd1, 0x9a, 0x04, 0xd1, 0xaa, 0x64, 0xce, - 0xc5, 0xe8, 0x2b, 0x64, 0xc4, 0xc5, 0x94, 0x6b, 0x24, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0xa4, - 0xa4, 0x87, 0xdf, 0x30, 0x3d, 0x5f, 0xa3, 0x20, 0xa6, 0x5c, 0x23, 0x2d, 0x5e, 0x2e, 0x46, 0x57, - 0x21, 0x0e, 0x2e, 0x96, 0x28, 0xd7, 0x20, 0x7f, 0x01, 0x06, 0x27, 0xd7, 0x28, 0xe7, 0xf4, 0xcc, - 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0xf4, 0xfc, 0x9c, 0xc4, 0xbc, 0x74, 0x7d, - 0xb0, 0x39, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a, 0xbe, 0x3e, - 0xc8, 0xe0, 0x94, 0xc4, 0x92, 0x44, 0x7d, 0x0c, 0x67, 0x25, 0xb1, 0x81, 0x55, 0x1a, 0x03, 0x02, - 0x00, 0x00, 0xff, 0xff, 0x81, 0xcc, 0x07, 0x7d, 0xed, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto deleted file mode 100755 index 4494c81..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/a.proto +++ /dev/null @@ -1,47 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package goproto.test.import_public.sub; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"; - -import "import_public/sub/b.proto"; - -message M { - // Field using a type in the same Go package, but a different source file. - M2 m2 = 1; -} - -enum E { - ZERO = 0; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go deleted file mode 100755 index d57a3bb..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: import_public/sub/b.proto - -package sub // import "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M2 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M2) Reset() { *m = M2{} } -func (m *M2) String() string { return proto.CompactTextString(m) } -func (*M2) ProtoMessage() {} -func (*M2) Descriptor() ([]byte, []int) { - return fileDescriptor_b_eba25180453d86b4, []int{0} -} -func (m *M2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M2.Unmarshal(m, b) -} -func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M2.Marshal(b, m, deterministic) -} -func (dst *M2) XXX_Merge(src proto.Message) { - xxx_messageInfo_M2.Merge(dst, src) -} -func (m *M2) XXX_Size() int { - return xxx_messageInfo_M2.Size(m) -} -func (m *M2) XXX_DiscardUnknown() { - xxx_messageInfo_M2.DiscardUnknown(m) -} - -var xxx_messageInfo_M2 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M2)(nil), "goproto.test.import_public.sub.M2") -} - -func init() { proto.RegisterFile("import_public/sub/b.proto", fileDescriptor_b_eba25180453d86b4) } - -var fileDescriptor_b_eba25180453d86b4 = []byte{ - // 127 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x89, 0x2f, 0x28, 0x4d, 0xca, 0xc9, 0x4c, 0xd6, 0x2f, 0x2e, 0x4d, 0xd2, 0x4f, 0xd2, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x4b, 0xcf, 0x07, 0x33, 0xf4, 0x4a, 0x52, 0x8b, 0x4b, - 0xf4, 0x50, 0xd4, 0xe9, 0x15, 0x97, 0x26, 0x29, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x39, 0xb9, 0x46, - 0x39, 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, - 0xe6, 0xa5, 0xeb, 0x83, 0xf5, 0x25, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba, - 0xe9, 0xf9, 0xfa, 0x20, 0x83, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0x31, 0x2c, 0x4d, 0x62, 0x03, 0xab, - 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x64, 0x42, 0xe4, 0xa8, 0x90, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto deleted file mode 100755 index c7299e0..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub/b.proto +++ /dev/null @@ -1,39 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package goproto.test.import_public.sub; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub"; - -message M2 { -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go deleted file mode 100755 index 7ef776b..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/import_public_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build go1.9 - -package testdata - -import ( - "testing" - - mainpb "github.com/golang/protobuf/protoc-gen-go/testdata/import_public" - subpb "github.com/golang/protobuf/protoc-gen-go/testdata/import_public/sub" -) - -func TestImportPublicLink(t *testing.T) { - // mainpb.[ME] should be interchangable with subpb.[ME]. - var _ mainpb.M = subpb.M{} - var _ mainpb.E = subpb.E(0) - _ = &mainpb.Public{ - M: &mainpb.M{}, - E: mainpb.E_ZERO, - Local: &mainpb.Local{ - M: &mainpb.M{}, - E: mainpb.E_ZERO, - }, - } - _ = &mainpb.Public{ - M: &subpb.M{}, - E: subpb.E_ZERO, - Local: &mainpb.Local{ - M: &subpb.M{}, - E: subpb.E_ZERO, - }, - } - _ = &mainpb.M{ - M2: &subpb.M2{}, - } -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go deleted file mode 100755 index ca312d6..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.pb.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/fmt/m.proto - -package fmt // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M) Reset() { *m = M{} } -func (m *M) String() string { return proto.CompactTextString(m) } -func (*M) ProtoMessage() {} -func (*M) Descriptor() ([]byte, []int) { - return fileDescriptor_m_867dd34c461422b8, []int{0} -} -func (m *M) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M.Unmarshal(m, b) -} -func (m *M) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M.Marshal(b, m, deterministic) -} -func (dst *M) XXX_Merge(src proto.Message) { - xxx_messageInfo_M.Merge(dst, src) -} -func (m *M) XXX_Size() int { - return xxx_messageInfo_M.Size(m) -} -func (m *M) XXX_DiscardUnknown() { - xxx_messageInfo_M.DiscardUnknown(m) -} - -var xxx_messageInfo_M proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M)(nil), "fmt.M") -} - -func init() { proto.RegisterFile("imports/fmt/m.proto", fileDescriptor_m_867dd34c461422b8) } - -var fileDescriptor_m_867dd34c461422b8 = []byte{ - // 109 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xce, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x4f, 0xcb, 0x2d, 0xd1, 0xcf, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, - 0x62, 0x4e, 0xcb, 0x2d, 0x51, 0x62, 0xe6, 0x62, 0xf4, 0x75, 0xb2, 0x8f, 0xb2, 0x4d, 0xcf, 0x2c, - 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0xd7, 0x07, - 0x2b, 0x4a, 0x2a, 0x4d, 0x83, 0x30, 0x92, 0x75, 0xd3, 0x53, 0xf3, 0x74, 0xd3, 0xf3, 0xf5, 0x4b, - 0x52, 0x8b, 0x4b, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0x91, 0x8c, 0x4c, 0x62, 0x03, 0xab, 0x31, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0xc4, 0xc9, 0xee, 0xbe, 0x68, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto deleted file mode 100755 index 142d8cf..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt/m.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package fmt; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt"; -message M {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go deleted file mode 100755 index 82ec35e..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.pb.go +++ /dev/null @@ -1,130 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_a_1/m1.proto - -package test_a_1 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type E1 int32 - -const ( - E1_E1_ZERO E1 = 0 -) - -var E1_name = map[int32]string{ - 0: "E1_ZERO", -} -var E1_value = map[string]int32{ - "E1_ZERO": 0, -} - -func (x E1) String() string { - return proto.EnumName(E1_name, int32(x)) -} -func (E1) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_m1_56a2598431d21e61, []int{0} -} - -type M1 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M1) Reset() { *m = M1{} } -func (m *M1) String() string { return proto.CompactTextString(m) } -func (*M1) ProtoMessage() {} -func (*M1) Descriptor() ([]byte, []int) { - return fileDescriptor_m1_56a2598431d21e61, []int{0} -} -func (m *M1) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M1.Unmarshal(m, b) -} -func (m *M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M1.Marshal(b, m, deterministic) -} -func (dst *M1) XXX_Merge(src proto.Message) { - xxx_messageInfo_M1.Merge(dst, src) -} -func (m *M1) XXX_Size() int { - return xxx_messageInfo_M1.Size(m) -} -func (m *M1) XXX_DiscardUnknown() { - xxx_messageInfo_M1.DiscardUnknown(m) -} - -var xxx_messageInfo_M1 proto.InternalMessageInfo - -type M1_1 struct { - M1 *M1 `protobuf:"bytes,1,opt,name=m1" json:"m1,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M1_1) Reset() { *m = M1_1{} } -func (m *M1_1) String() string { return proto.CompactTextString(m) } -func (*M1_1) ProtoMessage() {} -func (*M1_1) Descriptor() ([]byte, []int) { - return fileDescriptor_m1_56a2598431d21e61, []int{1} -} -func (m *M1_1) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M1_1.Unmarshal(m, b) -} -func (m *M1_1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M1_1.Marshal(b, m, deterministic) -} -func (dst *M1_1) XXX_Merge(src proto.Message) { - xxx_messageInfo_M1_1.Merge(dst, src) -} -func (m *M1_1) XXX_Size() int { - return xxx_messageInfo_M1_1.Size(m) -} -func (m *M1_1) XXX_DiscardUnknown() { - xxx_messageInfo_M1_1.DiscardUnknown(m) -} - -var xxx_messageInfo_M1_1 proto.InternalMessageInfo - -func (m *M1_1) GetM1() *M1 { - if m != nil { - return m.M1 - } - return nil -} - -func init() { - proto.RegisterType((*M1)(nil), "test.a.M1") - proto.RegisterType((*M1_1)(nil), "test.a.M1_1") - proto.RegisterEnum("test.a.E1", E1_name, E1_value) -} - -func init() { proto.RegisterFile("imports/test_a_1/m1.proto", fileDescriptor_m1_56a2598431d21e61) } - -var fileDescriptor_m1_56a2598431d21e61 = []byte{ - // 165 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd4, 0xcf, 0x35, 0xd4, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9, - 0x1a, 0x2a, 0x29, 0x71, 0xb1, 0xf8, 0x1a, 0xc6, 0x1b, 0x0a, 0x49, 0x71, 0x31, 0xe5, 0x1a, 0x4a, - 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0x71, 0xe9, 0x41, 0x94, 0xe8, 0xf9, 0x1a, 0x06, 0x31, 0xe5, - 0x1a, 0x6a, 0x09, 0x72, 0x31, 0xb9, 0x1a, 0x0a, 0x71, 0x73, 0xb1, 0xbb, 0x1a, 0xc6, 0x47, 0xb9, - 0x06, 0xf9, 0x0b, 0x30, 0x38, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, - 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0xcd, 0x4f, 0x2a, 0x4d, 0x83, - 0x30, 0x92, 0x75, 0xd3, 0x53, 0xf3, 0x74, 0xd3, 0xf3, 0xc1, 0x4e, 0x48, 0x49, 0x2c, 0x49, 0xd4, - 0x47, 0x77, 0x53, 0x12, 0x1b, 0x58, 0xa1, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xcc, 0xae, 0xc9, - 0xcd, 0xae, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto deleted file mode 100755 index da54c1e..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m1.proto +++ /dev/null @@ -1,44 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.a; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"; - -message M1 {} - -message M1_1 { - M1 m1 = 1; -} - -enum E1 { - E1_ZERO = 0; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go deleted file mode 100755 index 1b629bf..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_a_1/m2.proto - -package test_a_1 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M2 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M2) Reset() { *m = M2{} } -func (m *M2) String() string { return proto.CompactTextString(m) } -func (*M2) ProtoMessage() {} -func (*M2) Descriptor() ([]byte, []int) { - return fileDescriptor_m2_ccd6356c045a9ac3, []int{0} -} -func (m *M2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M2.Unmarshal(m, b) -} -func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M2.Marshal(b, m, deterministic) -} -func (dst *M2) XXX_Merge(src proto.Message) { - xxx_messageInfo_M2.Merge(dst, src) -} -func (m *M2) XXX_Size() int { - return xxx_messageInfo_M2.Size(m) -} -func (m *M2) XXX_DiscardUnknown() { - xxx_messageInfo_M2.DiscardUnknown(m) -} - -var xxx_messageInfo_M2 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M2)(nil), "test.a.M2") -} - -func init() { proto.RegisterFile("imports/test_a_1/m2.proto", fileDescriptor_m2_ccd6356c045a9ac3) } - -var fileDescriptor_m2_ccd6356c045a9ac3 = []byte{ - // 114 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd4, 0xcf, 0x35, 0xd2, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9, - 0x1a, 0x39, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, - 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f, - 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xe3, 0xe0, 0x7e, 0xc0, 0x77, 0x00, - 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto deleted file mode 100755 index 49499dc..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1/m2.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.a; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1"; -message M2 {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go deleted file mode 100755 index e3895d2..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_a_2/m3.proto - -package test_a_2 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M3 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M3) Reset() { *m = M3{} } -func (m *M3) String() string { return proto.CompactTextString(m) } -func (*M3) ProtoMessage() {} -func (*M3) Descriptor() ([]byte, []int) { - return fileDescriptor_m3_de310e87d08d4216, []int{0} -} -func (m *M3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M3.Unmarshal(m, b) -} -func (m *M3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M3.Marshal(b, m, deterministic) -} -func (dst *M3) XXX_Merge(src proto.Message) { - xxx_messageInfo_M3.Merge(dst, src) -} -func (m *M3) XXX_Size() int { - return xxx_messageInfo_M3.Size(m) -} -func (m *M3) XXX_DiscardUnknown() { - xxx_messageInfo_M3.DiscardUnknown(m) -} - -var xxx_messageInfo_M3 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M3)(nil), "test.a.M3") -} - -func init() { proto.RegisterFile("imports/test_a_2/m3.proto", fileDescriptor_m3_de310e87d08d4216) } - -var fileDescriptor_m3_de310e87d08d4216 = []byte{ - // 114 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd2, 0xcf, 0x35, 0xd6, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9, - 0x1a, 0x3b, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, - 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f, - 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x23, 0x86, 0x27, 0x47, 0x77, 0x00, - 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto deleted file mode 100755 index 5e811ef..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m3.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.a; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2"; -message M3 {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go deleted file mode 100755 index 65a3bad..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_a_2/m4.proto - -package test_a_2 // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M4 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M4) Reset() { *m = M4{} } -func (m *M4) String() string { return proto.CompactTextString(m) } -func (*M4) ProtoMessage() {} -func (*M4) Descriptor() ([]byte, []int) { - return fileDescriptor_m4_da12b386229f3791, []int{0} -} -func (m *M4) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M4.Unmarshal(m, b) -} -func (m *M4) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M4.Marshal(b, m, deterministic) -} -func (dst *M4) XXX_Merge(src proto.Message) { - xxx_messageInfo_M4.Merge(dst, src) -} -func (m *M4) XXX_Size() int { - return xxx_messageInfo_M4.Size(m) -} -func (m *M4) XXX_DiscardUnknown() { - xxx_messageInfo_M4.DiscardUnknown(m) -} - -var xxx_messageInfo_M4 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M4)(nil), "test.a.M4") -} - -func init() { proto.RegisterFile("imports/test_a_2/m4.proto", fileDescriptor_m4_da12b386229f3791) } - -var fileDescriptor_m4_da12b386229f3791 = []byte{ - // 114 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8c, 0x37, 0xd2, 0xcf, 0x35, 0xd1, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x09, 0xe9, 0x25, 0x2a, 0xb1, 0x70, 0x31, 0xf9, - 0x9a, 0x38, 0xb9, 0x44, 0x39, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x15, 0x26, 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, - 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0xb3, 0x52, 0x12, 0x4b, 0x12, 0xf5, 0xd1, 0x0d, 0x4f, - 0x62, 0x03, 0x2b, 0x34, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x58, 0xcb, 0x10, 0xc8, 0x77, 0x00, - 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto deleted file mode 100755 index 8f8fe3e..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2/m4.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.a; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2"; -message M4 {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go deleted file mode 100755 index 831f414..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_b_1/m1.proto - -package beta // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M1 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M1) Reset() { *m = M1{} } -func (m *M1) String() string { return proto.CompactTextString(m) } -func (*M1) ProtoMessage() {} -func (*M1) Descriptor() ([]byte, []int) { - return fileDescriptor_m1_aff127b054aec649, []int{0} -} -func (m *M1) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M1.Unmarshal(m, b) -} -func (m *M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M1.Marshal(b, m, deterministic) -} -func (dst *M1) XXX_Merge(src proto.Message) { - xxx_messageInfo_M1.Merge(dst, src) -} -func (m *M1) XXX_Size() int { - return xxx_messageInfo_M1.Size(m) -} -func (m *M1) XXX_DiscardUnknown() { - xxx_messageInfo_M1.DiscardUnknown(m) -} - -var xxx_messageInfo_M1 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M1)(nil), "test.b.part1.M1") -} - -func init() { proto.RegisterFile("imports/test_b_1/m1.proto", fileDescriptor_m1_aff127b054aec649) } - -var fileDescriptor_m1_aff127b054aec649 = []byte{ - // 125 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8a, 0x37, 0xd4, 0xcf, 0x35, 0xd4, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x01, 0x09, 0xe9, 0x25, 0xe9, 0x15, 0x24, 0x16, 0x95, - 0x18, 0x2a, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x3a, 0x79, 0x46, 0xb9, 0xa7, 0x67, 0x96, 0x64, 0x94, - 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x95, 0x27, - 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0x13, 0x53, 0x12, - 0x4b, 0x12, 0xf5, 0xd1, 0xad, 0xb0, 0x4e, 0x4a, 0x2d, 0x49, 0x4c, 0x62, 0x03, 0xab, 0x36, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x4a, 0xf1, 0x3b, 0x7f, 0x82, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto deleted file mode 100755 index 2c35ec4..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m1.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.b.part1; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1;beta"; -message M1 {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go deleted file mode 100755 index bc74105..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.pb.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_b_1/m2.proto - -package beta // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type M2 struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *M2) Reset() { *m = M2{} } -func (m *M2) String() string { return proto.CompactTextString(m) } -func (*M2) ProtoMessage() {} -func (*M2) Descriptor() ([]byte, []int) { - return fileDescriptor_m2_0c59cab35ba1b0d8, []int{0} -} -func (m *M2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_M2.Unmarshal(m, b) -} -func (m *M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_M2.Marshal(b, m, deterministic) -} -func (dst *M2) XXX_Merge(src proto.Message) { - xxx_messageInfo_M2.Merge(dst, src) -} -func (m *M2) XXX_Size() int { - return xxx_messageInfo_M2.Size(m) -} -func (m *M2) XXX_DiscardUnknown() { - xxx_messageInfo_M2.DiscardUnknown(m) -} - -var xxx_messageInfo_M2 proto.InternalMessageInfo - -func init() { - proto.RegisterType((*M2)(nil), "test.b.part2.M2") -} - -func init() { proto.RegisterFile("imports/test_b_1/m2.proto", fileDescriptor_m2_0c59cab35ba1b0d8) } - -var fileDescriptor_m2_0c59cab35ba1b0d8 = []byte{ - // 125 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcc, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x4f, 0x8a, 0x37, 0xd4, 0xcf, 0x35, 0xd2, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x01, 0x09, 0xe9, 0x25, 0xe9, 0x15, 0x24, 0x16, 0x95, - 0x18, 0x29, 0xb1, 0x70, 0x31, 0xf9, 0x1a, 0x39, 0x79, 0x46, 0xb9, 0xa7, 0x67, 0x96, 0x64, 0x94, - 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, 0xeb, 0x83, 0x95, 0x27, - 0x95, 0xa6, 0x41, 0x18, 0xc9, 0xba, 0xe9, 0xa9, 0x79, 0xba, 0xe9, 0xf9, 0x60, 0x13, 0x53, 0x12, - 0x4b, 0x12, 0xf5, 0xd1, 0xad, 0xb0, 0x4e, 0x4a, 0x2d, 0x49, 0x4c, 0x62, 0x03, 0xab, 0x36, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x44, 0x29, 0xbe, 0x6d, 0x82, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto deleted file mode 100755 index 13723be..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1/m2.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; -package test.b.part2; -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1;beta"; -message M2 {} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go deleted file mode 100755 index 72daffd..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.pb.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_import_a1m1.proto - -package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type A1M1 struct { - F *test_a_1.M1 `protobuf:"bytes,1,opt,name=f" json:"f,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *A1M1) Reset() { *m = A1M1{} } -func (m *A1M1) String() string { return proto.CompactTextString(m) } -func (*A1M1) ProtoMessage() {} -func (*A1M1) Descriptor() ([]byte, []int) { - return fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e, []int{0} -} -func (m *A1M1) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_A1M1.Unmarshal(m, b) -} -func (m *A1M1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_A1M1.Marshal(b, m, deterministic) -} -func (dst *A1M1) XXX_Merge(src proto.Message) { - xxx_messageInfo_A1M1.Merge(dst, src) -} -func (m *A1M1) XXX_Size() int { - return xxx_messageInfo_A1M1.Size(m) -} -func (m *A1M1) XXX_DiscardUnknown() { - xxx_messageInfo_A1M1.DiscardUnknown(m) -} - -var xxx_messageInfo_A1M1 proto.InternalMessageInfo - -func (m *A1M1) GetF() *test_a_1.M1 { - if m != nil { - return m.F - } - return nil -} - -func init() { - proto.RegisterType((*A1M1)(nil), "test.A1M1") -} - -func init() { - proto.RegisterFile("imports/test_import_a1m1.proto", fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e) -} - -var fileDescriptor_test_import_a1m1_d7f2b5c638a69f6e = []byte{ - // 149 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x87, 0x70, 0xe2, 0x13, 0x0d, 0x73, 0x0d, - 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xe2, 0x52, 0x92, 0x28, 0xaa, 0x12, 0xe3, - 0x0d, 0xf5, 0x61, 0x0a, 0x94, 0x14, 0xb8, 0x58, 0x1c, 0x0d, 0x7d, 0x0d, 0x85, 0x24, 0xb8, 0x18, - 0xd3, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xb8, 0xf4, 0x40, 0xca, 0xf4, 0x12, 0xf5, 0x7c, - 0x0d, 0x83, 0x18, 0xd3, 0x9c, 0xac, 0xa3, 0x2c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, - 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0x73, 0x12, 0xf3, 0xd2, 0xf5, 0xc1, 0x9a, 0x93, 0x4a, 0xd3, 0x20, - 0x8c, 0x64, 0xdd, 0xf4, 0xd4, 0x3c, 0xdd, 0xf4, 0x7c, 0xb0, 0xf9, 0x29, 0x89, 0x25, 0x89, 0xfa, - 0x50, 0x0b, 0x93, 0xd8, 0xc0, 0xf2, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x84, 0x2f, 0x18, - 0x23, 0xa8, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto deleted file mode 100755 index abf07f2..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m1.proto +++ /dev/null @@ -1,42 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package test; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports"; - -import "imports/test_a_1/m1.proto"; - -message A1M1 { - test.a.M1 f = 1; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go deleted file mode 100755 index 9e36ebd..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.pb.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_import_a1m2.proto - -package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type A1M2 struct { - F *test_a_1.M2 `protobuf:"bytes,1,opt,name=f" json:"f,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *A1M2) Reset() { *m = A1M2{} } -func (m *A1M2) String() string { return proto.CompactTextString(m) } -func (*A1M2) ProtoMessage() {} -func (*A1M2) Descriptor() ([]byte, []int) { - return fileDescriptor_test_import_a1m2_9a3281ce9464e116, []int{0} -} -func (m *A1M2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_A1M2.Unmarshal(m, b) -} -func (m *A1M2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_A1M2.Marshal(b, m, deterministic) -} -func (dst *A1M2) XXX_Merge(src proto.Message) { - xxx_messageInfo_A1M2.Merge(dst, src) -} -func (m *A1M2) XXX_Size() int { - return xxx_messageInfo_A1M2.Size(m) -} -func (m *A1M2) XXX_DiscardUnknown() { - xxx_messageInfo_A1M2.DiscardUnknown(m) -} - -var xxx_messageInfo_A1M2 proto.InternalMessageInfo - -func (m *A1M2) GetF() *test_a_1.M2 { - if m != nil { - return m.F - } - return nil -} - -func init() { - proto.RegisterType((*A1M2)(nil), "test.A1M2") -} - -func init() { - proto.RegisterFile("imports/test_import_a1m2.proto", fileDescriptor_test_import_a1m2_9a3281ce9464e116) -} - -var fileDescriptor_test_import_a1m2_9a3281ce9464e116 = []byte{ - // 149 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0xcb, 0xcc, 0x2d, 0xc8, - 0x2f, 0x2a, 0x29, 0xd6, 0x2f, 0x49, 0x2d, 0x2e, 0x89, 0x87, 0x70, 0xe2, 0x13, 0x0d, 0x73, 0x8d, - 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xe2, 0x52, 0x92, 0x28, 0xaa, 0x12, 0xe3, - 0x0d, 0xf5, 0x61, 0x0a, 0x94, 0x14, 0xb8, 0x58, 0x1c, 0x0d, 0x7d, 0x8d, 0x84, 0x24, 0xb8, 0x18, - 0xd3, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xb8, 0xf4, 0x40, 0xca, 0xf4, 0x12, 0xf5, 0x7c, - 0x8d, 0x82, 0x18, 0xd3, 0x9c, 0xac, 0xa3, 0x2c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, - 0xf3, 0x73, 0xf5, 0xd3, 0xf3, 0x73, 0x12, 0xf3, 0xd2, 0xf5, 0xc1, 0x9a, 0x93, 0x4a, 0xd3, 0x20, - 0x8c, 0x64, 0xdd, 0xf4, 0xd4, 0x3c, 0xdd, 0xf4, 0x7c, 0xb0, 0xf9, 0x29, 0x89, 0x25, 0x89, 0xfa, - 0x50, 0x0b, 0x93, 0xd8, 0xc0, 0xf2, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1f, 0x88, 0xfb, - 0xea, 0xa8, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto deleted file mode 100755 index 5c53950..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_a1m2.proto +++ /dev/null @@ -1,42 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package test; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports"; - -import "imports/test_a_1/m2.proto"; - -message A1M2 { - test.a.M2 f = 1; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go deleted file mode 100755 index f40e0b7..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.pb.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: imports/test_import_all.proto - -package imports // import "github.com/golang/protobuf/protoc-gen-go/testdata/imports" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import fmt1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/fmt" -import test_a_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_1" -import test_a_2 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_a_2" -import test_b_1 "github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_b_1" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type All struct { - Am1 *test_a_1.M1 `protobuf:"bytes,1,opt,name=am1" json:"am1,omitempty"` - Am2 *test_a_1.M2 `protobuf:"bytes,2,opt,name=am2" json:"am2,omitempty"` - Am3 *test_a_2.M3 `protobuf:"bytes,3,opt,name=am3" json:"am3,omitempty"` - Am4 *test_a_2.M4 `protobuf:"bytes,4,opt,name=am4" json:"am4,omitempty"` - Bm1 *test_b_1.M1 `protobuf:"bytes,5,opt,name=bm1" json:"bm1,omitempty"` - Bm2 *test_b_1.M2 `protobuf:"bytes,6,opt,name=bm2" json:"bm2,omitempty"` - Fmt *fmt1.M `protobuf:"bytes,7,opt,name=fmt" json:"fmt,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *All) Reset() { *m = All{} } -func (m *All) String() string { return proto.CompactTextString(m) } -func (*All) ProtoMessage() {} -func (*All) Descriptor() ([]byte, []int) { - return fileDescriptor_test_import_all_b41dc4592e4a4f3b, []int{0} -} -func (m *All) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_All.Unmarshal(m, b) -} -func (m *All) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_All.Marshal(b, m, deterministic) -} -func (dst *All) XXX_Merge(src proto.Message) { - xxx_messageInfo_All.Merge(dst, src) -} -func (m *All) XXX_Size() int { - return xxx_messageInfo_All.Size(m) -} -func (m *All) XXX_DiscardUnknown() { - xxx_messageInfo_All.DiscardUnknown(m) -} - -var xxx_messageInfo_All proto.InternalMessageInfo - -func (m *All) GetAm1() *test_a_1.M1 { - if m != nil { - return m.Am1 - } - return nil -} - -func (m *All) GetAm2() *test_a_1.M2 { - if m != nil { - return m.Am2 - } - return nil -} - -func (m *All) GetAm3() *test_a_2.M3 { - if m != nil { - return m.Am3 - } - return nil -} - -func (m *All) GetAm4() *test_a_2.M4 { - if m != nil { - return m.Am4 - } - return nil -} - -func (m *All) GetBm1() *test_b_1.M1 { - if m != nil { - return m.Bm1 - } - return nil -} - -func (m *All) GetBm2() *test_b_1.M2 { - if m != nil { - return m.Bm2 - } - return nil -} - -func (m *All) GetFmt() *fmt1.M { - if m != nil { - return m.Fmt - } - return nil -} - -func init() { - proto.RegisterType((*All)(nil), "test.All") -} - -func init() { - proto.RegisterFile("imports/test_import_all.proto", fileDescriptor_test_import_all_b41dc4592e4a4f3b) -} - -var fileDescriptor_test_import_all_b41dc4592e4a4f3b = []byte{ - // 258 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0xd0, 0xb1, 0x4e, 0xc3, 0x30, - 0x10, 0x06, 0x60, 0x15, 0x97, 0x20, 0x99, 0x05, 0x85, 0xc5, 0x20, 0x90, 0x50, 0x27, 0x96, 0xda, - 0xb2, 0x9d, 0x05, 0x31, 0xc1, 0xde, 0xa5, 0x23, 0x4b, 0x64, 0x97, 0xc6, 0x54, 0xf2, 0xd5, 0x51, - 0x7a, 0x7d, 0x5e, 0x5e, 0x05, 0xd9, 0x07, 0x12, 0x84, 0x66, 0x4b, 0xfe, 0xef, 0xb7, 0xce, 0x3e, - 0x7e, 0xbf, 0x83, 0x3e, 0x0d, 0x78, 0x50, 0xb8, 0x3d, 0x60, 0x4b, 0x3f, 0xad, 0x8b, 0x51, 0xf6, - 0x43, 0xc2, 0x54, 0xcf, 0x73, 0x7c, 0x7b, 0xf3, 0xa7, 0xe4, 0x5a, 0xad, 0x40, 0x53, 0xe1, 0x14, - 0x99, 0x09, 0x32, 0x0a, 0xec, 0x34, 0x35, 0x27, 0xc9, 0x4f, 0xcf, 0xf2, 0xbf, 0x67, 0x5d, 0xff, - 0x50, 0x07, 0xa8, 0x80, 0xc2, 0xc5, 0xe7, 0x8c, 0xb3, 0x97, 0x18, 0xeb, 0x3b, 0xce, 0x1c, 0x68, - 0x31, 0x7b, 0x98, 0x3d, 0x5e, 0x1a, 0x2e, 0xf3, 0x69, 0xe9, 0xe4, 0x4a, 0xaf, 0x73, 0x4c, 0x6a, - 0xc4, 0xd9, 0x48, 0x4d, 0x56, 0x43, 0x6a, 0x05, 0x1b, 0xa9, 0xcd, 0x6a, 0x49, 0x1b, 0x31, 0x1f, - 0x69, 0x93, 0xb5, 0xa9, 0x17, 0x9c, 0x79, 0xd0, 0xe2, 0xbc, 0xe8, 0x15, 0xa9, 0x97, 0xbd, 0x1b, - 0x50, 0x97, 0xe9, 0x1e, 0x34, 0x75, 0x8c, 0xa8, 0xfe, 0x77, 0x4c, 0xb9, 0x83, 0x07, 0x53, 0x0b, - 0xce, 0x3a, 0x40, 0x71, 0x51, 0x3a, 0x95, 0xec, 0x00, 0xe5, 0x6a, 0x9d, 0xa3, 0xd7, 0xe7, 0xb7, - 0xa7, 0xb0, 0xc3, 0x8f, 0xa3, 0x97, 0x9b, 0x04, 0x2a, 0xa4, 0xe8, 0xf6, 0x41, 0x95, 0xc7, 0xfb, - 0x63, 0x47, 0x1f, 0x9b, 0x65, 0xd8, 0xee, 0x97, 0x21, 0x95, 0xa5, 0xbd, 0x3b, 0x74, 0xea, 0x7b, - 0x55, 0xbe, 0x2a, 0x6e, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0x95, 0x39, 0xa3, 0x82, 0x03, 0x02, - 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto deleted file mode 100755 index 582d722..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/imports/test_import_all.proto +++ /dev/null @@ -1,58 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package test; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/imports"; - -// test_a_1/m*.proto are in the same Go package and proto package. -// test_a_*/*.proto are in different Go packages, but the same proto package. -// test_b_1/*.proto are in the same Go package, but different proto packages. -// fmt/m.proto has a package name which conflicts with "fmt". -import "imports/test_a_1/m1.proto"; -import "imports/test_a_1/m2.proto"; -import "imports/test_a_2/m3.proto"; -import "imports/test_a_2/m4.proto"; -import "imports/test_b_1/m1.proto"; -import "imports/test_b_1/m2.proto"; -import "imports/fmt/m.proto"; - -message All { - test.a.M1 am1 = 1; - test.a.M2 am2 = 2; - test.a.M3 am3 = 3; - test.a.M4 am4 = 4; - test.b.part1.M1 bm1 = 5; - test.b.part2.M2 bm2 = 6; - fmt.M fmt = 7; -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go deleted file mode 100755 index 7ec1f2d..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// A simple binary to link together the protocol buffers in this test. - -package testdata - -import ( - "testing" - - importspb "github.com/golang/protobuf/protoc-gen-go/testdata/imports" - multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi" - mytestpb "github.com/golang/protobuf/protoc-gen-go/testdata/my_test" -) - -func TestLink(t *testing.T) { - _ = &multipb.Multi1{} - _ = &mytestpb.Request{} - _ = &importspb.All{} -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go deleted file mode 100755 index da0fdf8..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.pb.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: multi/multi1.proto - -package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Multi1 struct { - Multi2 *Multi2 `protobuf:"bytes,1,req,name=multi2" json:"multi2,omitempty"` - Color *Multi2_Color `protobuf:"varint,2,opt,name=color,enum=multitest.Multi2_Color" json:"color,omitempty"` - HatType *Multi3_HatType `protobuf:"varint,3,opt,name=hat_type,json=hatType,enum=multitest.Multi3_HatType" json:"hat_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Multi1) Reset() { *m = Multi1{} } -func (m *Multi1) String() string { return proto.CompactTextString(m) } -func (*Multi1) ProtoMessage() {} -func (*Multi1) Descriptor() ([]byte, []int) { - return fileDescriptor_multi1_08e50c6822e808b8, []int{0} -} -func (m *Multi1) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Multi1.Unmarshal(m, b) -} -func (m *Multi1) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Multi1.Marshal(b, m, deterministic) -} -func (dst *Multi1) XXX_Merge(src proto.Message) { - xxx_messageInfo_Multi1.Merge(dst, src) -} -func (m *Multi1) XXX_Size() int { - return xxx_messageInfo_Multi1.Size(m) -} -func (m *Multi1) XXX_DiscardUnknown() { - xxx_messageInfo_Multi1.DiscardUnknown(m) -} - -var xxx_messageInfo_Multi1 proto.InternalMessageInfo - -func (m *Multi1) GetMulti2() *Multi2 { - if m != nil { - return m.Multi2 - } - return nil -} - -func (m *Multi1) GetColor() Multi2_Color { - if m != nil && m.Color != nil { - return *m.Color - } - return Multi2_BLUE -} - -func (m *Multi1) GetHatType() Multi3_HatType { - if m != nil && m.HatType != nil { - return *m.HatType - } - return Multi3_FEDORA -} - -func init() { - proto.RegisterType((*Multi1)(nil), "multitest.Multi1") -} - -func init() { proto.RegisterFile("multi/multi1.proto", fileDescriptor_multi1_08e50c6822e808b8) } - -var fileDescriptor_multi1_08e50c6822e808b8 = []byte{ - // 200 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29, - 0xc9, 0xd4, 0x07, 0x93, 0x86, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49, - 0x6a, 0x71, 0x89, 0x14, 0xb2, 0xb4, 0x11, 0x44, 0x1a, 0x45, 0xcc, 0x18, 0x22, 0xa6, 0x34, 0x83, - 0x91, 0x8b, 0xcd, 0x17, 0x6c, 0x86, 0x90, 0x26, 0x17, 0x1b, 0x44, 0xb9, 0x04, 0xa3, 0x02, 0x93, - 0x06, 0xb7, 0x91, 0xa0, 0x1e, 0xdc, 0x38, 0x3d, 0xb0, 0x12, 0xa3, 0x20, 0xa8, 0x02, 0x21, 0x5d, - 0x2e, 0xd6, 0xe4, 0xfc, 0x9c, 0xfc, 0x22, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x3e, 0x23, 0x71, 0x0c, - 0x95, 0x7a, 0xce, 0x20, 0xe9, 0x20, 0x88, 0x2a, 0x21, 0x13, 0x2e, 0x8e, 0x8c, 0xc4, 0x92, 0xf8, - 0x92, 0xca, 0x82, 0x54, 0x09, 0x66, 0xb0, 0x0e, 0x49, 0x74, 0x1d, 0xc6, 0x7a, 0x1e, 0x89, 0x25, - 0x21, 0x95, 0x05, 0xa9, 0x41, 0xec, 0x19, 0x10, 0x86, 0x93, 0x73, 0x94, 0x63, 0x7a, 0x66, 0x49, - 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0xba, 0x3e, 0xd8, - 0xd5, 0x49, 0xa5, 0x69, 0x10, 0x46, 0xb2, 0x6e, 0x7a, 0x6a, 0x9e, 0x6e, 0x7a, 0xbe, 0x3e, 0xc8, - 0xa0, 0x94, 0xc4, 0x92, 0x44, 0x88, 0xe7, 0xac, 0xe1, 0x86, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, - 0x60, 0x7d, 0xfc, 0x9f, 0x27, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto deleted file mode 100755 index d3a3204..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto +++ /dev/null @@ -1,46 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -import "multi/multi2.proto"; -import "multi/multi3.proto"; - -package multitest; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest"; - -message Multi1 { - required Multi2 multi2 = 1; - optional Multi2.Color color = 2; - optional Multi3.HatType hat_type = 3; -} - diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go deleted file mode 100755 index b66ce79..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.pb.go +++ /dev/null @@ -1,128 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: multi/multi2.proto - -package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Multi2_Color int32 - -const ( - Multi2_BLUE Multi2_Color = 1 - Multi2_GREEN Multi2_Color = 2 - Multi2_RED Multi2_Color = 3 -) - -var Multi2_Color_name = map[int32]string{ - 1: "BLUE", - 2: "GREEN", - 3: "RED", -} -var Multi2_Color_value = map[string]int32{ - "BLUE": 1, - "GREEN": 2, - "RED": 3, -} - -func (x Multi2_Color) Enum() *Multi2_Color { - p := new(Multi2_Color) - *p = x - return p -} -func (x Multi2_Color) String() string { - return proto.EnumName(Multi2_Color_name, int32(x)) -} -func (x *Multi2_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Multi2_Color_value, data, "Multi2_Color") - if err != nil { - return err - } - *x = Multi2_Color(value) - return nil -} -func (Multi2_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_multi2_c47490ad66d93e67, []int{0, 0} -} - -type Multi2 struct { - RequiredValue *int32 `protobuf:"varint,1,req,name=required_value,json=requiredValue" json:"required_value,omitempty"` - Color *Multi2_Color `protobuf:"varint,2,opt,name=color,enum=multitest.Multi2_Color" json:"color,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Multi2) Reset() { *m = Multi2{} } -func (m *Multi2) String() string { return proto.CompactTextString(m) } -func (*Multi2) ProtoMessage() {} -func (*Multi2) Descriptor() ([]byte, []int) { - return fileDescriptor_multi2_c47490ad66d93e67, []int{0} -} -func (m *Multi2) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Multi2.Unmarshal(m, b) -} -func (m *Multi2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Multi2.Marshal(b, m, deterministic) -} -func (dst *Multi2) XXX_Merge(src proto.Message) { - xxx_messageInfo_Multi2.Merge(dst, src) -} -func (m *Multi2) XXX_Size() int { - return xxx_messageInfo_Multi2.Size(m) -} -func (m *Multi2) XXX_DiscardUnknown() { - xxx_messageInfo_Multi2.DiscardUnknown(m) -} - -var xxx_messageInfo_Multi2 proto.InternalMessageInfo - -func (m *Multi2) GetRequiredValue() int32 { - if m != nil && m.RequiredValue != nil { - return *m.RequiredValue - } - return 0 -} - -func (m *Multi2) GetColor() Multi2_Color { - if m != nil && m.Color != nil { - return *m.Color - } - return Multi2_BLUE -} - -func init() { - proto.RegisterType((*Multi2)(nil), "multitest.Multi2") - proto.RegisterEnum("multitest.Multi2_Color", Multi2_Color_name, Multi2_Color_value) -} - -func init() { proto.RegisterFile("multi/multi2.proto", fileDescriptor_multi2_c47490ad66d93e67) } - -var fileDescriptor_multi2_c47490ad66d93e67 = []byte{ - // 202 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29, - 0xc9, 0xd4, 0x07, 0x93, 0x46, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49, - 0x6a, 0x71, 0x89, 0x52, 0x2b, 0x23, 0x17, 0x9b, 0x2f, 0x58, 0x4e, 0x48, 0x95, 0x8b, 0xaf, 0x28, - 0xb5, 0xb0, 0x34, 0xb3, 0x28, 0x35, 0x25, 0xbe, 0x2c, 0x31, 0xa7, 0x34, 0x55, 0x82, 0x51, 0x81, - 0x49, 0x83, 0x35, 0x88, 0x17, 0x26, 0x1a, 0x06, 0x12, 0x14, 0xd2, 0xe5, 0x62, 0x4d, 0xce, 0xcf, - 0xc9, 0x2f, 0x92, 0x60, 0x52, 0x60, 0xd4, 0xe0, 0x33, 0x12, 0xd7, 0x83, 0x1b, 0xa6, 0x07, 0x31, - 0x48, 0xcf, 0x19, 0x24, 0x1d, 0x04, 0x51, 0xa5, 0xa4, 0xca, 0xc5, 0x0a, 0xe6, 0x0b, 0x71, 0x70, - 0xb1, 0x38, 0xf9, 0x84, 0xba, 0x0a, 0x30, 0x0a, 0x71, 0x72, 0xb1, 0xba, 0x07, 0xb9, 0xba, 0xfa, - 0x09, 0x30, 0x09, 0xb1, 0x73, 0x31, 0x07, 0xb9, 0xba, 0x08, 0x30, 0x3b, 0x39, 0x47, 0x39, 0xa6, - 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, - 0xeb, 0x83, 0x5d, 0x9b, 0x54, 0x9a, 0x06, 0x61, 0x24, 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7, - 0xeb, 0x83, 0xec, 0x4a, 0x49, 0x2c, 0x49, 0x84, 0x78, 0xca, 0x1a, 0x6e, 0x3f, 0x20, 0x00, 0x00, - 0xff, 0xff, 0x49, 0x3b, 0x52, 0x44, 0xec, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto deleted file mode 100755 index ec5b431..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto +++ /dev/null @@ -1,48 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -package multitest; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest"; - -message Multi2 { - required int32 required_value = 1; - - enum Color { - BLUE = 1; - GREEN = 2; - RED = 3; - }; - optional Color color = 2; -} - diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go deleted file mode 100755 index f03c350..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.pb.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: multi/multi3.proto - -package multitest // import "github.com/golang/protobuf/protoc-gen-go/testdata/multi" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Multi3_HatType int32 - -const ( - Multi3_FEDORA Multi3_HatType = 1 - Multi3_FEZ Multi3_HatType = 2 -) - -var Multi3_HatType_name = map[int32]string{ - 1: "FEDORA", - 2: "FEZ", -} -var Multi3_HatType_value = map[string]int32{ - "FEDORA": 1, - "FEZ": 2, -} - -func (x Multi3_HatType) Enum() *Multi3_HatType { - p := new(Multi3_HatType) - *p = x - return p -} -func (x Multi3_HatType) String() string { - return proto.EnumName(Multi3_HatType_name, int32(x)) -} -func (x *Multi3_HatType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Multi3_HatType_value, data, "Multi3_HatType") - if err != nil { - return err - } - *x = Multi3_HatType(value) - return nil -} -func (Multi3_HatType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_multi3_d55a72b4628b7875, []int{0, 0} -} - -type Multi3 struct { - HatType *Multi3_HatType `protobuf:"varint,1,opt,name=hat_type,json=hatType,enum=multitest.Multi3_HatType" json:"hat_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Multi3) Reset() { *m = Multi3{} } -func (m *Multi3) String() string { return proto.CompactTextString(m) } -func (*Multi3) ProtoMessage() {} -func (*Multi3) Descriptor() ([]byte, []int) { - return fileDescriptor_multi3_d55a72b4628b7875, []int{0} -} -func (m *Multi3) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Multi3.Unmarshal(m, b) -} -func (m *Multi3) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Multi3.Marshal(b, m, deterministic) -} -func (dst *Multi3) XXX_Merge(src proto.Message) { - xxx_messageInfo_Multi3.Merge(dst, src) -} -func (m *Multi3) XXX_Size() int { - return xxx_messageInfo_Multi3.Size(m) -} -func (m *Multi3) XXX_DiscardUnknown() { - xxx_messageInfo_Multi3.DiscardUnknown(m) -} - -var xxx_messageInfo_Multi3 proto.InternalMessageInfo - -func (m *Multi3) GetHatType() Multi3_HatType { - if m != nil && m.HatType != nil { - return *m.HatType - } - return Multi3_FEDORA -} - -func init() { - proto.RegisterType((*Multi3)(nil), "multitest.Multi3") - proto.RegisterEnum("multitest.Multi3_HatType", Multi3_HatType_name, Multi3_HatType_value) -} - -func init() { proto.RegisterFile("multi/multi3.proto", fileDescriptor_multi3_d55a72b4628b7875) } - -var fileDescriptor_multi3_d55a72b4628b7875 = []byte{ - // 170 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xca, 0x2d, 0xcd, 0x29, - 0xc9, 0xd4, 0x07, 0x93, 0xc6, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x9c, 0x60, 0x5e, 0x49, - 0x6a, 0x71, 0x89, 0x52, 0x1c, 0x17, 0x9b, 0x2f, 0x58, 0x4a, 0xc8, 0x84, 0x8b, 0x23, 0x23, 0xb1, - 0x24, 0xbe, 0xa4, 0xb2, 0x20, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0xcf, 0x48, 0x52, 0x0f, 0xae, - 0x4e, 0x0f, 0xa2, 0x48, 0xcf, 0x23, 0xb1, 0x24, 0xa4, 0xb2, 0x20, 0x35, 0x88, 0x3d, 0x03, 0xc2, - 0x50, 0x92, 0xe3, 0x62, 0x87, 0x8a, 0x09, 0x71, 0x71, 0xb1, 0xb9, 0xb9, 0xba, 0xf8, 0x07, 0x39, - 0x0a, 0x30, 0x0a, 0xb1, 0x73, 0x31, 0xbb, 0xb9, 0x46, 0x09, 0x30, 0x39, 0x39, 0x47, 0x39, 0xa6, - 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, - 0xeb, 0x83, 0x5d, 0x91, 0x54, 0x9a, 0x06, 0x61, 0x24, 0xeb, 0xa6, 0xa7, 0xe6, 0xe9, 0xa6, 0xe7, - 0xeb, 0x83, 0x2c, 0x4a, 0x49, 0x2c, 0x49, 0x84, 0x38, 0xd6, 0x1a, 0x6e, 0x39, 0x20, 0x00, 0x00, - 0xff, 0xff, 0xd5, 0xa4, 0x1a, 0x0e, 0xc4, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto deleted file mode 100755 index 8690b88..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto +++ /dev/null @@ -1,45 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -package multitest; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/multi;multitest"; - -message Multi3 { - enum HatType { - FEDORA = 1; - FEZ = 2; - }; - optional HatType hat_type = 1; -} - diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go deleted file mode 100755 index 8cf6a69..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go +++ /dev/null @@ -1,1174 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: my_test/test.proto - -package test // import "github.com/golang/protobuf/protoc-gen-go/testdata/my_test" - -/* -This package holds interesting messages. -*/ - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type HatType int32 - -const ( - // deliberately skipping 0 - HatType_FEDORA HatType = 1 - HatType_FEZ HatType = 2 -) - -var HatType_name = map[int32]string{ - 1: "FEDORA", - 2: "FEZ", -} -var HatType_value = map[string]int32{ - "FEDORA": 1, - "FEZ": 2, -} - -func (x HatType) Enum() *HatType { - p := new(HatType) - *p = x - return p -} -func (x HatType) String() string { - return proto.EnumName(HatType_name, int32(x)) -} -func (x *HatType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") - if err != nil { - return err - } - *x = HatType(value) - return nil -} -func (HatType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{0} -} - -// This enum represents days of the week. -type Days int32 - -const ( - Days_MONDAY Days = 1 - Days_TUESDAY Days = 2 - Days_LUNDI Days = 1 -) - -var Days_name = map[int32]string{ - 1: "MONDAY", - 2: "TUESDAY", - // Duplicate value: 1: "LUNDI", -} -var Days_value = map[string]int32{ - "MONDAY": 1, - "TUESDAY": 2, - "LUNDI": 1, -} - -func (x Days) Enum() *Days { - p := new(Days) - *p = x - return p -} -func (x Days) String() string { - return proto.EnumName(Days_name, int32(x)) -} -func (x *Days) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") - if err != nil { - return err - } - *x = Days(value) - return nil -} -func (Days) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{1} -} - -type Request_Color int32 - -const ( - Request_RED Request_Color = 0 - Request_GREEN Request_Color = 1 - Request_BLUE Request_Color = 2 -) - -var Request_Color_name = map[int32]string{ - 0: "RED", - 1: "GREEN", - 2: "BLUE", -} -var Request_Color_value = map[string]int32{ - "RED": 0, - "GREEN": 1, - "BLUE": 2, -} - -func (x Request_Color) Enum() *Request_Color { - p := new(Request_Color) - *p = x - return p -} -func (x Request_Color) String() string { - return proto.EnumName(Request_Color_name, int32(x)) -} -func (x *Request_Color) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") - if err != nil { - return err - } - *x = Request_Color(value) - return nil -} -func (Request_Color) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{0, 0} -} - -type Reply_Entry_Game int32 - -const ( - Reply_Entry_FOOTBALL Reply_Entry_Game = 1 - Reply_Entry_TENNIS Reply_Entry_Game = 2 -) - -var Reply_Entry_Game_name = map[int32]string{ - 1: "FOOTBALL", - 2: "TENNIS", -} -var Reply_Entry_Game_value = map[string]int32{ - "FOOTBALL": 1, - "TENNIS": 2, -} - -func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { - p := new(Reply_Entry_Game) - *p = x - return p -} -func (x Reply_Entry_Game) String() string { - return proto.EnumName(Reply_Entry_Game_name, int32(x)) -} -func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") - if err != nil { - return err - } - *x = Reply_Entry_Game(value) - return nil -} -func (Reply_Entry_Game) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{1, 0, 0} -} - -// This is a message that might be sent somewhere. -type Request struct { - Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` - // optional imp.ImportedMessage imported_message = 2; - Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` - Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` - // optional imp.ImportedMessage.Owner owner = 6; - Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` - Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` - // This is a map field. It will generate map[int32]string. - NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // This is a map field whose value type is a message. - MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` - // This field should not conflict with any getters. - GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{0} -} -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (dst *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(dst, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -const Default_Request_Hat HatType = HatType_FEDORA - -var Default_Request_Deadline float32 = float32(math.Inf(1)) - -func (m *Request) GetKey() []int64 { - if m != nil { - return m.Key - } - return nil -} - -func (m *Request) GetHue() Request_Color { - if m != nil && m.Hue != nil { - return *m.Hue - } - return Request_RED -} - -func (m *Request) GetHat() HatType { - if m != nil && m.Hat != nil { - return *m.Hat - } - return Default_Request_Hat -} - -func (m *Request) GetDeadline() float32 { - if m != nil && m.Deadline != nil { - return *m.Deadline - } - return Default_Request_Deadline -} - -func (m *Request) GetSomegroup() *Request_SomeGroup { - if m != nil { - return m.Somegroup - } - return nil -} - -func (m *Request) GetNameMapping() map[int32]string { - if m != nil { - return m.NameMapping - } - return nil -} - -func (m *Request) GetMsgMapping() map[int64]*Reply { - if m != nil { - return m.MsgMapping - } - return nil -} - -func (m *Request) GetReset_() int32 { - if m != nil && m.Reset_ != nil { - return *m.Reset_ - } - return 0 -} - -func (m *Request) GetGetKey_() string { - if m != nil && m.GetKey_ != nil { - return *m.GetKey_ - } - return "" -} - -type Request_SomeGroup struct { - GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } -func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*Request_SomeGroup) ProtoMessage() {} -func (*Request_SomeGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{0, 0} -} -func (m *Request_SomeGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request_SomeGroup.Unmarshal(m, b) -} -func (m *Request_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request_SomeGroup.Marshal(b, m, deterministic) -} -func (dst *Request_SomeGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request_SomeGroup.Merge(dst, src) -} -func (m *Request_SomeGroup) XXX_Size() int { - return xxx_messageInfo_Request_SomeGroup.Size(m) -} -func (m *Request_SomeGroup) XXX_DiscardUnknown() { - xxx_messageInfo_Request_SomeGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_Request_SomeGroup proto.InternalMessageInfo - -func (m *Request_SomeGroup) GetGroupField() int32 { - if m != nil && m.GroupField != nil { - return *m.GroupField - } - return 0 -} - -type Reply struct { - Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` - CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Reply) Reset() { *m = Reply{} } -func (m *Reply) String() string { return proto.CompactTextString(m) } -func (*Reply) ProtoMessage() {} -func (*Reply) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{1} -} - -var extRange_Reply = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_Reply -} -func (m *Reply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Reply.Unmarshal(m, b) -} -func (m *Reply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Reply.Marshal(b, m, deterministic) -} -func (dst *Reply) XXX_Merge(src proto.Message) { - xxx_messageInfo_Reply.Merge(dst, src) -} -func (m *Reply) XXX_Size() int { - return xxx_messageInfo_Reply.Size(m) -} -func (m *Reply) XXX_DiscardUnknown() { - xxx_messageInfo_Reply.DiscardUnknown(m) -} - -var xxx_messageInfo_Reply proto.InternalMessageInfo - -func (m *Reply) GetFound() []*Reply_Entry { - if m != nil { - return m.Found - } - return nil -} - -func (m *Reply) GetCompactKeys() []int32 { - if m != nil { - return m.CompactKeys - } - return nil -} - -type Reply_Entry struct { - KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` - Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` - XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } -func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } -func (*Reply_Entry) ProtoMessage() {} -func (*Reply_Entry) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{1, 0} -} -func (m *Reply_Entry) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Reply_Entry.Unmarshal(m, b) -} -func (m *Reply_Entry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Reply_Entry.Marshal(b, m, deterministic) -} -func (dst *Reply_Entry) XXX_Merge(src proto.Message) { - xxx_messageInfo_Reply_Entry.Merge(dst, src) -} -func (m *Reply_Entry) XXX_Size() int { - return xxx_messageInfo_Reply_Entry.Size(m) -} -func (m *Reply_Entry) XXX_DiscardUnknown() { - xxx_messageInfo_Reply_Entry.DiscardUnknown(m) -} - -var xxx_messageInfo_Reply_Entry proto.InternalMessageInfo - -const Default_Reply_Entry_Value int64 = 7 - -func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { - if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { - return *m.KeyThatNeeds_1234Camel_CasIng - } - return 0 -} - -func (m *Reply_Entry) GetValue() int64 { - if m != nil && m.Value != nil { - return *m.Value - } - return Default_Reply_Entry_Value -} - -func (m *Reply_Entry) GetXMyFieldName_2() int64 { - if m != nil && m.XMyFieldName_2 != nil { - return *m.XMyFieldName_2 - } - return 0 -} - -type OtherBase struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OtherBase) Reset() { *m = OtherBase{} } -func (m *OtherBase) String() string { return proto.CompactTextString(m) } -func (*OtherBase) ProtoMessage() {} -func (*OtherBase) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{2} -} - -var extRange_OtherBase = []proto.ExtensionRange{ - {Start: 100, End: 536870911}, -} - -func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OtherBase -} -func (m *OtherBase) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OtherBase.Unmarshal(m, b) -} -func (m *OtherBase) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OtherBase.Marshal(b, m, deterministic) -} -func (dst *OtherBase) XXX_Merge(src proto.Message) { - xxx_messageInfo_OtherBase.Merge(dst, src) -} -func (m *OtherBase) XXX_Size() int { - return xxx_messageInfo_OtherBase.Size(m) -} -func (m *OtherBase) XXX_DiscardUnknown() { - xxx_messageInfo_OtherBase.DiscardUnknown(m) -} - -var xxx_messageInfo_OtherBase proto.InternalMessageInfo - -func (m *OtherBase) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -type ReplyExtensions struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } -func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } -func (*ReplyExtensions) ProtoMessage() {} -func (*ReplyExtensions) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{3} -} -func (m *ReplyExtensions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReplyExtensions.Unmarshal(m, b) -} -func (m *ReplyExtensions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReplyExtensions.Marshal(b, m, deterministic) -} -func (dst *ReplyExtensions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReplyExtensions.Merge(dst, src) -} -func (m *ReplyExtensions) XXX_Size() int { - return xxx_messageInfo_ReplyExtensions.Size(m) -} -func (m *ReplyExtensions) XXX_DiscardUnknown() { - xxx_messageInfo_ReplyExtensions.DiscardUnknown(m) -} - -var xxx_messageInfo_ReplyExtensions proto.InternalMessageInfo - -var E_ReplyExtensions_Time = &proto.ExtensionDesc{ - ExtendedType: (*Reply)(nil), - ExtensionType: (*float64)(nil), - Field: 101, - Name: "my.test.ReplyExtensions.time", - Tag: "fixed64,101,opt,name=time", - Filename: "my_test/test.proto", -} - -var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ - ExtendedType: (*Reply)(nil), - ExtensionType: (*ReplyExtensions)(nil), - Field: 105, - Name: "my.test.ReplyExtensions.carrot", - Tag: "bytes,105,opt,name=carrot", - Filename: "my_test/test.proto", -} - -var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ - ExtendedType: (*OtherBase)(nil), - ExtensionType: (*ReplyExtensions)(nil), - Field: 101, - Name: "my.test.ReplyExtensions.donut", - Tag: "bytes,101,opt,name=donut", - Filename: "my_test/test.proto", -} - -type OtherReplyExtensions struct { - Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } -func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } -func (*OtherReplyExtensions) ProtoMessage() {} -func (*OtherReplyExtensions) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{4} -} -func (m *OtherReplyExtensions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OtherReplyExtensions.Unmarshal(m, b) -} -func (m *OtherReplyExtensions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OtherReplyExtensions.Marshal(b, m, deterministic) -} -func (dst *OtherReplyExtensions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OtherReplyExtensions.Merge(dst, src) -} -func (m *OtherReplyExtensions) XXX_Size() int { - return xxx_messageInfo_OtherReplyExtensions.Size(m) -} -func (m *OtherReplyExtensions) XXX_DiscardUnknown() { - xxx_messageInfo_OtherReplyExtensions.DiscardUnknown(m) -} - -var xxx_messageInfo_OtherReplyExtensions proto.InternalMessageInfo - -func (m *OtherReplyExtensions) GetKey() int32 { - if m != nil && m.Key != nil { - return *m.Key - } - return 0 -} - -type OldReply struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `protobuf_messageset:"1" json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OldReply) Reset() { *m = OldReply{} } -func (m *OldReply) String() string { return proto.CompactTextString(m) } -func (*OldReply) ProtoMessage() {} -func (*OldReply) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{5} -} - -func (m *OldReply) MarshalJSON() ([]byte, error) { - return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) -} -func (m *OldReply) UnmarshalJSON(buf []byte) error { - return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) -} - -var extRange_OldReply = []proto.ExtensionRange{ - {Start: 100, End: 2147483646}, -} - -func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OldReply -} -func (m *OldReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OldReply.Unmarshal(m, b) -} -func (m *OldReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OldReply.Marshal(b, m, deterministic) -} -func (dst *OldReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_OldReply.Merge(dst, src) -} -func (m *OldReply) XXX_Size() int { - return xxx_messageInfo_OldReply.Size(m) -} -func (m *OldReply) XXX_DiscardUnknown() { - xxx_messageInfo_OldReply.DiscardUnknown(m) -} - -var xxx_messageInfo_OldReply proto.InternalMessageInfo - -type Communique struct { - MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` - // This is a oneof, called "union". - // - // Types that are valid to be assigned to Union: - // *Communique_Number - // *Communique_Name - // *Communique_Data - // *Communique_TempC - // *Communique_Height - // *Communique_Today - // *Communique_Maybe - // *Communique_Delta_ - // *Communique_Msg - // *Communique_Somegroup - Union isCommunique_Union `protobuf_oneof:"union"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Communique) Reset() { *m = Communique{} } -func (m *Communique) String() string { return proto.CompactTextString(m) } -func (*Communique) ProtoMessage() {} -func (*Communique) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{6} -} -func (m *Communique) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Communique.Unmarshal(m, b) -} -func (m *Communique) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Communique.Marshal(b, m, deterministic) -} -func (dst *Communique) XXX_Merge(src proto.Message) { - xxx_messageInfo_Communique.Merge(dst, src) -} -func (m *Communique) XXX_Size() int { - return xxx_messageInfo_Communique.Size(m) -} -func (m *Communique) XXX_DiscardUnknown() { - xxx_messageInfo_Communique.DiscardUnknown(m) -} - -var xxx_messageInfo_Communique proto.InternalMessageInfo - -type isCommunique_Union interface { - isCommunique_Union() -} - -type Communique_Number struct { - Number int32 `protobuf:"varint,5,opt,name=number,oneof"` -} -type Communique_Name struct { - Name string `protobuf:"bytes,6,opt,name=name,oneof"` -} -type Communique_Data struct { - Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` -} -type Communique_TempC struct { - TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` -} -type Communique_Height struct { - Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` -} -type Communique_Today struct { - Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` -} -type Communique_Maybe struct { - Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` -} -type Communique_Delta_ struct { - Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` -} -type Communique_Msg struct { - Msg *Reply `protobuf:"bytes,16,opt,name=msg,oneof"` -} -type Communique_Somegroup struct { - Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"` -} - -func (*Communique_Number) isCommunique_Union() {} -func (*Communique_Name) isCommunique_Union() {} -func (*Communique_Data) isCommunique_Union() {} -func (*Communique_TempC) isCommunique_Union() {} -func (*Communique_Height) isCommunique_Union() {} -func (*Communique_Today) isCommunique_Union() {} -func (*Communique_Maybe) isCommunique_Union() {} -func (*Communique_Delta_) isCommunique_Union() {} -func (*Communique_Msg) isCommunique_Union() {} -func (*Communique_Somegroup) isCommunique_Union() {} - -func (m *Communique) GetUnion() isCommunique_Union { - if m != nil { - return m.Union - } - return nil -} - -func (m *Communique) GetMakeMeCry() bool { - if m != nil && m.MakeMeCry != nil { - return *m.MakeMeCry - } - return false -} - -func (m *Communique) GetNumber() int32 { - if x, ok := m.GetUnion().(*Communique_Number); ok { - return x.Number - } - return 0 -} - -func (m *Communique) GetName() string { - if x, ok := m.GetUnion().(*Communique_Name); ok { - return x.Name - } - return "" -} - -func (m *Communique) GetData() []byte { - if x, ok := m.GetUnion().(*Communique_Data); ok { - return x.Data - } - return nil -} - -func (m *Communique) GetTempC() float64 { - if x, ok := m.GetUnion().(*Communique_TempC); ok { - return x.TempC - } - return 0 -} - -func (m *Communique) GetHeight() float32 { - if x, ok := m.GetUnion().(*Communique_Height); ok { - return x.Height - } - return 0 -} - -func (m *Communique) GetToday() Days { - if x, ok := m.GetUnion().(*Communique_Today); ok { - return x.Today - } - return Days_MONDAY -} - -func (m *Communique) GetMaybe() bool { - if x, ok := m.GetUnion().(*Communique_Maybe); ok { - return x.Maybe - } - return false -} - -func (m *Communique) GetDelta() int32 { - if x, ok := m.GetUnion().(*Communique_Delta_); ok { - return x.Delta - } - return 0 -} - -func (m *Communique) GetMsg() *Reply { - if x, ok := m.GetUnion().(*Communique_Msg); ok { - return x.Msg - } - return nil -} - -func (m *Communique) GetSomegroup() *Communique_SomeGroup { - if x, ok := m.GetUnion().(*Communique_Somegroup); ok { - return x.Somegroup - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ - (*Communique_Number)(nil), - (*Communique_Name)(nil), - (*Communique_Data)(nil), - (*Communique_TempC)(nil), - (*Communique_Height)(nil), - (*Communique_Today)(nil), - (*Communique_Maybe)(nil), - (*Communique_Delta_)(nil), - (*Communique_Msg)(nil), - (*Communique_Somegroup)(nil), - } -} - -func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Communique) - // union - switch x := m.Union.(type) { - case *Communique_Number: - b.EncodeVarint(5<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Number)) - case *Communique_Name: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Name) - case *Communique_Data: - b.EncodeVarint(7<<3 | proto.WireBytes) - b.EncodeRawBytes(x.Data) - case *Communique_TempC: - b.EncodeVarint(8<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.TempC)) - case *Communique_Height: - b.EncodeVarint(9<<3 | proto.WireFixed32) - b.EncodeFixed32(uint64(math.Float32bits(x.Height))) - case *Communique_Today: - b.EncodeVarint(10<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Today)) - case *Communique_Maybe: - t := uint64(0) - if x.Maybe { - t = 1 - } - b.EncodeVarint(11<<3 | proto.WireVarint) - b.EncodeVarint(t) - case *Communique_Delta_: - b.EncodeVarint(12<<3 | proto.WireVarint) - b.EncodeZigzag32(uint64(x.Delta)) - case *Communique_Msg: - b.EncodeVarint(16<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Msg); err != nil { - return err - } - case *Communique_Somegroup: - b.EncodeVarint(14<<3 | proto.WireStartGroup) - if err := b.Marshal(x.Somegroup); err != nil { - return err - } - b.EncodeVarint(14<<3 | proto.WireEndGroup) - case nil: - default: - return fmt.Errorf("Communique.Union has unexpected type %T", x) - } - return nil -} - -func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Communique) - switch tag { - case 5: // union.number - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Number{int32(x)} - return true, err - case 6: // union.name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Union = &Communique_Name{x} - return true, err - case 7: // union.data - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeRawBytes(true) - m.Union = &Communique_Data{x} - return true, err - case 8: // union.temp_c - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Union = &Communique_TempC{math.Float64frombits(x)} - return true, err - case 9: // union.height - if wire != proto.WireFixed32 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed32() - m.Union = &Communique_Height{math.Float32frombits(uint32(x))} - return true, err - case 10: // union.today - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Today{Days(x)} - return true, err - case 11: // union.maybe - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Union = &Communique_Maybe{x != 0} - return true, err - case 12: // union.delta - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeZigzag32() - m.Union = &Communique_Delta_{int32(x)} - return true, err - case 16: // union.msg - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Reply) - err := b.DecodeMessage(msg) - m.Union = &Communique_Msg{msg} - return true, err - case 14: // union.somegroup - if wire != proto.WireStartGroup { - return true, proto.ErrInternalBadWireType - } - msg := new(Communique_SomeGroup) - err := b.DecodeGroup(msg) - m.Union = &Communique_Somegroup{msg} - return true, err - default: - return false, nil - } -} - -func _Communique_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Communique) - // union - switch x := m.Union.(type) { - case *Communique_Number: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Number)) - case *Communique_Name: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Name))) - n += len(x.Name) - case *Communique_Data: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Data))) - n += len(x.Data) - case *Communique_TempC: - n += 1 // tag and wire - n += 8 - case *Communique_Height: - n += 1 // tag and wire - n += 4 - case *Communique_Today: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Today)) - case *Communique_Maybe: - n += 1 // tag and wire - n += 1 - case *Communique_Delta_: - n += 1 // tag and wire - n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) - case *Communique_Msg: - s := proto.Size(x.Msg) - n += 2 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Communique_Somegroup: - n += 1 // tag and wire - n += proto.Size(x.Somegroup) - n += 1 // tag and wire - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Communique_SomeGroup struct { - Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } -func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } -func (*Communique_SomeGroup) ProtoMessage() {} -func (*Communique_SomeGroup) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{6, 0} -} -func (m *Communique_SomeGroup) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Communique_SomeGroup.Unmarshal(m, b) -} -func (m *Communique_SomeGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Communique_SomeGroup.Marshal(b, m, deterministic) -} -func (dst *Communique_SomeGroup) XXX_Merge(src proto.Message) { - xxx_messageInfo_Communique_SomeGroup.Merge(dst, src) -} -func (m *Communique_SomeGroup) XXX_Size() int { - return xxx_messageInfo_Communique_SomeGroup.Size(m) -} -func (m *Communique_SomeGroup) XXX_DiscardUnknown() { - xxx_messageInfo_Communique_SomeGroup.DiscardUnknown(m) -} - -var xxx_messageInfo_Communique_SomeGroup proto.InternalMessageInfo - -func (m *Communique_SomeGroup) GetMember() string { - if m != nil && m.Member != nil { - return *m.Member - } - return "" -} - -type Communique_Delta struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } -func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } -func (*Communique_Delta) ProtoMessage() {} -func (*Communique_Delta) Descriptor() ([]byte, []int) { - return fileDescriptor_test_2309d445eee26af7, []int{6, 1} -} -func (m *Communique_Delta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Communique_Delta.Unmarshal(m, b) -} -func (m *Communique_Delta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Communique_Delta.Marshal(b, m, deterministic) -} -func (dst *Communique_Delta) XXX_Merge(src proto.Message) { - xxx_messageInfo_Communique_Delta.Merge(dst, src) -} -func (m *Communique_Delta) XXX_Size() int { - return xxx_messageInfo_Communique_Delta.Size(m) -} -func (m *Communique_Delta) XXX_DiscardUnknown() { - xxx_messageInfo_Communique_Delta.DiscardUnknown(m) -} - -var xxx_messageInfo_Communique_Delta proto.InternalMessageInfo - -var E_Tag = &proto.ExtensionDesc{ - ExtendedType: (*Reply)(nil), - ExtensionType: (*string)(nil), - Field: 103, - Name: "my.test.tag", - Tag: "bytes,103,opt,name=tag", - Filename: "my_test/test.proto", -} - -var E_Donut = &proto.ExtensionDesc{ - ExtendedType: (*Reply)(nil), - ExtensionType: (*OtherReplyExtensions)(nil), - Field: 106, - Name: "my.test.donut", - Tag: "bytes,106,opt,name=donut", - Filename: "my_test/test.proto", -} - -func init() { - proto.RegisterType((*Request)(nil), "my.test.Request") - proto.RegisterMapType((map[int64]*Reply)(nil), "my.test.Request.MsgMappingEntry") - proto.RegisterMapType((map[int32]string)(nil), "my.test.Request.NameMappingEntry") - proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") - proto.RegisterType((*Reply)(nil), "my.test.Reply") - proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") - proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") - proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") - proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") - proto.RegisterType((*OldReply)(nil), "my.test.OldReply") - proto.RegisterType((*Communique)(nil), "my.test.Communique") - proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") - proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") - proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) - proto.RegisterEnum("my.test.Days", Days_name, Days_value) - proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) - proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) - proto.RegisterExtension(E_ReplyExtensions_Time) - proto.RegisterExtension(E_ReplyExtensions_Carrot) - proto.RegisterExtension(E_ReplyExtensions_Donut) - proto.RegisterExtension(E_Tag) - proto.RegisterExtension(E_Donut) -} - -func init() { proto.RegisterFile("my_test/test.proto", fileDescriptor_test_2309d445eee26af7) } - -var fileDescriptor_test_2309d445eee26af7 = []byte{ - // 1033 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x55, 0xdd, 0x6e, 0xe3, 0x44, - 0x14, 0xce, 0xd8, 0x71, 0x7e, 0x4e, 0x42, 0x6b, 0x46, 0x55, 0x6b, 0x05, 0xed, 0xd6, 0x04, 0x8a, - 0x4c, 0xc5, 0xa6, 0xda, 0x80, 0xc4, 0x2a, 0x88, 0xd5, 0x36, 0x3f, 0x6d, 0xaa, 0x6d, 0x12, 0x69, - 0xda, 0x5e, 0xb0, 0x37, 0xd6, 0x34, 0x9e, 0x3a, 0xa6, 0x19, 0x3b, 0x6b, 0x8f, 0x11, 0xbe, 0xeb, - 0x53, 0xc0, 0x6b, 0x70, 0xcf, 0x0b, 0xf1, 0x16, 0x45, 0x33, 0x0e, 0x49, 0xda, 0xa0, 0xbd, 0xb1, - 0x7c, 0xce, 0xf9, 0xce, 0xe7, 0x39, 0x3f, 0xfe, 0x06, 0x30, 0xcf, 0x5c, 0xc1, 0x12, 0x71, 0x22, - 0x1f, 0xad, 0x45, 0x1c, 0x89, 0x08, 0x97, 0x79, 0xd6, 0x92, 0x66, 0x03, 0xf3, 0x74, 0x2e, 0x82, - 0x13, 0xf5, 0x7c, 0x9d, 0x07, 0x9b, 0xff, 0x14, 0xa1, 0x4c, 0xd8, 0xc7, 0x94, 0x25, 0x02, 0x9b, - 0xa0, 0xdf, 0xb3, 0xcc, 0x42, 0xb6, 0xee, 0xe8, 0x44, 0xbe, 0x62, 0x07, 0xf4, 0x59, 0xca, 0x2c, - 0xdd, 0x46, 0xce, 0x4e, 0x7b, 0xbf, 0xb5, 0x24, 0x6a, 0x2d, 0x13, 0x5a, 0xbd, 0x68, 0x1e, 0xc5, - 0x44, 0x42, 0xf0, 0x31, 0xe8, 0x33, 0x2a, 0xac, 0xa2, 0x42, 0x9a, 0x2b, 0xe4, 0x90, 0x8a, 0xeb, - 0x6c, 0xc1, 0x3a, 0xa5, 0xb3, 0x41, 0x7f, 0x42, 0x4e, 0x89, 0x04, 0xe1, 0x43, 0xa8, 0x78, 0x8c, - 0x7a, 0xf3, 0x20, 0x64, 0x56, 0xd9, 0x46, 0x8e, 0xd6, 0xd1, 0x83, 0xf0, 0x8e, 0xac, 0x9c, 0xf8, - 0x0d, 0x54, 0x93, 0x88, 0x33, 0x3f, 0x8e, 0xd2, 0x85, 0x55, 0xb1, 0x91, 0x03, 0xed, 0xc6, 0xd6, - 0xc7, 0xaf, 0x22, 0xce, 0xce, 0x25, 0x82, 0xac, 0xc1, 0xb8, 0x0f, 0xf5, 0x90, 0x72, 0xe6, 0x72, - 0xba, 0x58, 0x04, 0xa1, 0x6f, 0xed, 0xd8, 0xba, 0x53, 0x6b, 0x7f, 0xb9, 0x95, 0x3c, 0xa6, 0x9c, - 0x8d, 0x72, 0xcc, 0x20, 0x14, 0x71, 0x46, 0x6a, 0xe1, 0xda, 0x83, 0x4f, 0xa1, 0xc6, 0x13, 0x7f, - 0x45, 0xb2, 0xab, 0x48, 0xec, 0x2d, 0x92, 0x51, 0xe2, 0x3f, 0xe1, 0x00, 0xbe, 0x72, 0xe0, 0x3d, - 0x30, 0x62, 0x96, 0x30, 0x61, 0xd5, 0x6d, 0xe4, 0x18, 0x24, 0x37, 0xf0, 0x01, 0x94, 0x7d, 0x26, - 0x5c, 0xd9, 0x65, 0xd3, 0x46, 0x4e, 0x95, 0x94, 0x7c, 0x26, 0xde, 0xb3, 0xac, 0xf1, 0x1d, 0x54, - 0x57, 0xf5, 0xe0, 0x43, 0xa8, 0xa9, 0x6a, 0xdc, 0xbb, 0x80, 0xcd, 0x3d, 0xab, 0xaa, 0x18, 0x40, - 0xb9, 0xce, 0xa4, 0xa7, 0xf1, 0x16, 0xcc, 0xe7, 0x05, 0xac, 0x87, 0x27, 0xc1, 0x6a, 0x78, 0x7b, - 0x60, 0xfc, 0x46, 0xe7, 0x29, 0xb3, 0x34, 0xf5, 0xa9, 0xdc, 0xe8, 0x68, 0x6f, 0x50, 0x63, 0x04, - 0xbb, 0xcf, 0xce, 0xbe, 0x99, 0x8e, 0xf3, 0xf4, 0xaf, 0x37, 0xd3, 0x6b, 0xed, 0x9d, 0x8d, 0xf2, - 0x17, 0xf3, 0x6c, 0x83, 0xae, 0x79, 0x04, 0x86, 0xda, 0x04, 0x5c, 0x06, 0x9d, 0x0c, 0xfa, 0x66, - 0x01, 0x57, 0xc1, 0x38, 0x27, 0x83, 0xc1, 0xd8, 0x44, 0xb8, 0x02, 0xc5, 0xee, 0xe5, 0xcd, 0xc0, - 0xd4, 0x9a, 0x7f, 0x6a, 0x60, 0xa8, 0x5c, 0x7c, 0x0c, 0xc6, 0x5d, 0x94, 0x86, 0x9e, 0x5a, 0xb5, - 0x5a, 0x7b, 0xef, 0x29, 0x75, 0x2b, 0xef, 0x66, 0x0e, 0xc1, 0x47, 0x50, 0x9f, 0x46, 0x7c, 0x41, - 0xa7, 0xaa, 0x6d, 0x89, 0xa5, 0xd9, 0xba, 0x63, 0x74, 0x35, 0x13, 0x91, 0xda, 0xd2, 0xff, 0x9e, - 0x65, 0x49, 0xe3, 0x2f, 0x04, 0x46, 0x5e, 0x49, 0x1f, 0x0e, 0xef, 0x59, 0xe6, 0x8a, 0x19, 0x15, - 0x6e, 0xc8, 0x98, 0x97, 0xb8, 0xaf, 0xdb, 0xdf, 0xff, 0x30, 0xa5, 0x9c, 0xcd, 0xdd, 0x1e, 0x4d, - 0x2e, 0x42, 0xdf, 0x42, 0xb6, 0xe6, 0xe8, 0xe4, 0x8b, 0x7b, 0x96, 0x5d, 0xcf, 0xa8, 0x18, 0x4b, - 0xd0, 0x0a, 0x93, 0x43, 0xf0, 0xc1, 0x66, 0xf5, 0x7a, 0x07, 0xfd, 0xb8, 0x2c, 0x18, 0x7f, 0x03, - 0xa6, 0xcb, 0xb3, 0x7c, 0x34, 0xae, 0xda, 0xb5, 0xb6, 0xfa, 0x3f, 0x74, 0x52, 0x1f, 0x65, 0x6a, - 0x3c, 0x72, 0x34, 0xed, 0xa6, 0x0d, 0xc5, 0x73, 0xca, 0x19, 0xae, 0x43, 0xe5, 0x6c, 0x32, 0xb9, - 0xee, 0x9e, 0x5e, 0x5e, 0x9a, 0x08, 0x03, 0x94, 0xae, 0x07, 0xe3, 0xf1, 0xc5, 0x95, 0xa9, 0x1d, - 0x57, 0x2a, 0x9e, 0xf9, 0xf0, 0xf0, 0xf0, 0xa0, 0x35, 0xbf, 0x85, 0xea, 0x44, 0xcc, 0x58, 0xdc, - 0xa5, 0x09, 0xc3, 0x18, 0x8a, 0x92, 0x56, 0x8d, 0xa2, 0x4a, 0xd4, 0xfb, 0x06, 0xf4, 0x6f, 0x04, - 0xbb, 0xaa, 0x4b, 0x83, 0xdf, 0x05, 0x0b, 0x93, 0x20, 0x0a, 0x93, 0x76, 0x13, 0x8a, 0x22, 0xe0, - 0x0c, 0x3f, 0x1b, 0x91, 0xc5, 0x6c, 0xe4, 0x20, 0xa2, 0x62, 0xed, 0x77, 0x50, 0x9a, 0xd2, 0x38, - 0x8e, 0xc4, 0x16, 0x2a, 0x50, 0xe3, 0xb5, 0x9e, 0x7a, 0xd7, 0xec, 0x64, 0x99, 0xd7, 0xee, 0x82, - 0xe1, 0x45, 0x61, 0x2a, 0x30, 0x5e, 0x41, 0x57, 0x87, 0x56, 0x9f, 0xfa, 0x14, 0x49, 0x9e, 0xda, - 0x74, 0x60, 0x4f, 0xe5, 0x3c, 0x0b, 0x6f, 0x2f, 0x6f, 0xd3, 0x82, 0xca, 0x64, 0xee, 0x29, 0x9c, - 0xaa, 0xfe, 0xf1, 0xf1, 0xf1, 0xb1, 0xdc, 0xd1, 0x2a, 0xa8, 0xf9, 0x87, 0x0e, 0xd0, 0x8b, 0x38, - 0x4f, 0xc3, 0xe0, 0x63, 0xca, 0xf0, 0x4b, 0xa8, 0x71, 0x7a, 0xcf, 0x5c, 0xce, 0xdc, 0x69, 0x9c, - 0x53, 0x54, 0x48, 0x55, 0xba, 0x46, 0xac, 0x17, 0x67, 0xd8, 0x82, 0x52, 0x98, 0xf2, 0x5b, 0x16, - 0x5b, 0x86, 0x64, 0x1f, 0x16, 0xc8, 0xd2, 0xc6, 0x7b, 0xcb, 0x46, 0x97, 0x64, 0xa3, 0x87, 0x85, - 0xbc, 0xd5, 0xd2, 0xeb, 0x51, 0x41, 0x95, 0x30, 0xd5, 0xa5, 0x57, 0x5a, 0xf8, 0x00, 0x4a, 0x82, - 0xf1, 0x85, 0x3b, 0x55, 0x72, 0x84, 0x86, 0x05, 0x62, 0x48, 0xbb, 0x27, 0xe9, 0x67, 0x2c, 0xf0, - 0x67, 0x42, 0xfd, 0xa6, 0x9a, 0xa4, 0xcf, 0x6d, 0x7c, 0x04, 0x86, 0x88, 0x3c, 0x9a, 0x59, 0xa0, - 0x34, 0xf1, 0xb3, 0x55, 0x6f, 0xfa, 0x34, 0x4b, 0x14, 0x81, 0x8c, 0xe2, 0x7d, 0x30, 0x38, 0xcd, - 0x6e, 0x99, 0x55, 0x93, 0x27, 0x97, 0x7e, 0x65, 0x4a, 0xbf, 0xc7, 0xe6, 0x82, 0x2a, 0x01, 0xf9, - 0x5c, 0xfa, 0x95, 0x89, 0x9b, 0xa0, 0xf3, 0xc4, 0x57, 0xf2, 0xb1, 0xf5, 0x53, 0x0e, 0x0b, 0x44, - 0x06, 0xf1, 0xcf, 0x9b, 0xfa, 0xb9, 0xa3, 0xf4, 0xf3, 0xc5, 0x0a, 0xb9, 0xee, 0xdd, 0x5a, 0x42, - 0x87, 0x85, 0x0d, 0x11, 0x6d, 0x7c, 0xb5, 0x29, 0x46, 0xfb, 0x50, 0xe2, 0x4c, 0xf5, 0x6f, 0x37, - 0x57, 0xac, 0xdc, 0x6a, 0x94, 0xc1, 0xe8, 0xcb, 0x03, 0x75, 0xcb, 0x60, 0xa4, 0x61, 0x10, 0x85, - 0xc7, 0x2f, 0xa1, 0xbc, 0x94, 0x7b, 0xb9, 0xe6, 0xb9, 0xe0, 0x9b, 0x48, 0x8a, 0xc2, 0xd9, 0xe0, - 0x83, 0xa9, 0x1d, 0xb7, 0xa0, 0x28, 0x4b, 0x97, 0xc1, 0xd1, 0x64, 0xdc, 0x3f, 0xfd, 0xc5, 0x44, - 0xb8, 0x06, 0xe5, 0xeb, 0x9b, 0xc1, 0x95, 0x34, 0x34, 0xa9, 0x1a, 0x97, 0x37, 0xe3, 0xfe, 0x85, - 0x89, 0x1a, 0x9a, 0x89, 0x3a, 0x36, 0xe8, 0x82, 0xfa, 0x5b, 0xfb, 0xea, 0xab, 0x63, 0xc8, 0x50, - 0xa7, 0xf7, 0xdf, 0x4a, 0x3e, 0xc7, 0xfc, 0xaa, 0xba, 0xf3, 0xe2, 0xe9, 0xa2, 0xfe, 0xff, 0x4e, - 0x76, 0xdf, 0x7d, 0x78, 0xeb, 0x07, 0x62, 0x96, 0xde, 0xb6, 0xa6, 0x11, 0x3f, 0xf1, 0xa3, 0x39, - 0x0d, 0xfd, 0x13, 0x75, 0x39, 0xde, 0xa6, 0x77, 0xf9, 0xcb, 0xf4, 0x95, 0xcf, 0xc2, 0x57, 0x7e, - 0xa4, 0x6e, 0x55, 0xb9, 0x0f, 0x27, 0xcb, 0x6b, 0xf6, 0x27, 0xf9, 0xf8, 0x37, 0x00, 0x00, 0xff, - 0xff, 0x12, 0xd5, 0x46, 0x00, 0x75, 0x07, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto deleted file mode 100755 index 1ef3fd0..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto +++ /dev/null @@ -1,158 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; - -// This package holds interesting messages. -package my.test; // dotted package name - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/my_test;test"; - -//import "imp.proto"; -import "multi/multi1.proto"; // unused import - -enum HatType { - // deliberately skipping 0 - FEDORA = 1; - FEZ = 2; -} - -// This enum represents days of the week. -enum Days { - option allow_alias = true; - - MONDAY = 1; - TUESDAY = 2; - LUNDI = 1; // same value as MONDAY -} - -// This is a message that might be sent somewhere. -message Request { - enum Color { - RED = 0; - GREEN = 1; - BLUE = 2; - } - repeated int64 key = 1; -// optional imp.ImportedMessage imported_message = 2; - optional Color hue = 3; // no default - optional HatType hat = 4 [default=FEDORA]; -// optional imp.ImportedMessage.Owner owner = 6; - optional float deadline = 7 [default=inf]; - optional group SomeGroup = 8 { - optional int32 group_field = 9; - } - - // These foreign types are in imp2.proto, - // which is publicly imported by imp.proto. -// optional imp.PubliclyImportedMessage pub = 10; -// optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR]; - - - // This is a map field. It will generate map[int32]string. - map name_mapping = 14; - // This is a map field whose value type is a message. - map msg_mapping = 15; - - optional int32 reset = 12; - // This field should not conflict with any getters. - optional string get_key = 16; -} - -message Reply { - message Entry { - required int64 key_that_needs_1234camel_CasIng = 1; - optional int64 value = 2 [default=7]; - optional int64 _my_field_name_2 = 3; - enum Game { - FOOTBALL = 1; - TENNIS = 2; - } - } - repeated Entry found = 1; - repeated int32 compact_keys = 2 [packed=true]; - extensions 100 to max; -} - -message OtherBase { - optional string name = 1; - extensions 100 to max; -} - -message ReplyExtensions { - extend Reply { - optional double time = 101; - optional ReplyExtensions carrot = 105; - } - extend OtherBase { - optional ReplyExtensions donut = 101; - } -} - -message OtherReplyExtensions { - optional int32 key = 1; -} - -// top-level extension -extend Reply { - optional string tag = 103; - optional OtherReplyExtensions donut = 106; -// optional imp.ImportedMessage elephant = 107; // extend with message from another file. -} - -message OldReply { - // Extensions will be encoded in MessageSet wire format. - option message_set_wire_format = true; - extensions 100 to max; -} - -message Communique { - optional bool make_me_cry = 1; - - // This is a oneof, called "union". - oneof union { - int32 number = 5; - string name = 6; - bytes data = 7; - double temp_c = 8; - float height = 9; - Days today = 10; - bool maybe = 11; - sint32 delta = 12; // name will conflict with Delta below - Reply msg = 16; // requires two bytes to encode field tag - group SomeGroup = 14 { - optional string member = 15; - } - } - - message Delta {} -} - diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go deleted file mode 100755 index 3b0ad84..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.pb.go +++ /dev/null @@ -1,196 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto3/proto3.proto - -package proto3 // import "github.com/golang/protobuf/protoc-gen-go/testdata/proto3" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Request_Flavour int32 - -const ( - Request_SWEET Request_Flavour = 0 - Request_SOUR Request_Flavour = 1 - Request_UMAMI Request_Flavour = 2 - Request_GOPHERLICIOUS Request_Flavour = 3 -) - -var Request_Flavour_name = map[int32]string{ - 0: "SWEET", - 1: "SOUR", - 2: "UMAMI", - 3: "GOPHERLICIOUS", -} -var Request_Flavour_value = map[string]int32{ - "SWEET": 0, - "SOUR": 1, - "UMAMI": 2, - "GOPHERLICIOUS": 3, -} - -func (x Request_Flavour) String() string { - return proto.EnumName(Request_Flavour_name, int32(x)) -} -func (Request_Flavour) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_proto3_a752e09251f17e01, []int{0, 0} -} - -type Request struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Key []int64 `protobuf:"varint,2,rep,packed,name=key" json:"key,omitempty"` - Taste Request_Flavour `protobuf:"varint,3,opt,name=taste,enum=proto3.Request_Flavour" json:"taste,omitempty"` - Book *Book `protobuf:"bytes,4,opt,name=book" json:"book,omitempty"` - Unpacked []int64 `protobuf:"varint,5,rep,name=unpacked" json:"unpacked,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_a752e09251f17e01, []int{0} -} -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (dst *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(dst, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -func (m *Request) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Request) GetKey() []int64 { - if m != nil { - return m.Key - } - return nil -} - -func (m *Request) GetTaste() Request_Flavour { - if m != nil { - return m.Taste - } - return Request_SWEET -} - -func (m *Request) GetBook() *Book { - if m != nil { - return m.Book - } - return nil -} - -func (m *Request) GetUnpacked() []int64 { - if m != nil { - return m.Unpacked - } - return nil -} - -type Book struct { - Title string `protobuf:"bytes,1,opt,name=title" json:"title,omitempty"` - RawData []byte `protobuf:"bytes,2,opt,name=raw_data,json=rawData,proto3" json:"raw_data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Book) Reset() { *m = Book{} } -func (m *Book) String() string { return proto.CompactTextString(m) } -func (*Book) ProtoMessage() {} -func (*Book) Descriptor() ([]byte, []int) { - return fileDescriptor_proto3_a752e09251f17e01, []int{1} -} -func (m *Book) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Book.Unmarshal(m, b) -} -func (m *Book) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Book.Marshal(b, m, deterministic) -} -func (dst *Book) XXX_Merge(src proto.Message) { - xxx_messageInfo_Book.Merge(dst, src) -} -func (m *Book) XXX_Size() int { - return xxx_messageInfo_Book.Size(m) -} -func (m *Book) XXX_DiscardUnknown() { - xxx_messageInfo_Book.DiscardUnknown(m) -} - -var xxx_messageInfo_Book proto.InternalMessageInfo - -func (m *Book) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *Book) GetRawData() []byte { - if m != nil { - return m.RawData - } - return nil -} - -func init() { - proto.RegisterType((*Request)(nil), "proto3.Request") - proto.RegisterType((*Book)(nil), "proto3.Book") - proto.RegisterEnum("proto3.Request_Flavour", Request_Flavour_name, Request_Flavour_value) -} - -func init() { proto.RegisterFile("proto3/proto3.proto", fileDescriptor_proto3_a752e09251f17e01) } - -var fileDescriptor_proto3_a752e09251f17e01 = []byte{ - // 306 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x3c, 0x90, 0xcf, 0x4e, 0xf2, 0x40, - 0x14, 0xc5, 0x99, 0xfe, 0xf9, 0x80, 0xfb, 0xa1, 0x19, 0xaf, 0x26, 0x8e, 0x1b, 0x33, 0x61, 0xd5, - 0x0d, 0x25, 0xc1, 0x85, 0xc6, 0xb8, 0x11, 0x45, 0x25, 0x91, 0x60, 0x06, 0x89, 0x89, 0x1b, 0x33, - 0x85, 0xb1, 0x92, 0x42, 0x07, 0xcb, 0x54, 0xe2, 0xcb, 0xfa, 0x2c, 0xa6, 0x9d, 0xe2, 0xea, 0x9e, - 0x7b, 0xe7, 0xe4, 0x77, 0x32, 0x07, 0x0e, 0xd7, 0x99, 0x36, 0xfa, 0xac, 0x6b, 0x47, 0x58, 0x0e, - 0xfc, 0x67, 0xb7, 0xf6, 0x0f, 0x81, 0xba, 0x50, 0x9f, 0xb9, 0xda, 0x18, 0x44, 0xf0, 0x52, 0xb9, - 0x52, 0x8c, 0x70, 0x12, 0x34, 0x45, 0xa9, 0x91, 0x82, 0x9b, 0xa8, 0x6f, 0xe6, 0x70, 0x37, 0x70, - 0x45, 0x21, 0xb1, 0x03, 0xbe, 0x91, 0x1b, 0xa3, 0x98, 0xcb, 0x49, 0xb0, 0xdf, 0x3b, 0x0e, 0x2b, - 0x6e, 0x45, 0x09, 0xef, 0x96, 0xf2, 0x4b, 0xe7, 0x99, 0xb0, 0x2e, 0xe4, 0xe0, 0x45, 0x5a, 0x27, - 0xcc, 0xe3, 0x24, 0xf8, 0xdf, 0x6b, 0xed, 0xdc, 0x7d, 0xad, 0x13, 0x51, 0xbe, 0xe0, 0x29, 0x34, - 0xf2, 0x74, 0x2d, 0x67, 0x89, 0x9a, 0x33, 0xbf, 0xc8, 0xe9, 0x3b, 0xb4, 0x26, 0xfe, 0x6e, 0xed, - 0x2b, 0xa8, 0x57, 0x4c, 0x6c, 0x82, 0x3f, 0x79, 0x19, 0x0c, 0x9e, 0x69, 0x0d, 0x1b, 0xe0, 0x4d, - 0xc6, 0x53, 0x41, 0x49, 0x71, 0x9c, 0x8e, 0xae, 0x47, 0x43, 0xea, 0xe0, 0x01, 0xec, 0xdd, 0x8f, - 0x9f, 0x1e, 0x06, 0xe2, 0x71, 0x78, 0x33, 0x1c, 0x4f, 0x27, 0xd4, 0x6d, 0x9f, 0x83, 0x57, 0x64, - 0xe1, 0x11, 0xf8, 0x66, 0x61, 0x96, 0xbb, 0xdf, 0xd9, 0x05, 0x4f, 0xa0, 0x91, 0xc9, 0xed, 0xdb, - 0x5c, 0x1a, 0xc9, 0x1c, 0x4e, 0x82, 0x96, 0xa8, 0x67, 0x72, 0x7b, 0x2b, 0x8d, 0xec, 0x5f, 0xbe, - 0x5e, 0xc4, 0x0b, 0xf3, 0x91, 0x47, 0xe1, 0x4c, 0xaf, 0xba, 0xb1, 0x5e, 0xca, 0x34, 0xb6, 0x1d, - 0x46, 0xf9, 0xbb, 0x15, 0xb3, 0x4e, 0xac, 0xd2, 0x4e, 0xac, 0xbb, 0x46, 0x6d, 0x4c, 0xc1, 0xa8, - 0x3a, 0x8e, 0xaa, 0x76, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xec, 0x71, 0xee, 0xdb, 0x7b, 0x01, - 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto b/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto deleted file mode 100755 index 79954e4..0000000 --- a/examples/github.com/golang/protobuf/protoc-gen-go/testdata/proto3/proto3.proto +++ /dev/null @@ -1,55 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package proto3; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/proto3"; - -message Request { - enum Flavour { - SWEET = 0; - SOUR = 1; - UMAMI = 2; - GOPHERLICIOUS = 3; - } - string name = 1; - repeated int64 key = 2; - Flavour taste = 3; - Book book = 4; - repeated int64 unpacked = 5 [packed=false]; -} - -message Book { - string title = 1; - bytes raw_data = 2; -} diff --git a/examples/github.com/golang/protobuf/ptypes/any.go b/examples/github.com/golang/protobuf/ptypes/any.go deleted file mode 100755 index b2af97f..0000000 --- a/examples/github.com/golang/protobuf/ptypes/any.go +++ /dev/null @@ -1,139 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements functions to marshal proto.Message to/from -// google.protobuf.Any message. - -import ( - "fmt" - "reflect" - "strings" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/any" -) - -const googleApis = "type.googleapis.com/" - -// AnyMessageName returns the name of the message contained in a google.protobuf.Any message. -// -// Note that regular type assertions should be done using the Is -// function. AnyMessageName is provided for less common use cases like filtering a -// sequence of Any messages based on a set of allowed message type names. -func AnyMessageName(any *any.Any) (string, error) { - if any == nil { - return "", fmt.Errorf("message is nil") - } - slash := strings.LastIndex(any.TypeUrl, "/") - if slash < 0 { - return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) - } - return any.TypeUrl[slash+1:], nil -} - -// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. -func MarshalAny(pb proto.Message) (*any.Any, error) { - value, err := proto.Marshal(pb) - if err != nil { - return nil, err - } - return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil -} - -// DynamicAny is a value that can be passed to UnmarshalAny to automatically -// allocate a proto.Message for the type specified in a google.protobuf.Any -// message. The allocated message is stored in the embedded proto.Message. -// -// Example: -// -// var x ptypes.DynamicAny -// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } -// fmt.Printf("unmarshaled message: %v", x.Message) -type DynamicAny struct { - proto.Message -} - -// Empty returns a new proto.Message of the type specified in a -// google.protobuf.Any message. It returns an error if corresponding message -// type isn't linked in. -func Empty(any *any.Any) (proto.Message, error) { - aname, err := AnyMessageName(any) - if err != nil { - return nil, err - } - - t := proto.MessageType(aname) - if t == nil { - return nil, fmt.Errorf("any: message type %q isn't linked in", aname) - } - return reflect.New(t.Elem()).Interface().(proto.Message), nil -} - -// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any -// message and places the decoded result in pb. It returns an error if type of -// contents of Any message does not match type of pb message. -// -// pb can be a proto.Message, or a *DynamicAny. -func UnmarshalAny(any *any.Any, pb proto.Message) error { - if d, ok := pb.(*DynamicAny); ok { - if d.Message == nil { - var err error - d.Message, err = Empty(any) - if err != nil { - return err - } - } - return UnmarshalAny(any, d.Message) - } - - aname, err := AnyMessageName(any) - if err != nil { - return err - } - - mname := proto.MessageName(pb) - if aname != mname { - return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) - } - return proto.Unmarshal(any.Value, pb) -} - -// Is returns true if any value contains a given message type. -func Is(any *any.Any, pb proto.Message) bool { - aname, err := AnyMessageName(any) - if err != nil { - return false - } - - return aname == proto.MessageName(pb) -} diff --git a/examples/github.com/golang/protobuf/ptypes/any/any.pb.go b/examples/github.com/golang/protobuf/ptypes/any/any.pb.go deleted file mode 100755 index f67edc7..0000000 --- a/examples/github.com/golang/protobuf/ptypes/any/any.pb.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/any.proto - -package any // import "github.com/golang/protobuf/ptypes/any" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -type Any struct { - // A URL/resource name whose content describes the type of the - // serialized protocol buffer message. - // - // For URLs which use the scheme `http`, `https`, or no scheme, the - // following restrictions and interpretations apply: - // - // * If no scheme is provided, `https` is assumed. - // * The last segment of the URL's path must represent the fully - // qualified name of the type (as in `path/google.protobuf.Duration`). - // The name should be in a canonical form (e.g., leading "." is - // not accepted). - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"` - // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Any) Reset() { *m = Any{} } -func (m *Any) String() string { return proto.CompactTextString(m) } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { - return fileDescriptor_any_744b9ca530f228db, []int{0} -} -func (*Any) XXX_WellKnownType() string { return "Any" } -func (m *Any) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Any.Unmarshal(m, b) -} -func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Any.Marshal(b, m, deterministic) -} -func (dst *Any) XXX_Merge(src proto.Message) { - xxx_messageInfo_Any.Merge(dst, src) -} -func (m *Any) XXX_Size() int { - return xxx_messageInfo_Any.Size(m) -} -func (m *Any) XXX_DiscardUnknown() { - xxx_messageInfo_Any.DiscardUnknown(m) -} - -var xxx_messageInfo_Any proto.InternalMessageInfo - -func (m *Any) GetTypeUrl() string { - if m != nil { - return m.TypeUrl - } - return "" -} - -func (m *Any) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*Any)(nil), "google.protobuf.Any") -} - -func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_any_744b9ca530f228db) } - -var fileDescriptor_any_744b9ca530f228db = []byte{ - // 185 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, - 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, - 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, - 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, - 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, - 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, - 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, - 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, - 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, - 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/any/any.proto b/examples/github.com/golang/protobuf/ptypes/any/any.proto deleted file mode 100755 index c748667..0000000 --- a/examples/github.com/golang/protobuf/ptypes/any/any.proto +++ /dev/null @@ -1,149 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/any"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name whose content describes the type of the - // serialized protocol buffer message. - // - // For URLs which use the scheme `http`, `https`, or no scheme, the - // following restrictions and interpretations apply: - // - // * If no scheme is provided, `https` is assumed. - // * The last segment of the URL's path must represent the fully - // qualified name of the type (as in `path/google.protobuf.Duration`). - // The name should be in a canonical form (e.g., leading "." is - // not accepted). - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; -} diff --git a/examples/github.com/golang/protobuf/ptypes/any_test.go b/examples/github.com/golang/protobuf/ptypes/any_test.go deleted file mode 100755 index ed675b4..0000000 --- a/examples/github.com/golang/protobuf/ptypes/any_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/golang/protobuf/ptypes/any" -) - -func TestMarshalUnmarshal(t *testing.T) { - orig := &any.Any{Value: []byte("test")} - - packed, err := MarshalAny(orig) - if err != nil { - t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) - } - - unpacked := &any.Any{} - err = UnmarshalAny(packed, unpacked) - if err != nil || !proto.Equal(unpacked, orig) { - t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) - } -} - -func TestIs(t *testing.T) { - a, err := MarshalAny(&pb.FileDescriptorProto{}) - if err != nil { - t.Fatal(err) - } - if Is(a, &pb.DescriptorProto{}) { - t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") - } - if !Is(a, &pb.FileDescriptorProto{}) { - t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") - } -} - -func TestIsDifferentUrlPrefixes(t *testing.T) { - m := &pb.FileDescriptorProto{} - a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} - if !Is(a, m) { - t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) - } -} - -func TestUnmarshalDynamic(t *testing.T) { - want := &pb.FileDescriptorProto{Name: proto.String("foo")} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - var got DynamicAny - if err := UnmarshalAny(a, &got); err != nil { - t.Fatal(err) - } - if !proto.Equal(got.Message, want) { - t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) - } -} - -func TestEmpty(t *testing.T) { - want := &pb.FileDescriptorProto{} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - got, err := Empty(a) - if err != nil { - t.Fatal(err) - } - if !proto.Equal(got, want) { - t.Errorf("unequal empty message, got %q, want %q", got, want) - } - - // that's a valid type_url for a message which shouldn't be linked into this - // test binary. We want an error. - a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask" - if _, err := Empty(a); err == nil { - t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) - } -} diff --git a/examples/github.com/golang/protobuf/ptypes/doc.go b/examples/github.com/golang/protobuf/ptypes/doc.go deleted file mode 100755 index c0d595d..0000000 --- a/examples/github.com/golang/protobuf/ptypes/doc.go +++ /dev/null @@ -1,35 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package ptypes contains code for interacting with well-known types. -*/ -package ptypes diff --git a/examples/github.com/golang/protobuf/ptypes/duration.go b/examples/github.com/golang/protobuf/ptypes/duration.go deleted file mode 100755 index 65cb0f8..0000000 --- a/examples/github.com/golang/protobuf/ptypes/duration.go +++ /dev/null @@ -1,102 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements conversions between google.protobuf.Duration -// and time.Duration. - -import ( - "errors" - "fmt" - "time" - - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - // Range of a durpb.Duration in seconds, as specified in - // google/protobuf/duration.proto. This is about 10,000 years in seconds. - maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) - minSeconds = -maxSeconds -) - -// validateDuration determines whether the durpb.Duration is valid according to the -// definition in google/protobuf/duration.proto. A valid durpb.Duration -// may still be too large to fit into a time.Duration (the range of durpb.Duration -// is about 10,000 years, and the range of time.Duration is about 290). -func validateDuration(d *durpb.Duration) error { - if d == nil { - return errors.New("duration: nil Duration") - } - if d.Seconds < minSeconds || d.Seconds > maxSeconds { - return fmt.Errorf("duration: %v: seconds out of range", d) - } - if d.Nanos <= -1e9 || d.Nanos >= 1e9 { - return fmt.Errorf("duration: %v: nanos out of range", d) - } - // Seconds and Nanos must have the same sign, unless d.Nanos is zero. - if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { - return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) - } - return nil -} - -// Duration converts a durpb.Duration to a time.Duration. Duration -// returns an error if the durpb.Duration is invalid or is too large to be -// represented in a time.Duration. -func Duration(p *durpb.Duration) (time.Duration, error) { - if err := validateDuration(p); err != nil { - return 0, err - } - d := time.Duration(p.Seconds) * time.Second - if int64(d/time.Second) != p.Seconds { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - if p.Nanos != 0 { - d += time.Duration(p.Nanos) - if (d < 0) != (p.Nanos < 0) { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) - } - } - return d, nil -} - -// DurationProto converts a time.Duration to a durpb.Duration. -func DurationProto(d time.Duration) *durpb.Duration { - nanos := d.Nanoseconds() - secs := nanos / 1e9 - nanos -= secs * 1e9 - return &durpb.Duration{ - Seconds: secs, - Nanos: int32(nanos), - } -} diff --git a/examples/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/examples/github.com/golang/protobuf/ptypes/duration/duration.pb.go deleted file mode 100755 index 4d75473..0000000 --- a/examples/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/duration.proto - -package duration // import "github.com/golang/protobuf/ptypes/duration" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_duration_e7d612259e3f0613, []int{0} -} -func (*Duration) XXX_WellKnownType() string { return "Duration" } -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (dst *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(dst, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) -} - -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") -} - -func init() { - proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_duration_e7d612259e3f0613) -} - -var fileDescriptor_duration_e7d612259e3f0613 = []byte{ - // 190 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, - 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, - 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, - 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, - 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, - 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, - 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, - 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, - 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, - 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, - 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/duration/duration.proto b/examples/github.com/golang/protobuf/ptypes/duration/duration.proto deleted file mode 100755 index 975fce4..0000000 --- a/examples/github.com/golang/protobuf/ptypes/duration/duration.proto +++ /dev/null @@ -1,117 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/duration"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DurationProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (durations.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -message Duration { - - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - int64 seconds = 1; - - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - int32 nanos = 2; -} diff --git a/examples/github.com/golang/protobuf/ptypes/duration_test.go b/examples/github.com/golang/protobuf/ptypes/duration_test.go deleted file mode 100755 index e00491a..0000000 --- a/examples/github.com/golang/protobuf/ptypes/duration_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - minGoSeconds = math.MinInt64 / int64(1e9) - maxGoSeconds = math.MaxInt64 / int64(1e9) -) - -var durationTests = []struct { - proto *durpb.Duration - isValid bool - inRange bool - dur time.Duration -}{ - // The zero duration. - {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0}, - // Some ordinary non-zero durations. - {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, - {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, - {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, - {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, - // The largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, - // The smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, - {nil, false, false, 0}, - {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0}, - {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0}, - {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, - {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, - // The largest valid duration. - {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, - // The smallest valid duration. - {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, - // The smallest invalid duration above the valid range. - {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, - // The largest invalid duration below the valid range. - {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, - // One nanosecond past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, - // One nanosecond past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, - // One second past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, - // One second past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, -} - -func TestValidateDuration(t *testing.T) { - for _, test := range durationTests { - err := validateDuration(test.proto) - gotValid := (err == nil) - if gotValid != test.isValid { - t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) - } - } -} - -func TestDuration(t *testing.T) { - for _, test := range durationTests { - got, err := Duration(test.proto) - gotOK := (err == nil) - wantOK := test.isValid && test.inRange - if gotOK != wantOK { - t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK) - } - if err == nil && got != test.dur { - t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur) - } - } -} - -func TestDurationProto(t *testing.T) { - for _, test := range durationTests { - if test.isValid && test.inRange { - got := DurationProto(test.dur) - if !proto.Equal(got, test.proto) { - t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) - } - } - } -} diff --git a/examples/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/examples/github.com/golang/protobuf/ptypes/empty/empty.pb.go deleted file mode 100755 index a69b403..0000000 --- a/examples/github.com/golang/protobuf/ptypes/empty/empty.pb.go +++ /dev/null @@ -1,79 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/empty.proto - -package empty // import "github.com/golang/protobuf/ptypes/empty" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// A generic empty message that you can re-use to avoid defining duplicated -// empty messages in your APIs. A typical example is to use it as the request -// or the response type of an API method. For instance: -// -// service Foo { -// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); -// } -// -// The JSON representation for `Empty` is empty JSON object `{}`. -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_empty_39e6d6db0632e5b2, []int{0} -} -func (*Empty) XXX_WellKnownType() string { return "Empty" } -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Empty)(nil), "google.protobuf.Empty") -} - -func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor_empty_39e6d6db0632e5b2) } - -var fileDescriptor_empty_39e6d6db0632e5b2 = []byte{ - // 148 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28, - 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57, - 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36, - 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, - 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c, - 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10, - 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, - 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6, - 0xb7, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/empty/empty.proto b/examples/github.com/golang/protobuf/ptypes/empty/empty.proto deleted file mode 100755 index 03cacd2..0000000 --- a/examples/github.com/golang/protobuf/ptypes/empty/empty.proto +++ /dev/null @@ -1,52 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/empty"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "EmptyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; -option cc_enable_arenas = true; - -// A generic empty message that you can re-use to avoid defining duplicated -// empty messages in your APIs. A typical example is to use it as the request -// or the response type of an API method. For instance: -// -// service Foo { -// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); -// } -// -// The JSON representation for `Empty` is empty JSON object `{}`. -message Empty {} diff --git a/examples/github.com/golang/protobuf/ptypes/struct/struct.pb.go b/examples/github.com/golang/protobuf/ptypes/struct/struct.pb.go deleted file mode 100755 index 442c0e0..0000000 --- a/examples/github.com/golang/protobuf/ptypes/struct/struct.pb.go +++ /dev/null @@ -1,440 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/struct.proto - -package structpb // import "github.com/golang/protobuf/ptypes/struct" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// `NullValue` is a singleton enumeration to represent the null value for the -// `Value` type union. -// -// The JSON representation for `NullValue` is JSON `null`. -type NullValue int32 - -const ( - // Null value. - NullValue_NULL_VALUE NullValue = 0 -) - -var NullValue_name = map[int32]string{ - 0: "NULL_VALUE", -} -var NullValue_value = map[string]int32{ - "NULL_VALUE": 0, -} - -func (x NullValue) String() string { - return proto.EnumName(NullValue_name, int32(x)) -} -func (NullValue) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_struct_3a5a94e0c7801b27, []int{0} -} -func (NullValue) XXX_WellKnownType() string { return "NullValue" } - -// `Struct` represents a structured data value, consisting of fields -// which map to dynamically typed values. In some languages, `Struct` -// might be supported by a native representation. For example, in -// scripting languages like JS a struct is represented as an -// object. The details of that representation are described together -// with the proto support for the language. -// -// The JSON representation for `Struct` is JSON object. -type Struct struct { - // Unordered map of dynamically typed values. - Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Struct) Reset() { *m = Struct{} } -func (m *Struct) String() string { return proto.CompactTextString(m) } -func (*Struct) ProtoMessage() {} -func (*Struct) Descriptor() ([]byte, []int) { - return fileDescriptor_struct_3a5a94e0c7801b27, []int{0} -} -func (*Struct) XXX_WellKnownType() string { return "Struct" } -func (m *Struct) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Struct.Unmarshal(m, b) -} -func (m *Struct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Struct.Marshal(b, m, deterministic) -} -func (dst *Struct) XXX_Merge(src proto.Message) { - xxx_messageInfo_Struct.Merge(dst, src) -} -func (m *Struct) XXX_Size() int { - return xxx_messageInfo_Struct.Size(m) -} -func (m *Struct) XXX_DiscardUnknown() { - xxx_messageInfo_Struct.DiscardUnknown(m) -} - -var xxx_messageInfo_Struct proto.InternalMessageInfo - -func (m *Struct) GetFields() map[string]*Value { - if m != nil { - return m.Fields - } - return nil -} - -// `Value` represents a dynamically typed value which can be either -// null, a number, a string, a boolean, a recursive struct value, or a -// list of values. A producer of value is expected to set one of that -// variants, absence of any variant indicates an error. -// -// The JSON representation for `Value` is JSON value. -type Value struct { - // The kind of value. - // - // Types that are valid to be assigned to Kind: - // *Value_NullValue - // *Value_NumberValue - // *Value_StringValue - // *Value_BoolValue - // *Value_StructValue - // *Value_ListValue - Kind isValue_Kind `protobuf_oneof:"kind"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Value) Reset() { *m = Value{} } -func (m *Value) String() string { return proto.CompactTextString(m) } -func (*Value) ProtoMessage() {} -func (*Value) Descriptor() ([]byte, []int) { - return fileDescriptor_struct_3a5a94e0c7801b27, []int{1} -} -func (*Value) XXX_WellKnownType() string { return "Value" } -func (m *Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Value.Unmarshal(m, b) -} -func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Value.Marshal(b, m, deterministic) -} -func (dst *Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_Value.Merge(dst, src) -} -func (m *Value) XXX_Size() int { - return xxx_messageInfo_Value.Size(m) -} -func (m *Value) XXX_DiscardUnknown() { - xxx_messageInfo_Value.DiscardUnknown(m) -} - -var xxx_messageInfo_Value proto.InternalMessageInfo - -type isValue_Kind interface { - isValue_Kind() -} - -type Value_NullValue struct { - NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"` -} -type Value_NumberValue struct { - NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"` -} -type Value_StringValue struct { - StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"` -} -type Value_BoolValue struct { - BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"` -} -type Value_StructValue struct { - StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"` -} -type Value_ListValue struct { - ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"` -} - -func (*Value_NullValue) isValue_Kind() {} -func (*Value_NumberValue) isValue_Kind() {} -func (*Value_StringValue) isValue_Kind() {} -func (*Value_BoolValue) isValue_Kind() {} -func (*Value_StructValue) isValue_Kind() {} -func (*Value_ListValue) isValue_Kind() {} - -func (m *Value) GetKind() isValue_Kind { - if m != nil { - return m.Kind - } - return nil -} - -func (m *Value) GetNullValue() NullValue { - if x, ok := m.GetKind().(*Value_NullValue); ok { - return x.NullValue - } - return NullValue_NULL_VALUE -} - -func (m *Value) GetNumberValue() float64 { - if x, ok := m.GetKind().(*Value_NumberValue); ok { - return x.NumberValue - } - return 0 -} - -func (m *Value) GetStringValue() string { - if x, ok := m.GetKind().(*Value_StringValue); ok { - return x.StringValue - } - return "" -} - -func (m *Value) GetBoolValue() bool { - if x, ok := m.GetKind().(*Value_BoolValue); ok { - return x.BoolValue - } - return false -} - -func (m *Value) GetStructValue() *Struct { - if x, ok := m.GetKind().(*Value_StructValue); ok { - return x.StructValue - } - return nil -} - -func (m *Value) GetListValue() *ListValue { - if x, ok := m.GetKind().(*Value_ListValue); ok { - return x.ListValue - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{ - (*Value_NullValue)(nil), - (*Value_NumberValue)(nil), - (*Value_StringValue)(nil), - (*Value_BoolValue)(nil), - (*Value_StructValue)(nil), - (*Value_ListValue)(nil), - } -} - -func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Value) - // kind - switch x := m.Kind.(type) { - case *Value_NullValue: - b.EncodeVarint(1<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.NullValue)) - case *Value_NumberValue: - b.EncodeVarint(2<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.NumberValue)) - case *Value_StringValue: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.StringValue) - case *Value_BoolValue: - t := uint64(0) - if x.BoolValue { - t = 1 - } - b.EncodeVarint(4<<3 | proto.WireVarint) - b.EncodeVarint(t) - case *Value_StructValue: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.StructValue); err != nil { - return err - } - case *Value_ListValue: - b.EncodeVarint(6<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ListValue); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("Value.Kind has unexpected type %T", x) - } - return nil -} - -func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Value) - switch tag { - case 1: // kind.null_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Kind = &Value_NullValue{NullValue(x)} - return true, err - case 2: // kind.number_value - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Kind = &Value_NumberValue{math.Float64frombits(x)} - return true, err - case 3: // kind.string_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Kind = &Value_StringValue{x} - return true, err - case 4: // kind.bool_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Kind = &Value_BoolValue{x != 0} - return true, err - case 5: // kind.struct_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Struct) - err := b.DecodeMessage(msg) - m.Kind = &Value_StructValue{msg} - return true, err - case 6: // kind.list_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ListValue) - err := b.DecodeMessage(msg) - m.Kind = &Value_ListValue{msg} - return true, err - default: - return false, nil - } -} - -func _Value_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Value) - // kind - switch x := m.Kind.(type) { - case *Value_NullValue: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.NullValue)) - case *Value_NumberValue: - n += 1 // tag and wire - n += 8 - case *Value_StringValue: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.StringValue))) - n += len(x.StringValue) - case *Value_BoolValue: - n += 1 // tag and wire - n += 1 - case *Value_StructValue: - s := proto.Size(x.StructValue) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Value_ListValue: - s := proto.Size(x.ListValue) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// `ListValue` is a wrapper around a repeated field of values. -// -// The JSON representation for `ListValue` is JSON array. -type ListValue struct { - // Repeated field of dynamically typed values. - Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListValue) Reset() { *m = ListValue{} } -func (m *ListValue) String() string { return proto.CompactTextString(m) } -func (*ListValue) ProtoMessage() {} -func (*ListValue) Descriptor() ([]byte, []int) { - return fileDescriptor_struct_3a5a94e0c7801b27, []int{2} -} -func (*ListValue) XXX_WellKnownType() string { return "ListValue" } -func (m *ListValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListValue.Unmarshal(m, b) -} -func (m *ListValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListValue.Marshal(b, m, deterministic) -} -func (dst *ListValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListValue.Merge(dst, src) -} -func (m *ListValue) XXX_Size() int { - return xxx_messageInfo_ListValue.Size(m) -} -func (m *ListValue) XXX_DiscardUnknown() { - xxx_messageInfo_ListValue.DiscardUnknown(m) -} - -var xxx_messageInfo_ListValue proto.InternalMessageInfo - -func (m *ListValue) GetValues() []*Value { - if m != nil { - return m.Values - } - return nil -} - -func init() { - proto.RegisterType((*Struct)(nil), "google.protobuf.Struct") - proto.RegisterMapType((map[string]*Value)(nil), "google.protobuf.Struct.FieldsEntry") - proto.RegisterType((*Value)(nil), "google.protobuf.Value") - proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue") - proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value) -} - -func init() { - proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor_struct_3a5a94e0c7801b27) -} - -var fileDescriptor_struct_3a5a94e0c7801b27 = []byte{ - // 417 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40, - 0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09, - 0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94, - 0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa, - 0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff, - 0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc, - 0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15, - 0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d, - 0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce, - 0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39, - 0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab, - 0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84, - 0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48, - 0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f, - 0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59, - 0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a, - 0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64, - 0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92, - 0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25, - 0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37, - 0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6, - 0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4, - 0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda, - 0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9, - 0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53, - 0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00, - 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/struct/struct.proto b/examples/github.com/golang/protobuf/ptypes/struct/struct.proto deleted file mode 100755 index 7d7808e..0000000 --- a/examples/github.com/golang/protobuf/ptypes/struct/struct.proto +++ /dev/null @@ -1,96 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/struct;structpb"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "StructProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - - -// `Struct` represents a structured data value, consisting of fields -// which map to dynamically typed values. In some languages, `Struct` -// might be supported by a native representation. For example, in -// scripting languages like JS a struct is represented as an -// object. The details of that representation are described together -// with the proto support for the language. -// -// The JSON representation for `Struct` is JSON object. -message Struct { - // Unordered map of dynamically typed values. - map fields = 1; -} - -// `Value` represents a dynamically typed value which can be either -// null, a number, a string, a boolean, a recursive struct value, or a -// list of values. A producer of value is expected to set one of that -// variants, absence of any variant indicates an error. -// -// The JSON representation for `Value` is JSON value. -message Value { - // The kind of value. - oneof kind { - // Represents a null value. - NullValue null_value = 1; - // Represents a double value. - double number_value = 2; - // Represents a string value. - string string_value = 3; - // Represents a boolean value. - bool bool_value = 4; - // Represents a structured value. - Struct struct_value = 5; - // Represents a repeated `Value`. - ListValue list_value = 6; - } -} - -// `NullValue` is a singleton enumeration to represent the null value for the -// `Value` type union. -// -// The JSON representation for `NullValue` is JSON `null`. -enum NullValue { - // Null value. - NULL_VALUE = 0; -} - -// `ListValue` is a wrapper around a repeated field of values. -// -// The JSON representation for `ListValue` is JSON array. -message ListValue { - // Repeated field of dynamically typed values. - repeated Value values = 1; -} diff --git a/examples/github.com/golang/protobuf/ptypes/timestamp.go b/examples/github.com/golang/protobuf/ptypes/timestamp.go deleted file mode 100755 index 47f10db..0000000 --- a/examples/github.com/golang/protobuf/ptypes/timestamp.go +++ /dev/null @@ -1,134 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -// This file implements operations on google.protobuf.Timestamp. - -import ( - "errors" - "fmt" - "time" - - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -const ( - // Seconds field of the earliest valid Timestamp. - // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - minValidSeconds = -62135596800 - // Seconds field just after the latest valid Timestamp. - // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). - maxValidSeconds = 253402300800 -) - -// validateTimestamp determines whether a Timestamp is valid. -// A valid timestamp represents a time in the range -// [0001-01-01, 10000-01-01) and has a Nanos field -// in the range [0, 1e9). -// -// If the Timestamp is valid, validateTimestamp returns nil. -// Otherwise, it returns an error that describes -// the problem. -// -// Every valid Timestamp can be represented by a time.Time, but the converse is not true. -func validateTimestamp(ts *tspb.Timestamp) error { - if ts == nil { - return errors.New("timestamp: nil Timestamp") - } - if ts.Seconds < minValidSeconds { - return fmt.Errorf("timestamp: %v before 0001-01-01", ts) - } - if ts.Seconds >= maxValidSeconds { - return fmt.Errorf("timestamp: %v after 10000-01-01", ts) - } - if ts.Nanos < 0 || ts.Nanos >= 1e9 { - return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) - } - return nil -} - -// Timestamp converts a google.protobuf.Timestamp proto to a time.Time. -// It returns an error if the argument is invalid. -// -// Unlike most Go functions, if Timestamp returns an error, the first return value -// is not the zero time.Time. Instead, it is the value obtained from the -// time.Unix function when passed the contents of the Timestamp, in the UTC -// locale. This may or may not be a meaningful time; many invalid Timestamps -// do map to valid time.Times. -// -// A nil Timestamp returns an error. The first return value in that case is -// undefined. -func Timestamp(ts *tspb.Timestamp) (time.Time, error) { - // Don't return the zero value on error, because corresponds to a valid - // timestamp. Instead return whatever time.Unix gives us. - var t time.Time - if ts == nil { - t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp - } else { - t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() - } - return t, validateTimestamp(ts) -} - -// TimestampNow returns a google.protobuf.Timestamp for the current time. -func TimestampNow() *tspb.Timestamp { - ts, err := TimestampProto(time.Now()) - if err != nil { - panic("ptypes: time.Now() out of Timestamp range") - } - return ts -} - -// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. -// It returns an error if the resulting Timestamp is invalid. -func TimestampProto(t time.Time) (*tspb.Timestamp, error) { - seconds := t.Unix() - nanos := int32(t.Sub(time.Unix(seconds, 0))) - ts := &tspb.Timestamp{ - Seconds: seconds, - Nanos: nanos, - } - if err := validateTimestamp(ts); err != nil { - return nil, err - } - return ts, nil -} - -// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid -// Timestamps, it returns an error message in parentheses. -func TimestampString(ts *tspb.Timestamp) string { - t, err := Timestamp(ts) - if err != nil { - return fmt.Sprintf("(%v)", err) - } - return t.Format(time.RFC3339Nano) -} diff --git a/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go deleted file mode 100755 index e9c2222..0000000 --- a/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/timestamp.proto - -package timestamp // import "github.com/golang/protobuf/ptypes/timestamp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required, though only UTC (as indicated by "Z") is presently supported. -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--) -// to obtain a formatter capable of generating timestamps in this format. -// -// -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_timestamp_b826e8e5fba671a8, []int{0} -} -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (dst *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(dst, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) -} - -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 -} - -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos - } - return 0 -} - -func init() { - proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") -} - -func init() { - proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_timestamp_b826e8e5fba671a8) -} - -var fileDescriptor_timestamp_b826e8e5fba671a8 = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, - 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, - 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, - 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, - 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, - 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, - 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, - 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, - 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, - 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto deleted file mode 100755 index 06750ab..0000000 --- a/examples/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto +++ /dev/null @@ -1,133 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/timestamp"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TimestampProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Timestamp represents a point in time independent of any time zone -// or calendar, represented as seconds and fractions of seconds at -// nanosecond resolution in UTC Epoch time. It is encoded using the -// Proleptic Gregorian Calendar which extends the Gregorian calendar -// backwards to year one. It is encoded assuming all minutes are 60 -// seconds long, i.e. leap seconds are "smeared" so that no leap second -// table is needed for interpretation. Range is from -// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. -// By restricting to that range, we ensure that we can convert to -// and from RFC 3339 date strings. -// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required, though only UTC (as indicated by "Z") is presently supported. -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) -// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one -// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--) -// to obtain a formatter capable of generating timestamps in this format. -// -// -message Timestamp { - - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/examples/github.com/golang/protobuf/ptypes/timestamp_test.go b/examples/github.com/golang/protobuf/ptypes/timestamp_test.go deleted file mode 100755 index 6e3c969..0000000 --- a/examples/github.com/golang/protobuf/ptypes/timestamp_test.go +++ /dev/null @@ -1,153 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -var tests = []struct { - ts *tspb.Timestamp - valid bool - t time.Time -}{ - // The timestamp representing the Unix epoch date. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, - // The smallest representable timestamp. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, - time.Unix(math.MinInt64, math.MinInt32).UTC()}, - // The smallest representable timestamp with non-negative nanos. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, - // The earliest valid timestamp. - {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, - //"0001-01-01T00:00:00Z"}, - // The largest representable timestamp. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, - time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, - // The largest representable timestamp with nanos in range. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, - time.Unix(math.MaxInt64, 1e9-1).UTC()}, - // The largest valid timestamp. - {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, - time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, - // The smallest invalid timestamp that is larger than the valid range. - {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, - // A date before the epoch. - {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, - // A date after the epoch. - {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, - // A date after the epoch, in the middle of the day. - {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true, - time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, -} - -func TestValidateTimestamp(t *testing.T) { - for _, s := range tests { - got := validateTimestamp(s.ts) - if (got == nil) != s.valid { - t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) - } - } -} - -func TestTimestamp(t *testing.T) { - for _, s := range tests { - got, err := Timestamp(s.ts) - if (err == nil) != s.valid { - t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid) - } else if s.valid && got != s.t { - t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t) - } - } - // Special case: a nil Timestamp is an error, but returns the 0 Unix time. - got, err := Timestamp(nil) - want := time.Unix(0, 0).UTC() - if got != want { - t.Errorf("Timestamp(nil) = %v, want %v", got, want) - } - if err == nil { - t.Errorf("Timestamp(nil) error = nil, expected error") - } -} - -func TestTimestampProto(t *testing.T) { - for _, s := range tests { - got, err := TimestampProto(s.t) - if (err == nil) != s.valid { - t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) - } else if s.valid && !proto.Equal(got, s.ts) { - t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) - } - } - // No corresponding special case here: no time.Time results in a nil Timestamp. -} - -func TestTimestampString(t *testing.T) { - for _, test := range []struct { - ts *tspb.Timestamp - want string - }{ - // Not much testing needed because presumably time.Format is - // well-tested. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, - {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"}, - } { - got := TimestampString(test.ts) - if got != test.want { - t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) - } - } -} - -func utcDate(year, month, day int) time.Time { - return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) -} - -func TestTimestampNow(t *testing.T) { - // Bracket the expected time. - before := time.Now() - ts := TimestampNow() - after := time.Now() - - tm, err := Timestamp(ts) - if err != nil { - t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) - } - if tm.Before(before) || tm.After(after) { - t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) - } -} diff --git a/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go b/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go deleted file mode 100755 index d1fc4d0..0000000 --- a/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go +++ /dev/null @@ -1,443 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/wrappers.proto - -package wrappers // import "github.com/golang/protobuf/ptypes/wrappers" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Wrapper message for `double`. -// -// The JSON representation for `DoubleValue` is JSON number. -type DoubleValue struct { - // The double value. - Value float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DoubleValue) Reset() { *m = DoubleValue{} } -func (m *DoubleValue) String() string { return proto.CompactTextString(m) } -func (*DoubleValue) ProtoMessage() {} -func (*DoubleValue) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{0} -} -func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" } -func (m *DoubleValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DoubleValue.Unmarshal(m, b) -} -func (m *DoubleValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DoubleValue.Marshal(b, m, deterministic) -} -func (dst *DoubleValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_DoubleValue.Merge(dst, src) -} -func (m *DoubleValue) XXX_Size() int { - return xxx_messageInfo_DoubleValue.Size(m) -} -func (m *DoubleValue) XXX_DiscardUnknown() { - xxx_messageInfo_DoubleValue.DiscardUnknown(m) -} - -var xxx_messageInfo_DoubleValue proto.InternalMessageInfo - -func (m *DoubleValue) GetValue() float64 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `float`. -// -// The JSON representation for `FloatValue` is JSON number. -type FloatValue struct { - // The float value. - Value float32 `protobuf:"fixed32,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FloatValue) Reset() { *m = FloatValue{} } -func (m *FloatValue) String() string { return proto.CompactTextString(m) } -func (*FloatValue) ProtoMessage() {} -func (*FloatValue) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{1} -} -func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" } -func (m *FloatValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FloatValue.Unmarshal(m, b) -} -func (m *FloatValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FloatValue.Marshal(b, m, deterministic) -} -func (dst *FloatValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_FloatValue.Merge(dst, src) -} -func (m *FloatValue) XXX_Size() int { - return xxx_messageInfo_FloatValue.Size(m) -} -func (m *FloatValue) XXX_DiscardUnknown() { - xxx_messageInfo_FloatValue.DiscardUnknown(m) -} - -var xxx_messageInfo_FloatValue proto.InternalMessageInfo - -func (m *FloatValue) GetValue() float32 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `int64`. -// -// The JSON representation for `Int64Value` is JSON string. -type Int64Value struct { - // The int64 value. - Value int64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Int64Value) Reset() { *m = Int64Value{} } -func (m *Int64Value) String() string { return proto.CompactTextString(m) } -func (*Int64Value) ProtoMessage() {} -func (*Int64Value) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{2} -} -func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" } -func (m *Int64Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Int64Value.Unmarshal(m, b) -} -func (m *Int64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Int64Value.Marshal(b, m, deterministic) -} -func (dst *Int64Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_Int64Value.Merge(dst, src) -} -func (m *Int64Value) XXX_Size() int { - return xxx_messageInfo_Int64Value.Size(m) -} -func (m *Int64Value) XXX_DiscardUnknown() { - xxx_messageInfo_Int64Value.DiscardUnknown(m) -} - -var xxx_messageInfo_Int64Value proto.InternalMessageInfo - -func (m *Int64Value) GetValue() int64 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `uint64`. -// -// The JSON representation for `UInt64Value` is JSON string. -type UInt64Value struct { - // The uint64 value. - Value uint64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UInt64Value) Reset() { *m = UInt64Value{} } -func (m *UInt64Value) String() string { return proto.CompactTextString(m) } -func (*UInt64Value) ProtoMessage() {} -func (*UInt64Value) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{3} -} -func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" } -func (m *UInt64Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UInt64Value.Unmarshal(m, b) -} -func (m *UInt64Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UInt64Value.Marshal(b, m, deterministic) -} -func (dst *UInt64Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_UInt64Value.Merge(dst, src) -} -func (m *UInt64Value) XXX_Size() int { - return xxx_messageInfo_UInt64Value.Size(m) -} -func (m *UInt64Value) XXX_DiscardUnknown() { - xxx_messageInfo_UInt64Value.DiscardUnknown(m) -} - -var xxx_messageInfo_UInt64Value proto.InternalMessageInfo - -func (m *UInt64Value) GetValue() uint64 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `int32`. -// -// The JSON representation for `Int32Value` is JSON number. -type Int32Value struct { - // The int32 value. - Value int32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Int32Value) Reset() { *m = Int32Value{} } -func (m *Int32Value) String() string { return proto.CompactTextString(m) } -func (*Int32Value) ProtoMessage() {} -func (*Int32Value) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{4} -} -func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" } -func (m *Int32Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Int32Value.Unmarshal(m, b) -} -func (m *Int32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Int32Value.Marshal(b, m, deterministic) -} -func (dst *Int32Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_Int32Value.Merge(dst, src) -} -func (m *Int32Value) XXX_Size() int { - return xxx_messageInfo_Int32Value.Size(m) -} -func (m *Int32Value) XXX_DiscardUnknown() { - xxx_messageInfo_Int32Value.DiscardUnknown(m) -} - -var xxx_messageInfo_Int32Value proto.InternalMessageInfo - -func (m *Int32Value) GetValue() int32 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `uint32`. -// -// The JSON representation for `UInt32Value` is JSON number. -type UInt32Value struct { - // The uint32 value. - Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UInt32Value) Reset() { *m = UInt32Value{} } -func (m *UInt32Value) String() string { return proto.CompactTextString(m) } -func (*UInt32Value) ProtoMessage() {} -func (*UInt32Value) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{5} -} -func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" } -func (m *UInt32Value) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UInt32Value.Unmarshal(m, b) -} -func (m *UInt32Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UInt32Value.Marshal(b, m, deterministic) -} -func (dst *UInt32Value) XXX_Merge(src proto.Message) { - xxx_messageInfo_UInt32Value.Merge(dst, src) -} -func (m *UInt32Value) XXX_Size() int { - return xxx_messageInfo_UInt32Value.Size(m) -} -func (m *UInt32Value) XXX_DiscardUnknown() { - xxx_messageInfo_UInt32Value.DiscardUnknown(m) -} - -var xxx_messageInfo_UInt32Value proto.InternalMessageInfo - -func (m *UInt32Value) GetValue() uint32 { - if m != nil { - return m.Value - } - return 0 -} - -// Wrapper message for `bool`. -// -// The JSON representation for `BoolValue` is JSON `true` and `false`. -type BoolValue struct { - // The bool value. - Value bool `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BoolValue) Reset() { *m = BoolValue{} } -func (m *BoolValue) String() string { return proto.CompactTextString(m) } -func (*BoolValue) ProtoMessage() {} -func (*BoolValue) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{6} -} -func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" } -func (m *BoolValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BoolValue.Unmarshal(m, b) -} -func (m *BoolValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BoolValue.Marshal(b, m, deterministic) -} -func (dst *BoolValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_BoolValue.Merge(dst, src) -} -func (m *BoolValue) XXX_Size() int { - return xxx_messageInfo_BoolValue.Size(m) -} -func (m *BoolValue) XXX_DiscardUnknown() { - xxx_messageInfo_BoolValue.DiscardUnknown(m) -} - -var xxx_messageInfo_BoolValue proto.InternalMessageInfo - -func (m *BoolValue) GetValue() bool { - if m != nil { - return m.Value - } - return false -} - -// Wrapper message for `string`. -// -// The JSON representation for `StringValue` is JSON string. -type StringValue struct { - // The string value. - Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StringValue) Reset() { *m = StringValue{} } -func (m *StringValue) String() string { return proto.CompactTextString(m) } -func (*StringValue) ProtoMessage() {} -func (*StringValue) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{7} -} -func (*StringValue) XXX_WellKnownType() string { return "StringValue" } -func (m *StringValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StringValue.Unmarshal(m, b) -} -func (m *StringValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StringValue.Marshal(b, m, deterministic) -} -func (dst *StringValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_StringValue.Merge(dst, src) -} -func (m *StringValue) XXX_Size() int { - return xxx_messageInfo_StringValue.Size(m) -} -func (m *StringValue) XXX_DiscardUnknown() { - xxx_messageInfo_StringValue.DiscardUnknown(m) -} - -var xxx_messageInfo_StringValue proto.InternalMessageInfo - -func (m *StringValue) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -// Wrapper message for `bytes`. -// -// The JSON representation for `BytesValue` is JSON string. -type BytesValue struct { - // The bytes value. - Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BytesValue) Reset() { *m = BytesValue{} } -func (m *BytesValue) String() string { return proto.CompactTextString(m) } -func (*BytesValue) ProtoMessage() {} -func (*BytesValue) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_16c7c35c009f3253, []int{8} -} -func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" } -func (m *BytesValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BytesValue.Unmarshal(m, b) -} -func (m *BytesValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BytesValue.Marshal(b, m, deterministic) -} -func (dst *BytesValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_BytesValue.Merge(dst, src) -} -func (m *BytesValue) XXX_Size() int { - return xxx_messageInfo_BytesValue.Size(m) -} -func (m *BytesValue) XXX_DiscardUnknown() { - xxx_messageInfo_BytesValue.DiscardUnknown(m) -} - -var xxx_messageInfo_BytesValue proto.InternalMessageInfo - -func (m *BytesValue) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue") - proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue") - proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value") - proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value") - proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value") - proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value") - proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue") - proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue") - proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue") -} - -func init() { - proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor_wrappers_16c7c35c009f3253) -} - -var fileDescriptor_wrappers_16c7c35c009f3253 = []byte{ - // 259 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c, - 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca, - 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c, - 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5, - 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13, - 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8, - 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca, - 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a, - 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x0d, - 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x5a, 0xe8, 0x3a, 0xf1, 0x86, 0x43, 0x83, 0x3f, 0x00, 0x24, - 0x12, 0xc0, 0x18, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, - 0x9e, 0x9f, 0x93, 0x98, 0x97, 0x8e, 0x88, 0xaa, 0x82, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x78, 0x8c, - 0xfd, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, - 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, - 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x6c, 0xb9, 0xb8, 0xfe, - 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto b/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto deleted file mode 100755 index 0194763..0000000 --- a/examples/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto +++ /dev/null @@ -1,118 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Wrappers for primitive (non-message) types. These types are useful -// for embedding primitives in the `google.protobuf.Any` type and for places -// where we need to distinguish between the absence of a primitive -// typed field and its default value. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/wrappers"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "WrappersProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// Wrapper message for `double`. -// -// The JSON representation for `DoubleValue` is JSON number. -message DoubleValue { - // The double value. - double value = 1; -} - -// Wrapper message for `float`. -// -// The JSON representation for `FloatValue` is JSON number. -message FloatValue { - // The float value. - float value = 1; -} - -// Wrapper message for `int64`. -// -// The JSON representation for `Int64Value` is JSON string. -message Int64Value { - // The int64 value. - int64 value = 1; -} - -// Wrapper message for `uint64`. -// -// The JSON representation for `UInt64Value` is JSON string. -message UInt64Value { - // The uint64 value. - uint64 value = 1; -} - -// Wrapper message for `int32`. -// -// The JSON representation for `Int32Value` is JSON number. -message Int32Value { - // The int32 value. - int32 value = 1; -} - -// Wrapper message for `uint32`. -// -// The JSON representation for `UInt32Value` is JSON number. -message UInt32Value { - // The uint32 value. - uint32 value = 1; -} - -// Wrapper message for `bool`. -// -// The JSON representation for `BoolValue` is JSON `true` and `false`. -message BoolValue { - // The bool value. - bool value = 1; -} - -// Wrapper message for `string`. -// -// The JSON representation for `StringValue` is JSON string. -message StringValue { - // The string value. - string value = 1; -} - -// Wrapper message for `bytes`. -// -// The JSON representation for `BytesValue` is JSON string. -message BytesValue { - // The bytes value. - bytes value = 1; -} diff --git a/examples/github.com/golang/protobuf/regenerate.sh b/examples/github.com/golang/protobuf/regenerate.sh deleted file mode 100755 index dc7e2d1..0000000 --- a/examples/github.com/golang/protobuf/regenerate.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/bash - -set -e - -# Install the working tree's protoc-gen-gen in a tempdir. -tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) -trap 'rm -rf $tmpdir' EXIT -mkdir -p $tmpdir/bin -PATH=$tmpdir/bin:$PATH -GOBIN=$tmpdir/bin go install ./protoc-gen-go - -# Public imports require at least Go 1.9. -supportTypeAliases="" -if go list -f '{{context.ReleaseTags}}' runtime | grep -q go1.9; then - supportTypeAliases=1 -fi - -# Generate various test protos. -PROTO_DIRS=( - conformance/internal/conformance_proto - jsonpb/jsonpb_test_proto - proto - protoc-gen-go/testdata -) -for dir in ${PROTO_DIRS[@]}; do - for p in `find $dir -name "*.proto"`; do - if [[ $p == */import_public/* && ! $supportTypeAliases ]]; then - echo "# $p (skipped)" - continue; - fi - echo "# $p" - protoc -I$dir --go_out=plugins=grpc,paths=source_relative:$dir $p - done -done - -# Deriving the location of the source protos from the path to the -# protoc binary may be a bit odd, but this is what protoc itself does. -PROTO_INCLUDE=$(dirname $(dirname $(which protoc)))/include - -# Well-known types. -WKT_PROTOS=(any duration empty struct timestamp wrappers) -for p in ${WKT_PROTOS[@]}; do - echo "# google/protobuf/$p.proto" - protoc --go_out=paths=source_relative:$tmpdir google/protobuf/$p.proto - cp $tmpdir/google/protobuf/$p.pb.go ptypes/$p - cp $PROTO_INCLUDE/google/protobuf/$p.proto ptypes/$p -done - -# descriptor.proto. -echo "# google/protobuf/descriptor.proto" -protoc --go_out=paths=source_relative:$tmpdir google/protobuf/descriptor.proto -cp $tmpdir/google/protobuf/descriptor.pb.go protoc-gen-go/descriptor -cp $PROTO_INCLUDE/google/protobuf/descriptor.proto protoc-gen-go/descriptor diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore b/examples/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore deleted file mode 100755 index c198e6a..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore +++ /dev/null @@ -1,202 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -### Windows template -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk -### Kate template -# Swap Files # -.*.kate-swp -.swp.* -### SublimeText template -# cache files for sublime text -*.tmlanguage.cache -*.tmPreferences.cache -*.stTheme.cache - -# workspace files are user-specific -*.sublime-workspace - -# project files should be checked into the repository, unless a significant -# proportion of contributors will probably not be using SublimeText -# *.sublime-project - -# sftp configuration file -sftp-config.json -### Linux template -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea -.idea/tasks.xml -.idea/dictionaries -.idea/vcs.xml -.idea/jsLibraryMappings.xml - -# Sensitive or high-churn files: -.idea/dataSources.ids -.idea/dataSources.xml -.idea/dataSources.local.xml -.idea/sqlDataSources.xml -.idea/dynamic.xml -.idea/uiDesigner.xml - -# Gradle: -.idea/gradle.xml -.idea/libraries - -# Mongo Explorer plugin: -.idea/mongoSettings.xml - -## File-based project format: -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties -### Xcode template -# Xcode -# -# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore - -## Build generated -build/ -DerivedData/ - -## Various settings -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint -### Eclipse template - -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.settings/ -.loadpath -.recommenders - -# Eclipse Core -.project - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# PyDev specific (Python IDE for Eclipse) -*.pydevproject - -# CDT-specific (C/C++ Development Tooling) -.cproject - -# JDT-specific (Eclipse Java Development Tools) -.classpath - -# Java annotation processor (APT) -.factorypath - -# PDT-specific (PHP Development Tools) -.buildpath - -# sbteclipse plugin -.target - -# Tern plugin -.tern-project - -# TeXlipse plugin -.texlipse - -# STS (Spring Tool Suite) -.springBeans - -# Code Recommenders -.recommenders/ - - -coverage.txt - -#vendor -vendor/ diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/.travis.yml b/examples/github.com/grpc-ecosystem/go-grpc-middleware/.travis.yml deleted file mode 100755 index 2fc21dd..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -sudo: false -language: go -go: - - 1.8.x -env: - - DEP_VERSION="0.3.2" - -before_install: - # Download the binary to bin folder in $GOPATH - - curl -L -s https://github.com/golang/dep/releases/download/v${DEP_VERSION}/dep-linux-amd64 -o $GOPATH/bin/dep - # Make the binary executable - - chmod +x $GOPATH/bin/dep - -install: - - dep ensure - -script: - - make checkdocs - - make test - -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md b/examples/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md deleted file mode 100755 index dd52ab8..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# Contributing - -We would love to have people submit pull requests and help make `grpc-ecosystem/go-grpc-middleware` even better 👍. - -Fork, then clone the repo: - -```bash -git clone git@github.com:your-username/go-grpc-middleware.git -``` - -Before checking in please run the following: - -```bash -make all -``` - -This will `vet`, `fmt`, regenerate documentation and run all tests. - - -Push to your fork and open a pull request. \ No newline at end of file diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/DOC.md b/examples/github.com/grpc-ecosystem/go-grpc-middleware/DOC.md deleted file mode 100755 index 511d953..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/DOC.md +++ /dev/null @@ -1,166 +0,0 @@ -# grpc_middleware -`import "github.com/grpc-ecosystem/go-grpc-middleware"` - -* [Overview](#pkg-overview) -* [Imported Packages](#pkg-imports) -* [Index](#pkg-index) - -## Overview -`grpc_middleware` is a collection of gRPC middleware packages: interceptors, helpers and tools. - -### Middleware -gRPC is a fantastic RPC middleware, which sees a lot of adoption in the Golang world. However, the -upstream gRPC codebase is relatively bare bones. - -This package, and most of its child packages provides commonly needed middleware for gRPC: -client-side interceptors for retires, server-side interceptors for input validation and auth, -functions for chaining said interceptors, metadata convenience methods and more. - -### Chaining -By default, gRPC doesn't allow one to have more than one interceptor either on the client nor on -the server side. `grpc_middleware` provides convenient chaining methods - -Simple way of turning a multiple interceptors into a single interceptor. Here's an example for -server chaining: - - myServer := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(loggingStream, monitoringStream, authStream)), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(loggingUnary, monitoringUnary, authUnary), - ) - -These interceptors will be executed from left to right: logging, monitoring and auth. - -Here's an example for client side chaining: - - clientConn, err = grpc.Dial( - address, - grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)), - grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)), - ) - client = pb_testproto.NewTestServiceClient(clientConn) - resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"}) - -These interceptors will be executed from left to right: monitoring and then retry logic. - -The retry interceptor will call every interceptor that follows it whenever when a retry happens. - -### Writing Your Own -Implementing your own interceptor is pretty trivial: there are interfaces for that. But the interesting -bit exposing common data to handlers (and other middleware), similarly to HTTP Middleware design. -For example, you may want to pass the identity of the caller from the auth interceptor all the way -to the handling function. - -For example, a client side interceptor example for auth looks like: - - func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - newCtx := context.WithValue(ctx, "user_id", "john@example.com") - return handler(newCtx, req) - } - -Unfortunately, it's not as easy for streaming RPCs. These have the `context.Context` embedded within -the `grpc.ServerStream` object. To pass values through context, a wrapper (`WrappedServerStream`) is -needed. For example: - - func FakeAuthStreamingInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - newStream := grpc_middleware.WrapServerStream(stream) - newStream.WrappedContext = context.WithValue(ctx, "user_id", "john@example.com") - return handler(srv, stream) - } - -## Imported Packages - -- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context) -- [google.golang.org/grpc](https://godoc.org/google.golang.org/grpc) - -## Index -* [func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor](#ChainStreamClient) -* [func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor](#ChainStreamServer) -* [func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor](#ChainUnaryClient) -* [func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor](#ChainUnaryServer) -* [func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption](#WithStreamServerChain) -* [func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption](#WithUnaryServerChain) -* [type WrappedServerStream](#WrappedServerStream) - * [func WrapServerStream(stream grpc.ServerStream) \*WrappedServerStream](#WrapServerStream) - * [func (w \*WrappedServerStream) Context() context.Context](#WrappedServerStream.Context) - -#### Package files -[chain.go](./chain.go) [doc.go](./doc.go) [wrappers.go](./wrappers.go) - -## func [ChainStreamClient](./chain.go#L136) -``` go -func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor -``` -ChainStreamClient creates a single interceptor out of a chain of many interceptors. - -Execution is done in left-to-right order, including passing of context. -For example ChainStreamClient(one, two, three) will execute one before two before three. - -## func [ChainStreamServer](./chain.go#L58) -``` go -func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor -``` -ChainStreamServer creates a single interceptor out of a chain of many interceptors. - -Execution is done in left-to-right order, including passing of context. -For example ChainUnaryServer(one, two, three) will execute one before two before three. -If you want to pass context between interceptors, use WrapServerStream. - -## func [ChainUnaryClient](./chain.go#L97) -``` go -func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor -``` -ChainUnaryClient creates a single interceptor out of a chain of many interceptors. - -Execution is done in left-to-right order, including passing of context. -For example ChainUnaryClient(one, two, three) will execute one before two before three. - -## func [ChainUnaryServer](./chain.go#L18) -``` go -func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor -``` -ChainUnaryServer creates a single interceptor out of a chain of many interceptors. - -Execution is done in left-to-right order, including passing of context. -For example ChainUnaryServer(one, two, three) will execute one before two before three, and three -will see context changes of one and two. - -## func [WithStreamServerChain](./chain.go#L181) -``` go -func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption -``` -WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors. -Basically syntactic sugar. - -## func [WithUnaryServerChain](./chain.go#L175) -``` go -func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption -``` -Chain creates a single interceptor out of a chain of many interceptors. - -WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors. -Basically syntactic sugar. - -## type [WrappedServerStream](./wrappers.go#L12-L16) -``` go -type WrappedServerStream struct { - grpc.ServerStream - // WrappedContext is the wrapper's own Context. You can assign it. - WrappedContext context.Context -} -``` -WrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context. - -### func [WrapServerStream](./wrappers.go#L24) -``` go -func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream -``` -WrapServerStream returns a ServerStream that has the ability to overwrite context. - -### func (\*WrappedServerStream) [Context](./wrappers.go#L19) -``` go -func (w *WrappedServerStream) Context() context.Context -``` -Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context() - -- - - -Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd) \ No newline at end of file diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.lock b/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.lock deleted file mode 100755 index ebdcb75..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.lock +++ /dev/null @@ -1,123 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "cloud.google.com/go" - packages = ["compute/metadata"] - revision = "2d3a6656c17a60b0815b7e06ab0be04eacb6e613" - version = "v0.16.0" - -[[projects]] - name = "github.com/davecgh/go-spew" - packages = ["spew"] - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - name = "github.com/gogo/protobuf" - packages = ["gogoproto","proto","protoc-gen-gogo/descriptor"] - revision = "342cbe0a04158f6dcb03ca0079991a51a4248c02" - version = "v0.5" - -[[projects]] - branch = "master" - name = "github.com/golang/protobuf" - packages = ["jsonpb","proto","ptypes","ptypes/any","ptypes/duration","ptypes/struct","ptypes/timestamp"] - revision = "1e59b77b52bf8e4b449a57e6f79f21226d571845" - -[[projects]] - name = "github.com/opentracing/opentracing-go" - packages = [".","ext","log","mocktracer"] - revision = "1949ddbfd147afd4d964a9f00b24eb291e0e7c38" - version = "v1.0.2" - -[[projects]] - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - name = "github.com/sirupsen/logrus" - packages = ["."] - revision = "f006c2ac4710855cf0f916dd6b77acf6b048dc6e" - version = "v1.0.3" - -[[projects]] - name = "github.com/stretchr/testify" - packages = ["assert","require","suite"] - revision = "69483b4bd14f5845b5a1e55bca19e954e827f1d0" - version = "v1.1.4" - -[[projects]] - name = "go.uber.org/atomic" - packages = ["."] - revision = "8474b86a5a6f79c443ce4b2992817ff32cf208b8" - version = "v1.3.1" - -[[projects]] - name = "go.uber.org/multierr" - packages = ["."] - revision = "3c4937480c32f4c13a875a1829af76c98ca3d40a" - version = "v1.1.0" - -[[projects]] - name = "go.uber.org/zap" - packages = [".","buffer","internal/bufferpool","internal/color","internal/exit","zapcore"] - revision = "35aad584952c3e7020db7b839f6b102de6271f89" - version = "v1.7.1" - -[[projects]] - branch = "master" - name = "golang.org/x/crypto" - packages = ["ssh/terminal"] - revision = "94eea52f7b742c7cbe0b03b22f0c4c8631ece122" - -[[projects]] - branch = "master" - name = "golang.org/x/net" - packages = ["context","context/ctxhttp","http2","http2/hpack","idna","internal/timeseries","lex/httplex","trace"] - revision = "a8b9294777976932365dabb6640cf1468d95c70f" - -[[projects]] - branch = "master" - name = "golang.org/x/oauth2" - packages = [".","google","internal","jws","jwt"] - revision = "f95fa95eaa936d9d87489b15d1d18b97c1ba9c28" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix","windows"] - revision = "13fcbd661c8ececa8807a29b48407d674b1d8ed8" - -[[projects]] - branch = "master" - name = "golang.org/x/text" - packages = ["collate","collate/build","internal/colltab","internal/gen","internal/tag","internal/triegen","internal/ucd","language","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"] - revision = "75cc3cad82b5f47d3fb229ddda8c5167da14f294" - -[[projects]] - name = "google.golang.org/appengine" - packages = [".","internal","internal/app_identity","internal/base","internal/datastore","internal/log","internal/modules","internal/remote_api","internal/urlfetch","urlfetch"] - revision = "150dc57a1b433e64154302bdc40b6bb8aefa313a" - version = "v1.0.0" - -[[projects]] - branch = "master" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - revision = "7f0da29060c682909f650ad8ed4e515bd74fa12a" - -[[projects]] - name = "google.golang.org/grpc" - packages = [".","balancer","balancer/roundrobin","codes","connectivity","credentials","credentials/oauth","encoding","grpclb/grpc_lb_v1/messages","grpclog","internal","keepalive","metadata","naming","peer","resolver","resolver/dns","resolver/passthrough","stats","status","tap","transport"] - revision = "5a9f7b402fe85096d2e1d0383435ee1876e863d0" - version = "v1.8.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "b24c6670412eb0bc44ed1db77fecc52333f8725f3e3272bdc568f5683a63031f" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.toml b/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.toml deleted file mode 100755 index 0a7d4c1..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/Gopkg.toml +++ /dev/null @@ -1,35 +0,0 @@ -[[constraint]] - name = "github.com/gogo/protobuf" - version = "0.5.0" - -[[constraint]] - branch = "master" - name = "github.com/golang/protobuf" - -[[constraint]] - name = "github.com/opentracing/opentracing-go" - version = "1.0.2" - -[[constraint]] - name = "github.com/sirupsen/logrus" - version = "1.0.3" - -[[constraint]] - name = "github.com/stretchr/testify" - version = "1.1.4" - -[[constraint]] - name = "go.uber.org/zap" - version = "1.7.1" - -[[constraint]] - branch = "master" - name = "golang.org/x/net" - -[[constraint]] - branch = "master" - name = "golang.org/x/oauth2" - -[[constraint]] - name = "google.golang.org/grpc" - version = "1.8.0" diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE b/examples/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE deleted file mode 100755 index b2b0650..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/README.md b/examples/github.com/grpc-ecosystem/go-grpc-middleware/README.md deleted file mode 100755 index 52e5373..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# Go gRPC Middleware - -[![Travis Build](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware) -[![Go Report Card](https://goreportcard.com/badge/github.com/grpc-ecosystem/go-grpc-middleware)](https://goreportcard.com/report/github.com/grpc-ecosystem/go-grpc-middleware) -[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/grpc-ecosystem/go-grpc-middleware) -[![SourceGraph](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/-/badge.svg)](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/?badge) -[![codecov](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware/branch/master/graph/badge.svg)](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware) -[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) -[![quality: production](https://img.shields.io/badge/quality-production-orange.svg)](#status) -[![Slack](slack.png)](https://join.slack.com/t/improbable-eng/shared_invite/enQtMzQ1ODcyMzQ5MjM4LWY5ZWZmNGM2ODc5MmViNmQ3ZTA3ZTY3NzQwOTBlMTkzZmIxZTIxODk0OWU3YjZhNWVlNDU3MDlkZGViZjhkMjc) - -[gRPC Go](https://github.com/grpc/grpc-go) Middleware: interceptors, helpers, utilities. - -**Important** The repo recently moved to `github.com/grpc-ecosystem/go-grpc-middleware`, please update your import paths. - -## Middleware - -[gRPC Go](https://github.com/grpc/grpc-go) recently acquired support for -Interceptors, i.e. [middleware](https://medium.com/@matryer/writing-middleware-in-golang-and-how-go-makes-it-so-much-fun-4375c1246e81#.gv7tdlghs) -that is executed either on the gRPC Server before the request is passed onto the user's application logic, or on the gRPC client either around the user call. It is a perfect way to implement -common patterns: auth, logging, message, validation, retries or monitoring. - -These are generic building blocks that make it easy to build multiple microservices easily. -The purpose of this repository is to act as a go-to point for such reusable functionality. It contains -some of them itself, but also will link to useful external repos. - -`grpc_middleware` itself provides support for chaining interceptors. See [Documentation](DOC.md), but here's an example: - -```go -import "github.com/grpc-ecosystem/go-grpc-middleware" - -myServer := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( - grpc_ctxtags.StreamServerInterceptor(), - grpc_opentracing.StreamServerInterceptor(), - grpc_prometheus.StreamServerInterceptor, - grpc_zap.StreamServerInterceptor(zapLogger), - grpc_auth.StreamServerInterceptor(myAuthFunction), - grpc_recovery.StreamServerInterceptor(), - )), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( - grpc_ctxtags.UnaryServerInterceptor(), - grpc_opentracing.UnaryServerInterceptor(), - grpc_prometheus.UnaryServerInterceptor, - grpc_zap.UnaryServerInterceptor(zapLogger), - grpc_auth.UnaryServerInterceptor(myAuthFunction), - grpc_recovery.UnaryServerInterceptor(), - )), -) -``` - -## Interceptors - -*Please send a PR to add new interceptors or middleware to this list* - -#### Auth - * [`grpc_auth`](auth) - a customizable (via `AuthFunc`) piece of auth middleware - -#### Logging - * [`grpc_ctxtags`](tags/) - a library that adds a `Tag` map to context, with data populated from request body - * [`grpc_zap`](logging/zap/) - integration of [zap](https://github.com/uber-go/zap) logging library into gRPC handlers. - * [`grpc_logrus`](logging/logrus/) - integration of [logrus](https://github.com/sirupsen/logrus) logging library into gRPC handlers. - - -#### Monitoring - * [`grpc_prometheus`⚡](https://github.com/grpc-ecosystem/go-grpc-prometheus) - Prometheus client-side and server-side monitoring middleware - * [`otgrpc`⚡](https://github.com/grpc-ecosystem/grpc-opentracing/tree/master/go/otgrpc) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors - * [`grpc_opentracing`](tracing/opentracing) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors with support for streaming and handler-returned tags - -#### Client - * [`grpc_retry`](retry/) - a generic gRPC response code retry mechanism, client-side middleware - -#### Server - * [`grpc_validator`](validator/) - codegen inbound message validation from `.proto` options - * [`grpc_recovery`](recovery/) - turn panics into gRPC errors - - -## Status - -This code has been running in *production* since May 2016 as the basis of the gRPC micro services stack at [Improbable](https://improbable.io). - -Additional tooling will be added, and contributions are welcome. - -## License - -`go-grpc-middleware` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details. diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain.go b/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain.go deleted file mode 100755 index 45a2f5f..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -// gRPC Server Interceptor chaining middleware. - -package grpc_middleware - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc" -) - -// ChainUnaryServer creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryServer(one, two, three) will execute one before two before three, and three -// will see context changes of one and two. -func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor { - n := len(interceptors) - - if n > 1 { - lastI := n - 1 - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - var ( - chainHandler grpc.UnaryHandler - curI int - ) - - chainHandler = func(currentCtx context.Context, currentReq interface{}) (interface{}, error) { - if curI == lastI { - return handler(currentCtx, currentReq) - } - curI++ - resp, err := interceptors[curI](currentCtx, currentReq, info, chainHandler) - curI-- - return resp, err - } - - return interceptors[0](ctx, req, info, chainHandler) - } - } - - if n == 1 { - return interceptors[0] - } - - // n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil. - return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - return handler(ctx, req) - } -} - -// ChainStreamServer creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryServer(one, two, three) will execute one before two before three. -// If you want to pass context between interceptors, use WrapServerStream. -func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor { - n := len(interceptors) - - if n > 1 { - lastI := n - 1 - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - var ( - chainHandler grpc.StreamHandler - curI int - ) - - chainHandler = func(currentSrv interface{}, currentStream grpc.ServerStream) error { - if curI == lastI { - return handler(currentSrv, currentStream) - } - curI++ - err := interceptors[curI](currentSrv, currentStream, info, chainHandler) - curI-- - return err - } - - return interceptors[0](srv, stream, info, chainHandler) - } - } - - if n == 1 { - return interceptors[0] - } - - // n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil. - return func(srv interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - return handler(srv, stream) - } -} - -// ChainUnaryClient creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryClient(one, two, three) will execute one before two before three. -func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor { - n := len(interceptors) - - if n > 1 { - lastI := n - 1 - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - var ( - chainHandler grpc.UnaryInvoker - curI int - ) - - chainHandler = func(currentCtx context.Context, currentMethod string, currentReq, currentRepl interface{}, currentConn *grpc.ClientConn, currentOpts ...grpc.CallOption) error { - if curI == lastI { - return invoker(currentCtx, currentMethod, currentReq, currentRepl, currentConn, currentOpts...) - } - curI++ - err := interceptors[curI](currentCtx, currentMethod, currentReq, currentRepl, currentConn, chainHandler, currentOpts...) - curI-- - return err - } - - return interceptors[0](ctx, method, req, reply, cc, chainHandler, opts...) - } - } - - if n == 1 { - return interceptors[0] - } - - // n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil. - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - return invoker(ctx, method, req, reply, cc, opts...) - } -} - -// ChainStreamClient creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainStreamClient(one, two, three) will execute one before two before three. -func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor { - n := len(interceptors) - - if n > 1 { - lastI := n - 1 - return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - var ( - chainHandler grpc.Streamer - curI int - ) - - chainHandler = func(currentCtx context.Context, currentDesc *grpc.StreamDesc, currentConn *grpc.ClientConn, currentMethod string, currentOpts ...grpc.CallOption) (grpc.ClientStream, error) { - if curI == lastI { - return streamer(currentCtx, currentDesc, currentConn, currentMethod, currentOpts...) - } - curI++ - stream, err := interceptors[curI](currentCtx, currentDesc, currentConn, currentMethod, chainHandler, currentOpts...) - curI-- - return stream, err - } - - return interceptors[0](ctx, desc, cc, method, chainHandler, opts...) - } - } - - if n == 1 { - return interceptors[0] - } - - // n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil. - return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - return streamer(ctx, desc, cc, method, opts...) - } -} - -// Chain creates a single interceptor out of a chain of many interceptors. -// -// WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors. -// Basically syntactic sugar. -func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption { - return grpc.UnaryInterceptor(ChainUnaryServer(interceptors...)) -} - -// WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors. -// Basically syntactic sugar. -func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption { - return grpc.StreamInterceptor(ChainStreamServer(interceptors...)) -} diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain_test.go b/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain_test.go deleted file mode 100755 index 60008a1..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/chain_test.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package grpc_middleware - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" -) - -var ( - someServiceName = "SomeService.StreamMethod" - parentUnaryInfo = &grpc.UnaryServerInfo{FullMethod: someServiceName} - parentStreamInfo = &grpc.StreamServerInfo{ - FullMethod: someServiceName, - IsServerStream: true, - } - someValue = 1 - parentContext = context.WithValue(context.TODO(), "parent", someValue) -) - -func TestChainUnaryServer(t *testing.T) { - input := "input" - output := "output" - - first := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - requireContextValue(t, ctx, "parent", "first interceptor must know the parent context value") - require.Equal(t, parentUnaryInfo, info, "first interceptor must know the someUnaryServerInfo") - ctx = context.WithValue(ctx, "first", 1) - return handler(ctx, req) - } - second := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - requireContextValue(t, ctx, "parent", "second interceptor must know the parent context value") - requireContextValue(t, ctx, "first", "second interceptor must know the first context value") - require.Equal(t, parentUnaryInfo, info, "second interceptor must know the someUnaryServerInfo") - ctx = context.WithValue(ctx, "second", 1) - return handler(ctx, req) - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - require.EqualValues(t, input, req, "handler must get the input") - requireContextValue(t, ctx, "parent", "handler must know the parent context value") - requireContextValue(t, ctx, "first", "handler must know the first context value") - requireContextValue(t, ctx, "second", "handler must know the second context value") - return output, nil - } - - chain := ChainUnaryServer(first, second) - out, _ := chain(parentContext, input, parentUnaryInfo, handler) - require.EqualValues(t, output, out, "chain must return handler's output") -} - -func TestChainStreamServer(t *testing.T) { - someService := &struct{}{} - recvMessage := "received" - sentMessage := "sent" - outputError := fmt.Errorf("some error") - - first := func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - requireContextValue(t, stream.Context(), "parent", "first interceptor must know the parent context value") - require.Equal(t, parentStreamInfo, info, "first interceptor must know the parentStreamInfo") - require.Equal(t, someService, srv, "first interceptor must know someService") - wrapped := WrapServerStream(stream) - wrapped.WrappedContext = context.WithValue(stream.Context(), "first", 1) - return handler(srv, wrapped) - } - second := func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - requireContextValue(t, stream.Context(), "parent", "second interceptor must know the parent context value") - requireContextValue(t, stream.Context(), "parent", "second interceptor must know the first context value") - require.Equal(t, parentStreamInfo, info, "second interceptor must know the parentStreamInfo") - require.Equal(t, someService, srv, "second interceptor must know someService") - wrapped := WrapServerStream(stream) - wrapped.WrappedContext = context.WithValue(stream.Context(), "second", 1) - return handler(srv, wrapped) - } - handler := func(srv interface{}, stream grpc.ServerStream) error { - require.Equal(t, someService, srv, "handler must know someService") - requireContextValue(t, stream.Context(), "parent", "handler must know the parent context value") - requireContextValue(t, stream.Context(), "first", "handler must know the first context value") - requireContextValue(t, stream.Context(), "second", "handler must know the second context value") - require.NoError(t, stream.RecvMsg(recvMessage), "handler must have access to stream messages") - require.NoError(t, stream.SendMsg(sentMessage), "handler must be able to send stream messages") - return outputError - } - fakeStream := &fakeServerStream{ctx: parentContext, recvMessage: recvMessage} - chain := ChainStreamServer(first, second) - err := chain(someService, fakeStream, parentStreamInfo, handler) - require.Equal(t, outputError, err, "chain must return handler's error") - require.Equal(t, sentMessage, fakeStream.sentMessage, "handler's sent message must propagate to stream") -} - -func TestChainUnaryClient(t *testing.T) { - ignoredMd := metadata.Pairs("foo", "bar") - parentOpts := []grpc.CallOption{grpc.Header(&ignoredMd)} - reqMessage := "request" - replyMessage := "reply" - outputError := fmt.Errorf("some error") - - first := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - requireContextValue(t, ctx, "parent", "first must know the parent context value") - require.Equal(t, someServiceName, method, "first must know someService") - require.Len(t, opts, 1, "first should see parent CallOptions") - wrappedCtx := context.WithValue(ctx, "first", 1) - return invoker(wrappedCtx, method, req, reply, cc, opts...) - } - second := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - requireContextValue(t, ctx, "parent", "second must know the parent context value") - require.Equal(t, someServiceName, method, "second must know someService") - require.Len(t, opts, 1, "second should see parent CallOptions") - wrappedOpts := append(opts, grpc.FailFast(true)) - wrappedCtx := context.WithValue(ctx, "second", 1) - return invoker(wrappedCtx, method, req, reply, cc, wrappedOpts...) - } - invoker := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { - require.Equal(t, someServiceName, method, "invoker must know someService") - requireContextValue(t, ctx, "parent", "invoker must know the parent context value") - requireContextValue(t, ctx, "first", "invoker must know the first context value") - requireContextValue(t, ctx, "second", "invoker must know the second context value") - require.Len(t, opts, 2, "invoker should see both CallOpts from second and parent") - return outputError - } - chain := ChainUnaryClient(first, second) - err := chain(parentContext, someServiceName, reqMessage, replyMessage, nil, invoker, parentOpts...) - require.Equal(t, outputError, err, "chain must return invokers's error") -} - -func TestChainStreamClient(t *testing.T) { - ignoredMd := metadata.Pairs("foo", "bar") - parentOpts := []grpc.CallOption{grpc.Header(&ignoredMd)} - clientStream := &fakeClientStream{} - fakeStreamDesc := &grpc.StreamDesc{ClientStreams: true, ServerStreams: true, StreamName: someServiceName} - - first := func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - requireContextValue(t, ctx, "parent", "first must know the parent context value") - require.Equal(t, someServiceName, method, "first must know someService") - require.Len(t, opts, 1, "first should see parent CallOptions") - wrappedCtx := context.WithValue(ctx, "first", 1) - return streamer(wrappedCtx, desc, cc, method, opts...) - } - second := func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - requireContextValue(t, ctx, "parent", "second must know the parent context value") - require.Equal(t, someServiceName, method, "second must know someService") - require.Len(t, opts, 1, "second should see parent CallOptions") - wrappedOpts := append(opts, grpc.FailFast(true)) - wrappedCtx := context.WithValue(ctx, "second", 1) - return streamer(wrappedCtx, desc, cc, method, wrappedOpts...) - } - streamer := func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) { - require.Equal(t, someServiceName, method, "streamer must know someService") - require.Equal(t, fakeStreamDesc, desc, "streamer must see the right StreamDesc") - - requireContextValue(t, ctx, "parent", "streamer must know the parent context value") - requireContextValue(t, ctx, "first", "streamer must know the first context value") - requireContextValue(t, ctx, "second", "streamer must know the second context value") - require.Len(t, opts, 2, "streamer should see both CallOpts from second and parent") - return clientStream, nil - } - chain := ChainStreamClient(first, second) - someStream, err := chain(parentContext, fakeStreamDesc, nil, someServiceName, streamer, parentOpts...) - require.NoError(t, err, "chain must not return an error as nothing there reutrned it") - require.Equal(t, clientStream, someStream, "chain must return invokers's clientstream") -} - -func requireContextValue(t *testing.T, ctx context.Context, key string, msg ...interface{}) { - val := ctx.Value(key) - require.NotNil(t, val, msg...) - require.Equal(t, someValue, val, msg...) -} diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/doc.go b/examples/github.com/grpc-ecosystem/go-grpc-middleware/doc.go deleted file mode 100755 index 7168950..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/doc.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -/* -`grpc_middleware` is a collection of gRPC middleware packages: interceptors, helpers and tools. - -Middleware - -gRPC is a fantastic RPC middleware, which sees a lot of adoption in the Golang world. However, the -upstream gRPC codebase is relatively bare bones. - -This package, and most of its child packages provides commonly needed middleware for gRPC: -client-side interceptors for retires, server-side interceptors for input validation and auth, -functions for chaining said interceptors, metadata convenience methods and more. - -Chaining - -By default, gRPC doesn't allow one to have more than one interceptor either on the client nor on -the server side. `grpc_middleware` provides convenient chaining methods - -Simple way of turning a multiple interceptors into a single interceptor. Here's an example for -server chaining: - - myServer := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(loggingStream, monitoringStream, authStream)), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(loggingUnary, monitoringUnary, authUnary), - ) - -These interceptors will be executed from left to right: logging, monitoring and auth. - -Here's an example for client side chaining: - - clientConn, err = grpc.Dial( - address, - grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)), - grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)), - ) - client = pb_testproto.NewTestServiceClient(clientConn) - resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"}) - -These interceptors will be executed from left to right: monitoring and then retry logic. - -The retry interceptor will call every interceptor that follows it whenever when a retry happens. - -Writing Your Own - -Implementing your own interceptor is pretty trivial: there are interfaces for that. But the interesting -bit exposing common data to handlers (and other middleware), similarly to HTTP Middleware design. -For example, you may want to pass the identity of the caller from the auth interceptor all the way -to the handling function. - -For example, a client side interceptor example for auth looks like: - - func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - newCtx := context.WithValue(ctx, "user_id", "john@example.com") - return handler(newCtx, req) - } - -Unfortunately, it's not as easy for streaming RPCs. These have the `context.Context` embedded within -the `grpc.ServerStream` object. To pass values through context, a wrapper (`WrappedServerStream`) is -needed. For example: - - func FakeAuthStreamingInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - newStream := grpc_middleware.WrapServerStream(stream) - newStream.WrappedContext = context.WithValue(ctx, "user_id", "john@example.com") - return handler(srv, stream) - } -*/ -package grpc_middleware diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/makefile b/examples/github.com/grpc-ecosystem/go-grpc-middleware/makefile deleted file mode 100755 index 3e0f296..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/makefile +++ /dev/null @@ -1,22 +0,0 @@ -SHELL="/bin/bash" - -GOFILES_NOVENDOR = $(shell go list ./... | grep -v /vendor/) - -all: vet fmt docs test - -docs: - ./scripts/docs.sh generate - -checkdocs: - ./scripts/docs.sh check - -fmt: - go fmt $(GOFILES_NOVENDOR) - -vet: - go vet $(GOFILES_NOVENDOR) - -test: vet - ./scripts/test_all.sh - -.PHONY: all docs validate test diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/slack.png b/examples/github.com/grpc-ecosystem/go-grpc-middleware/slack.png deleted file mode 100755 index cc8f9a68a9368ca56dab09e6902ae41ecb8356b8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5088 zcmZ|Tc{Ei2`vCAe3x;e-vX2jlNl|9+lk+JWL6qTqDN!GHjk+C(5ghC|Q z89rp+TE@P8@A&Wc$M1E{ooDX7=b1U@eeXQaGxw31i7o>jCmjF)4ElOn=3p!VH&$k9 z@Kt}PY#$78cXeZR0C@NG+>s*{xXd;33>H00c<_z^VfPD82-M zOW4=V*OkE&)J}%FT3`h2YqrFIfflQ09RNm~vkfcI7zMte3Dh^%rkR6tA+FNiG=De_ z04%BcTIx4LCpPTDZn9dAoZbov8v4dCE&J634Y7Qp&X3^i)B1M(ADWDkSV*iN7kd)> zqd4~Y*H}BDdBJ$Wu0|IuL+0RbEjvkFo(wIsbO_aTEJU62)m;xvI%)0jP3x;w2nU<) z@2u*WC30Bt>TuK+>2UK948xvI_!&&wc(kmn$)(p4^0&uYvw!h_KvchE7vw+xNJ63p z3Va*cnVhjFDE_dqa(r-66Cwh$yDuYa9*+6AtDq3Cwa`yfL=H^(#{~0H2xDMeh>qp- z^0}j7#;SeYqT9-`^VAd*dw##F3SPruUt0PBV_h~NfP4F@M5ydvA!>`oqlOxml8Y8r zzfJG|=l*wk%qpd)pteM8&76R;qWwW9TCpcwP@;TaNh#IBX&G4&UHg$vw7J6|@A&?( zsfCrJb_kZ;Db(IIm_invBB-A-P@PNa5ztNMR`CDXx!apYBH{6GbYWa_$-D%2rihp| ziumC^e*@} z5o=w0)5UGOMz$zNTcdDaT%=!s;j^5_|Ht17GT%whqFOCH|R>^DXD zMAt}!?X}qW_^PT`uTGwxI&3RM$cnB1cIFcXO+WPqH??+8`FYhm@jsCz)QXkD-GBF8Qf68r3Zu%CeRqd`Zn=g=d52GkeC(9`Y}Fe(j(-f zIIZf6-pfd_l$3qrk^7gQy|S@j;}~za9XDL8R95EYEh-vYQPI=WXN2p%kf^|&j_&P6 zs)~ui`m@W+6oct&8ffAfV2nJElL&#djZrO?l{L?@_rQ9^QRmL|>*P?_w5tocu)x63 z*$E_QGTTYa&PjQtX+h1>DmTz`cKK#kSm_*o&!q}?e8m02-kDkU;FAs*spv?EP2xh? z8yP_HzSR|dpMmJ@aw0K})!{!4WbUnUoT(Zi1a+<6{YWx1SL@@Fk^-dM^6=o~KPI%( z+~6B&H-LeG)7VG+SsJ;E%XjyYFVTVXHO#B;RyQ&## z@L;7Qc6O3T9k8(m-`{i6?zlq3#Ke`0w}Q48deMR8w10au>Nc*5R%OW{)g;8;Ru>yV zHc3%`ej-l+AtPqGViPJxq=fkKswl4DzQ$wd$zC@yW~v5aR%&DW!a(+hi2)t0bqkwS z4RKmUf#Y+3Rpm6kax2t7c!wMq$lZ9GI&QpTbXUy;yd#Iti1`&2Q@}2sL0_jh?;y!e zPpvrsaqi)ecI$h26^1xR0Ylv5L)`m{%`{36i~jlfIoLtqWoK{)6ya#0RIm`@k(CzZ z!(P@Jt~FtQ7r$o7!J5vX?J0Qq*b+OP{AS?echqR%5)#~uv-8rCjnyc#J2N8|H(>N! zI}_f@ypq8c#Y^{TiKc2QVJTVX^aSU-|Awj@a;Qv<$VxI_5iKuo@q>NyQc=lz1w8uH z72gdr$&LOsyL_GRvg_QZuUX;?>+4Wh>|_HMr-31)exkDw&&Dp>H<{H9`}2qO@m4Er zr1HWe@Z!LsjJj9g&CNzdJ3FKe&I;9Ozl~SsVT<$*zG_~q`a2b$2pZ_m?Pe&u-psIvNqrE7IY+BJO(JCuY8Qd0kALDo~MNUruFUps0kp?Xp@ZQ>(NTrg)<2ilGn-s%qyqC*?ACXe<52jCC{+^x<` zudRfOGkjvmR+(W$qRFl}Vz1`ZPs#!6<4FNwIfMI>Dr}mg%z>bzfI6MQy+4x!Tb!qW zY3Wcv|2>1#c{AuCgZ7}fQsdBmkLny-jej`7zIwDyt9Sl)sIt9jg4Fi()+IKI+KoGH z(Z>hdYbuXg<;V-dmoCK;hc1jY`b{;eL;y52DQN}}-lqi^46Z`#(a$~(;^buiU9hnT zU3g??hg)6k@2{1bO+=NIeIFX%dD2xSQOCiDprN@3EQ`ljFmZ8Z_Whx1pOVW|RPt0% z%w5DT2LU%w%<>9;P3itR0@{#(#m1KIZrHg?t$*mU^}ox9zsK)@y&NxF|4OJJc4df1 zC^at5WK=1i7S2MO%M=)BcGL0_ddp*Q-Z%v}_<2m%6msvG0R$(gT~M5)MDSBbDP)MP zOt&IqFqos02t$R^9}W)E|1fs<_hYC76;t(#-$?WHo**>%Br`qC8lbq*)B@>@?%*0I@&nN;MQ%13cLLdrt8;La^(5zc-hS1AWflLodNPhs z$(YuJZm?fFIhpkLWr7!LsB{=@^|E2N!kXB!MNM60H$Id@np?5nSVd7s(hayoo()&Y zXg`XpHDCw3-4gtc<1M8gKTx4D=VL~|p?PQ3A#*x4jnV*FUn&GF_GL;(^jtLzx^sp& zK=HKFUCKm>q9rGp)E0Aka(p;WpZ?`FM-qV8wy}tu! z9i6+IwXSHl#g!rNQRrxuN+|X}C^ItVmqVz0P0-qS-P*`Drn*3*P(%bOWP}Z3perz4 zo1Pjwu&$e$c6JIsDE(kpC?W>$N)8HUMC9$piyg~E;InKoV%Q~<8$(~S(7FkOC4)eB z@{6>{L-AiblXqfN{P=B8erZ~dKNpA_Enb2bX%ZU3b<`GHTUyYPPH>-rPmj>r+J=UX z|6teB4T6ppCH>zTEpC}^5sY7Za4^XP(LJ!MvYKj$G8K4Lym4{I4Jm4zK^X70n`th* zNos7LxXkL`#K?$=(tDUXG_=_6un;~pzi3=on+N>*{rrp0Q|gZ$Goj91^k^|&xn#j{ z|J5IIGxQ7_`eU7)be+TH#JNs;`*KT|t1CDJQUUrClNaD-HV1ot>X4eycMZF%!{GG_ z_&Z!)@u9M^osSJhr)_KNEP!V2NN8w)IlXIB(}xBu!r@|8MDo~aXt+hofi0svEGUG6 zCgqIS%e@%d^}XNo-A|G3OmWRjR{9jQErB!dJ%@^nv&K63o9rYqdLa>KEUL;W5~mN1 zj451cQx%TJTSB%-goxN43Ilvh5h0F-iB~z4+3LN=V1afbj!Et4R|k_C9FG|X2XZ!i z?&fl@sgaHl+f$@z3h_QIFR!{faVdAEEjOL|!{6lG8Svh{e*MPKLhpJ2p}yK8peZSd zD4hFREjNcT^3NCYN_R3uktaLzHo@jbz$SOzphvxFPR$=5AHh;HAWJq|@x^O;%#?h< zqTCFi%$w0W4>53!XwiT~k_VdtL@lAXV&QCcMWq0F%s7u%y}cTH6!ogEgk||f1kSgW zmhRwiW_-X$^<=LvbC(2@;e1|F_#i5Jy7_|e+PwY~H49>Y@_;)dZJ!%hmqbM6 zFn|oF`;zx)ctf?^y_K!{%LLV^g46P;RAJ>D4am`o=_Qn#3y_&PRK%kQ|GYrX*T0=@ z;2PGrTLCtRK~n!x10K3X2w5L%*@Aj{*13cA{>zu>Xk<)Zj+don`S8L5TKj>`ZL81t z8x|v^=xveNRS{OOni)T{tO8iIFK`8@#GI5@3kgA8T{#(y^Z3teLmoWv-v_4^t@}5d zL$B8O*gDLH%s@Dk21_hp{$V##?HJ|d^$L@dk2z>K2fQp})cdmJd`Ta|j*HE*O^SzB z#x941NOBbE34$Xk+L=ON_H5++DDiICtKOy(ZwDRR&3uw(Z6lreFU;-V0rJdrY@g$W zRBNeY=>)@yxJi(8#LH-Qm1gI>)2<&AHa1?801GWaw`jO$LFfXSnM}Tju)8gu@twfP zoNsXsjyCM=NZ@2ZBa?u^!BnBnE~qbIVUw4K;pk-d+BHAF^k^@iYgw`V{mqK0w0SG= zS?pfqJwS^eiIfPLHB4_`eRFehX>A*4#KvjR=5=!MlEnQ4IXPHq+whseVvzZIEPd>n*c0HEB^=b!T)9QYs_=a=?8XoCa14=Hoi@)!d!C3hU}x zNiI;A+Gos$QPiTNS-ek9czB-jawL&S(&Fj^5-F^7v;|A{0`nQ^>2pqTv6T()`~rVs zfozjPsVqoRQCZJ-Un6d*4R4v<&B1xyn8;6V z_@5+XbLzAR)tTtNkV~=sx!;hur~c>cV>Wyz?6{lDo6_rS*%QgIK@+5n!#;|{wB)KyB4U|;DLJPP1C@@FzM@~ctV z`mHaSe&=SWiri9zfq#_FkUp?_PmRjf*3^_S zLE;YeaZZM+`O42Pr<>#nI#GKOILrA)zKm3Cy!7h;|7BwR5gE*}62^niPug*NjKT`} z3JP|)qN41kp6 zRe5nq8F4AOo02k$G75^43gE7yq@<=ga_s*k`1rbbx`qA!2~ym}E?|NrQ|-94SX#jjnJm)CTa(>D^oW*K(PRrb$m?jo2A=xdv3 JRcScf`yb{=X{rDK diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go b/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go deleted file mode 100755 index 597b862..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package grpc_middleware - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc" -) - -// WrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context. -type WrappedServerStream struct { - grpc.ServerStream - // WrappedContext is the wrapper's own Context. You can assign it. - WrappedContext context.Context -} - -// Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context() -func (w *WrappedServerStream) Context() context.Context { - return w.WrappedContext -} - -// WrapServerStream returns a ServerStream that has the ability to overwrite context. -func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream { - if existing, ok := stream.(*WrappedServerStream); ok { - return existing - } - return &WrappedServerStream{ServerStream: stream, WrappedContext: stream.Context()} -} diff --git a/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers_test.go b/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers_test.go deleted file mode 100755 index 69c3b9b..0000000 --- a/examples/github.com/grpc-ecosystem/go-grpc-middleware/wrappers_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package grpc_middleware - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" -) - -func TestWrapServerStream(t *testing.T) { - ctx := context.WithValue(context.TODO(), "something", 1) - fake := &fakeServerStream{ctx: ctx} - wrapped := WrapServerStream(fake) - assert.NotNil(t, wrapped.Context().Value("something"), "values from fake must propagate to wrapper") - wrapped.WrappedContext = context.WithValue(wrapped.Context(), "other", 2) - assert.NotNil(t, wrapped.Context().Value("other"), "values from wrapper must be set") -} - -type fakeServerStream struct { - grpc.ServerStream - ctx context.Context - recvMessage interface{} - sentMessage interface{} -} - -func (f *fakeServerStream) Context() context.Context { - return f.ctx -} - -func (f *fakeServerStream) SendMsg(m interface{}) error { - if f.sentMessage != nil { - return grpc.Errorf(codes.AlreadyExists, "fakeServerStream only takes one message, sorry") - } - f.sentMessage = m - return nil -} - -func (f *fakeServerStream) RecvMsg(m interface{}) error { - if f.recvMessage == nil { - return grpc.Errorf(codes.NotFound, "fakeServerStream has no message, sorry") - } - return nil -} - -type fakeClientStream struct { - grpc.ClientStream -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/.gitignore deleted file mode 100755 index 55e4918..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -_output/ -.idea - -# Bazel. -bazel-bin -bazel-genfiles -bazel-grpc-gateway -bazel-out -bazel-testlogs diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis.yml b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis.yml deleted file mode 100755 index 323a464..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis.yml +++ /dev/null @@ -1,81 +0,0 @@ -language: go -sudo: false -go: - - 1.9.x - - 1.10.x - - master -go_import_path: github.com/grpc-ecosystem/grpc-gateway -cache: - directories: - - $HOME/local - - ${TRAVIS_BUILD_DIR}/examples/browser/node_modules - - $HOME/.cache/_grpc_gateway_bazel -before_install: - - if [ "${USE_BAZEL}" = true ]; then ./.travis/install-bazel.sh $BAZEL_VERSION; fi - - test "${USE_BAZEL}" = true || ./.travis/install-protoc.sh $PROTOC_VERSION - - test "${USE_BAZEL}" = true || ./.travis/install-swagger-codegen.sh $SWAGGER_CODEGEN_VERSION - - test "${USE_BAZEL}" = true || (nvm install $NODE_VERSION && nvm use $NODE_VERSION && node --version) - - test "${USE_BAZEL}" = true || go get github.com/golang/lint/golint - - test "${USE_BAZEL}" = true || go get github.com/dghubble/sling - - test "${USE_BAZEL}" = true || go get github.com/go-resty/resty -install: - # Make sure externally referenced packages are go-gettable. - - test "${USE_BAZEL}" = true || - go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway - - test "${USE_BAZEL}" = true || - go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger - - test "${USE_BAZEL}" = true || - go get github.com/grpc-ecosystem/grpc-gateway/runtime - - test "${USE_BAZEL}" = true || - go get github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server - - test "${USE_BAZEL}" = true || - go get github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server - - # Just build if USE_BAZEL - - if [ "${USE_BAZEL}" = true ]; then ./.travis/bazel-build.sh; fi -before_script: - - test "${USE_BAZEL}" = true || - (cd examples/browser && npm install) -script: - # Make sure examples of generated files are up-to-date - - test "${USE_BAZEL}" = true || - (make realclean && make examples SWAGGER_CODEGEN="java -jar $HOME/local/swagger-codegen-cli.jar") - - if [ -z "${USE_BAZEL}" ] && - (go version | grep -q "${GO_VERSION_TO_DIFF_TEST}") && - [ -z "${GATEWAY_PLUGIN_FLAGS}" ]; then - test -z "$(git status --porcelain)" || (git status; git diff; exit 1); - fi - - # Unit tests, integration tests and code health checks - - test "${USE_BAZEL}" = true || - env GLOG_logtostderr=1 go test -race -v github.com/grpc-ecosystem/grpc-gateway/... - - test "${USE_BAZEL}" = true || - make lint - - test "${USE_BAZEL}" = true || - sh -c 'cd examples/browser && node ./node_modules/gulp/bin/gulp' - - - if [ "${USE_BAZEL}" = true ]; then ./.travis/bazel-test.sh; fi - - # test coverage - - if (go version | grep -q "${GO_VERSION_TO_DIFF_TEST}") && - [ -z "${GATEWAY_PLUGIN_FLAGS}" ]; then - env GLOG_logtostderr=1 ./bin/coverage; - fi -after_success: - - bash <(curl -s https://codecov.io/bash) - -env: - global: - - "PATH=$PATH:$HOME/local/bin" - - GO_VERSION_TO_DIFF_TEST="go version go1\.10\.[0-9]\+ linux/amd64" - - BAZEL_VERSION=0.12.0 - - NODE_VERSION=v6.1 - - PROTOC_VERSION=3.1.0 - - SWAGGER_CODEGEN_VERSION=2.2.2 - matrix: - - GATEWAY_PLUGIN_FLAGS= - - GATEWAY_PLUGIN_FLAGS=request_context=false -matrix: - include: - - go: master - env: USE_BAZEL=true diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-build.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-build.sh deleted file mode 100755 index f46781d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-build.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -eu - -bazel \ - --batch \ - --output_base=$HOME/.cache/_grpc_gateway_bazel \ - --host_jvm_args=-Xmx500m \ - --host_jvm_args=-Xms500m \ - build \ - --local_resources=400,1,1.0 \ - //... diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-test.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-test.sh deleted file mode 100755 index 86dbbf3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/bazel-test.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -eu - -bazel \ - --batch \ - --output_base=$HOME/.cache/_grpc_gateway_bazel \ - --host_jvm_args=-Xmx500m \ - --host_jvm_args=-Xms500m \ - test \ - --local_resources=400,1,1.0 \ - --test_output=errors \ - --features=race \ - //... diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-bazel.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-bazel.sh deleted file mode 100755 index 9bebe44..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-bazel.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh -eu - -bazel_version=$1 - -if test -z "${bazel_version}"; then - echo "Usage: .travis/install-bazel.sh bazel-version" - exit 1 -fi - -if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then - OS=darwin -else - OS=linux -fi - -filename=bazel-${bazel_version}-installer-${OS}-x86_64.sh -wget https://github.com/bazelbuild/bazel/releases/download/${bazel_version}/${filename} -chmod +x $filename -./$filename --user -rm -f $filename diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-protoc.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-protoc.sh deleted file mode 100755 index d96c259..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-protoc.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -eu -protoc_version=$1 -if test -z "${protoc_version}"; then - echo "Usage: .travis/install-protoc.sh protoc-version" - exit 1 -fi -if [ "`$HOME/local/bin/protoc-${protoc_version} --version 2>/dev/null | cut -d' ' -f 2`" != ${protoc_version} ]; then - rm -rf $HOME/local/bin $HOME/local/include - - mkdir -p $HOME/tmp $HOME/local - cd $HOME/tmp - wget https://github.com/google/protobuf/releases/download/v${protoc_version}/protoc-${protoc_version}-linux-x86_64.zip - unzip protoc-${protoc_version}-linux-x86_64.zip - mv bin $HOME/local/bin - mv include $HOME/local/include -fi - -echo \$ $HOME/local/bin/protoc --version -$HOME/local/bin/protoc --version diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-swagger-codegen.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-swagger-codegen.sh deleted file mode 100755 index ad4c8b5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/.travis/install-swagger-codegen.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -eu -codegen_version=$1 -if test -z "${codegen_version}"; then - echo "Usage: .travis/install-swagger-codegen.sh codegen-version" - exit 1 -fi - -wget http://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/${codegen_version}/swagger-codegen-cli-${codegen_version}.jar \ - -O $HOME/local/swagger-codegen-cli.jar diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/BUILD b/examples/github.com/grpc-ecosystem/grpc-gateway/BUILD deleted file mode 100755 index 0ab0afa..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/BUILD +++ /dev/null @@ -1,23 +0,0 @@ -load("@bazel_gazelle//:def.bzl", "gazelle") - -# gazelle:exclude third_party - -gazelle( - name = "gazelle_diff", - mode = "diff", - prefix = "github.com/grpc-ecosystem/grpc-gateway", -) - -gazelle( - name = "gazelle_fix", - mode = "fix", - prefix = "github.com/grpc-ecosystem/grpc-gateway", -) - -package_group( - name = "generators", - packages = [ - "//protoc-gen-grpc-gateway/...", - "//protoc-gen-swagger/...", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md b/examples/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md deleted file mode 100755 index bc7f219..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/CHANGELOG.md +++ /dev/null @@ -1,590 +0,0 @@ -# Change Log - -## [v1.4.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.4.1) (2018-05-23) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.4.0...v1.4.1) - -**Closed issues:** - -- Next release ? [\#605](https://github.com/grpc-ecosystem/grpc-gateway/issues/605) - -**Merged pull requests:** - -- Translate gRPC FailedPrecondition as HTTP PreconditionFailed [\#657](https://github.com/grpc-ecosystem/grpc-gateway/pull/657) ([slomek](https://github.com/slomek)) - -## [v1.4.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.4.0) (2018-05-20) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.3.1...v1.4.0) - -**Implemented enhancements:** - -- customize the error return [\#405](https://github.com/grpc-ecosystem/grpc-gateway/issues/405) -- Support map type in query string [\#316](https://github.com/grpc-ecosystem/grpc-gateway/issues/316) -- gRPC gateway Bazel build rules [\#66](https://github.com/grpc-ecosystem/grpc-gateway/issues/66) -- Support bytes fields in path parameter [\#5](https://github.com/grpc-ecosystem/grpc-gateway/issues/5) - -**Closed issues:** - -- the protoc\_gen\_swagger bazel rule generates non working import path. [\#633](https://github.com/grpc-ecosystem/grpc-gateway/issues/633) -- code.NotFound should return a 404 instead of a 405 [\#630](https://github.com/grpc-ecosystem/grpc-gateway/issues/630) -- field in query path not found [\#629](https://github.com/grpc-ecosystem/grpc-gateway/issues/629) -- how to use client pool in the gateway? [\#612](https://github.com/grpc-ecosystem/grpc-gateway/issues/612) -- pass http request uri to grpc server [\#587](https://github.com/grpc-ecosystem/grpc-gateway/issues/587) -- bidi streams have racy read caused by goroutine that closes over local variable [\#583](https://github.com/grpc-ecosystem/grpc-gateway/issues/583) -- Streamed response is not valid json \(or: is this the expected format?\) [\#581](https://github.com/grpc-ecosystem/grpc-gateway/issues/581) -- Import "google/api/annotations.proto" was not found or had errors. [\#574](https://github.com/grpc-ecosystem/grpc-gateway/issues/574) -- is there has a way to let grpc-gateway server support multiple endpoints [\#573](https://github.com/grpc-ecosystem/grpc-gateway/issues/573) -- would it be possible to avoid vendoring "third\_party/googleapis/" [\#572](https://github.com/grpc-ecosystem/grpc-gateway/issues/572) -- Path parameters can't have URL encoded values [\#566](https://github.com/grpc-ecosystem/grpc-gateway/issues/566) -- Is there anyway to output the access log of grpc gateway [\#556](https://github.com/grpc-ecosystem/grpc-gateway/issues/556) -- proto: no slice oenc for \*reflect.rtype = \[\]\*reflect.rtype [\#551](https://github.com/grpc-ecosystem/grpc-gateway/issues/551) -- autoreconf not found [\#549](https://github.com/grpc-ecosystem/grpc-gateway/issues/549) -- \[feature\]combine expvar into grpc-gateway [\#542](https://github.com/grpc-ecosystem/grpc-gateway/issues/542) -- Source code still imports "golang.org/x/net/context" [\#533](https://github.com/grpc-ecosystem/grpc-gateway/issues/533) -- Incorrect error message when execute protoc-gen-grpc-gateway to HTTP GET method with BODY [\#531](https://github.com/grpc-ecosystem/grpc-gateway/issues/531) -- add support for the google.api.HttpBody proto as a request [\#528](https://github.com/grpc-ecosystem/grpc-gateway/issues/528) -- Prefixed model names in generated swagger spec [\#525](https://github.com/grpc-ecosystem/grpc-gateway/issues/525) -- Better format for error.message in stream [\#519](https://github.com/grpc-ecosystem/grpc-gateway/issues/519) -- Getting this on go get . in the src directory: HelloService.pb.go:20:8 - no Go files in \go\src\google\api [\#518](https://github.com/grpc-ecosystem/grpc-gateway/issues/518) -- ci: set up codecov [\#513](https://github.com/grpc-ecosystem/grpc-gateway/issues/513) -- protoc-gen-swagger not using description field of info swagger object [\#511](https://github.com/grpc-ecosystem/grpc-gateway/issues/511) -- Cut a minor release for https://github.com/grpc-ecosystem/grpc-gateway/issues/495 [\#506](https://github.com/grpc-ecosystem/grpc-gateway/issues/506) -- bug: uncapitalized service name causes runtime error unknown function in service.pb.gw.go [\#484](https://github.com/grpc-ecosystem/grpc-gateway/issues/484) -- RESOURCE\_EXHAUSTED -\> 503 [\#431](https://github.com/grpc-ecosystem/grpc-gateway/issues/431) -- Adding authentication definitions to generated swagger files [\#428](https://github.com/grpc-ecosystem/grpc-gateway/issues/428) -- Move to stdlib context over x/net/context [\#326](https://github.com/grpc-ecosystem/grpc-gateway/issues/326) -- deprecate 1.6 and embrace \(\*http.Request\).Context by default [\#313](https://github.com/grpc-ecosystem/grpc-gateway/issues/313) - -**Merged pull requests:** - -- Generate a single swagger definition on demand [\#658](https://github.com/grpc-ecosystem/grpc-gateway/pull/658) ([achew22](https://github.com/achew22)) -- Regenerate example files [\#656](https://github.com/grpc-ecosystem/grpc-gateway/pull/656) ([achew22](https://github.com/achew22)) -- Add v1.4.0 changelog [\#655](https://github.com/grpc-ecosystem/grpc-gateway/pull/655) ([achew22](https://github.com/achew22)) -- Add README.md for examples [\#645](https://github.com/grpc-ecosystem/grpc-gateway/pull/645) ([liukgg](https://github.com/liukgg)) -- JSONPb marshaler panics if input is nil interface [\#639](https://github.com/grpc-ecosystem/grpc-gateway/pull/639) ([jhump](https://github.com/jhump)) -- provide access to underlying \*json.Decoder from JSONPb.NewDecoder [\#637](https://github.com/grpc-ecosystem/grpc-gateway/pull/637) ([jhump](https://github.com/jhump)) -- fix compile errors caused by protobuf finally merging their dev branch to master [\#636](https://github.com/grpc-ecosystem/grpc-gateway/pull/636) ([jhump](https://github.com/jhump)) -- Generate import mappings. [\#635](https://github.com/grpc-ecosystem/grpc-gateway/pull/635) ([ensonic](https://github.com/ensonic)) -- Add support for the grpc\_api\_configuration option in the bazel rule. [\#632](https://github.com/grpc-ecosystem/grpc-gateway/pull/632) ([ensonic](https://github.com/ensonic)) -- Use repo relative labels in protoc-gen-swagger [\#631](https://github.com/grpc-ecosystem/grpc-gateway/pull/631) ([achew22](https://github.com/achew22)) -- Correct dependencies in Makefile [\#626](https://github.com/grpc-ecosystem/grpc-gateway/pull/626) ([yugui](https://github.com/yugui)) -- Avoid timing issues in the integration tests [\#624](https://github.com/grpc-ecosystem/grpc-gateway/pull/624) ([yugui](https://github.com/yugui)) -- Fix typos in gRPC API Configuration usage documentation [\#623](https://github.com/grpc-ecosystem/grpc-gateway/pull/623) ([hacst](https://github.com/hacst)) -- Skip unnecessary steps in USE\_BAZEL builds on TravisCI [\#622](https://github.com/grpc-ecosystem/grpc-gateway/pull/622) ([yugui](https://github.com/yugui)) -- Support param for field from Oneof definition. [\#621](https://github.com/grpc-ecosystem/grpc-gateway/pull/621) ([bonafideyan](https://github.com/bonafideyan)) -- Fixes file integrity errors on TravisCI [\#619](https://github.com/grpc-ecosystem/grpc-gateway/pull/619) ([yugui](https://github.com/yugui)) -- Reorganize examples [\#618](https://github.com/grpc-ecosystem/grpc-gateway/pull/618) ([yugui](https://github.com/yugui)) -- Update dependency declarations in the Makefile [\#617](https://github.com/grpc-ecosystem/grpc-gateway/pull/617) ([yugui](https://github.com/yugui)) -- Support delete method in swagger generator [\#616](https://github.com/grpc-ecosystem/grpc-gateway/pull/616) ([blackdahila](https://github.com/blackdahila)) -- feat\(bazel\): Add rule for generating .swagger.json files [\#613](https://github.com/grpc-ecosystem/grpc-gateway/pull/613) ([mrmeku](https://github.com/mrmeku)) -- Support UNIX domain socket in the example servers [\#609](https://github.com/grpc-ecosystem/grpc-gateway/pull/609) ([yugui](https://github.com/yugui)) -- misspelling [\#601](https://github.com/grpc-ecosystem/grpc-gateway/pull/601) ([chemidy](https://github.com/chemidy)) -- Pulled out parseReq func into a generic package + tests [\#600](https://github.com/grpc-ecosystem/grpc-gateway/pull/600) ([f0rmiga](https://github.com/f0rmiga)) -- Added Bazel support [\#599](https://github.com/grpc-ecosystem/grpc-gateway/pull/599) ([f0rmiga](https://github.com/f0rmiga)) -- Add basic docs section [\#597](https://github.com/grpc-ecosystem/grpc-gateway/pull/597) ([achew22](https://github.com/achew22)) -- Upgrade to go1.10 and regenerate [\#596](https://github.com/grpc-ecosystem/grpc-gateway/pull/596) ([achew22](https://github.com/achew22)) -- Support cases where the request is done with transfer-encoding chunked [\#589](https://github.com/grpc-ecosystem/grpc-gateway/pull/589) ([jacksontj](https://github.com/jacksontj)) -- Support multiple metadata annotators [\#586](https://github.com/grpc-ecosystem/grpc-gateway/pull/586) ([dmacthedestroyer](https://github.com/dmacthedestroyer)) -- Changed to use more appropriate http status code for ResourceExhausted [\#580](https://github.com/grpc-ecosystem/grpc-gateway/pull/580) ([eleniums](https://github.com/eleniums)) -- fix racy access of err variable [\#575](https://github.com/grpc-ecosystem/grpc-gateway/pull/575) ([jhump](https://github.com/jhump)) -- runtime: return 503 not 403 with ResourceExhausted. [\#569](https://github.com/grpc-ecosystem/grpc-gateway/pull/569) ([hexfusion](https://github.com/hexfusion)) -- \[\]byte in query now uses base64.StdEncoding [\#565](https://github.com/grpc-ecosystem/grpc-gateway/pull/565) ([lucasvo](https://github.com/lucasvo)) -- Add 3rd party rpc protos in order to have access to status and error [\#563](https://github.com/grpc-ecosystem/grpc-gateway/pull/563) ([rvegas](https://github.com/rvegas)) -- Add details to stream error response [\#561](https://github.com/grpc-ecosystem/grpc-gateway/pull/561) ([johanbrandhorst](https://github.com/johanbrandhorst)) -- fix noenc error by fixing Details error field [\#557](https://github.com/grpc-ecosystem/grpc-gateway/pull/557) ([srenatus](https://github.com/srenatus)) -- error details: add @type key by switching to any.Any [\#553](https://github.com/grpc-ecosystem/grpc-gateway/pull/553) ([srenatus](https://github.com/srenatus)) -- Add a FAQ [\#550](https://github.com/grpc-ecosystem/grpc-gateway/pull/550) ([achew22](https://github.com/achew22)) -- Add security fields support to protoc-gen-swagger [\#547](https://github.com/grpc-ecosystem/grpc-gateway/pull/547) ([ivucica](https://github.com/ivucica)) -- Omit well-known type definitions from swagger output [\#541](https://github.com/grpc-ecosystem/grpc-gateway/pull/541) ([alexleigh](https://github.com/alexleigh)) -- Use importPath to set package name rather than package path. [\#537](https://github.com/grpc-ecosystem/grpc-gateway/pull/537) ([rwlincoln](https://github.com/rwlincoln)) -- Support for map type in query string [\#535](https://github.com/grpc-ecosystem/grpc-gateway/pull/535) ([adamstruck](https://github.com/adamstruck)) -- Fix error message in protoc-gen-grpc-gateway \(for \#531\) [\#532](https://github.com/grpc-ecosystem/grpc-gateway/pull/532) ([budougumi0617](https://github.com/budougumi0617)) -- runtime: support FieldMask as query param [\#529](https://github.com/grpc-ecosystem/grpc-gateway/pull/529) ([glerchundi](https://github.com/glerchundi)) -- Fix decoding empty request body [\#527](https://github.com/grpc-ecosystem/grpc-gateway/pull/527) ([syhpoon](https://github.com/syhpoon)) -- Add description, summary and tags fields in operationObject \(swagger\) [\#526](https://github.com/grpc-ecosystem/grpc-gateway/pull/526) ([devnull-](https://github.com/devnull-)) -- Converts the first letter of service name to uppercase [\#522](https://github.com/grpc-ecosystem/grpc-gateway/pull/522) ([thurt](https://github.com/thurt)) -- Add support for basic gRPC API Configuration YAML files [\#521](https://github.com/grpc-ecosystem/grpc-gateway/pull/521) ([hacst](https://github.com/hacst)) -- Fix travis to only difftest on go 1.9 [\#520](https://github.com/grpc-ecosystem/grpc-gateway/pull/520) ([achew22](https://github.com/achew22)) -- add error details to error json [\#515](https://github.com/grpc-ecosystem/grpc-gateway/pull/515) ([srenatus](https://github.com/srenatus)) -- ci: add codecov [\#514](https://github.com/grpc-ecosystem/grpc-gateway/pull/514) ([tmc](https://github.com/tmc)) -- Generate "Description" and "TermsOfService" fields [\#512](https://github.com/grpc-ecosystem/grpc-gateway/pull/512) ([lukasmalkmus](https://github.com/lukasmalkmus)) -- Release 1.3.1 [\#509](https://github.com/grpc-ecosystem/grpc-gateway/pull/509) ([tmc](https://github.com/tmc)) -- Support mapping bytes to \[\]byte [\#489](https://github.com/grpc-ecosystem/grpc-gateway/pull/489) ([loderunner](https://github.com/loderunner)) -- properly respect file flag for protoc-gen-swagger [\#293](https://github.com/grpc-ecosystem/grpc-gateway/pull/293) ([tmc](https://github.com/tmc)) - -## [v1.3.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3.1) (2017-12-23) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.3.0...v1.3.1) - -**Implemented enhancements:** - -- Support import\_path? [\#443](https://github.com/grpc-ecosystem/grpc-gateway/issues/443) - -**Closed issues:** - -- protoc-gen-swagger missing definition issue [\#504](https://github.com/grpc-ecosystem/grpc-gateway/issues/504) -- Are gateway metrics available? [\#498](https://github.com/grpc-ecosystem/grpc-gateway/issues/498) -- Backwards incompatible change to chunked encoding [\#495](https://github.com/grpc-ecosystem/grpc-gateway/issues/495) -- Map of list [\#493](https://github.com/grpc-ecosystem/grpc-gateway/issues/493) -- Repeated nested messages doesn't work in GET requests queries. [\#492](https://github.com/grpc-ecosystem/grpc-gateway/issues/492) -- How to run `makefile` for this repo? [\#491](https://github.com/grpc-ecosystem/grpc-gateway/issues/491) -- all SubConns are in TransientFailure [\#490](https://github.com/grpc-ecosystem/grpc-gateway/issues/490) -- Appengine Standard Environment: "not an Appengine context" [\#487](https://github.com/grpc-ecosystem/grpc-gateway/issues/487) -- Enum Path Parameter to Swagger [\#486](https://github.com/grpc-ecosystem/grpc-gateway/issues/486) -- Should v1.3 be also tagged as v1.3.0? [\#483](https://github.com/grpc-ecosystem/grpc-gateway/issues/483) -- HTTP response is not correct json encoded if the grpc return stream of objects. [\#481](https://github.com/grpc-ecosystem/grpc-gateway/issues/481) -- Support JSON-RPCv2 [\#477](https://github.com/grpc-ecosystem/grpc-gateway/issues/477) -- Naming convention? [\#475](https://github.com/grpc-ecosystem/grpc-gateway/issues/475) -- Request context not being used [\#470](https://github.com/grpc-ecosystem/grpc-gateway/issues/470) -- Generate Swagger documentation [\#469](https://github.com/grpc-ecosystem/grpc-gateway/issues/469) -- Support Request | make: swagger-codegen: Command not found [\#468](https://github.com/grpc-ecosystem/grpc-gateway/issues/468) -- How do you generate a swagger yaml file instead of json? [\#467](https://github.com/grpc-ecosystem/grpc-gateway/issues/467) -- Add default support for proto over http [\#465](https://github.com/grpc-ecosystem/grpc-gateway/issues/465) -- Allow compiling the gateway code to a different go package [\#463](https://github.com/grpc-ecosystem/grpc-gateway/issues/463) -- support google.api.HttpBody [\#457](https://github.com/grpc-ecosystem/grpc-gateway/issues/457) -- \[swagger bug\] with google/protobuf/wrappers.proto [\#453](https://github.com/grpc-ecosystem/grpc-gateway/issues/453) -- The tensorflow serving support RESTful api:{"error":"json: cannot unmarshal object into Go value of type \[\]json.RawMessage","code":3} [\#444](https://github.com/grpc-ecosystem/grpc-gateway/issues/444) -- choose some return fields omit or not omit by configure [\#439](https://github.com/grpc-ecosystem/grpc-gateway/issues/439) -- swagger title and version hardcoded [\#437](https://github.com/grpc-ecosystem/grpc-gateway/issues/437) -- Change the path though http header [\#424](https://github.com/grpc-ecosystem/grpc-gateway/issues/424) -- google/protobuf/descriptor.proto: File not found [\#422](https://github.com/grpc-ecosystem/grpc-gateway/issues/422) -- Output file will not compile if the .proto file does not contain a service with parameters in the url path [\#389](https://github.com/grpc-ecosystem/grpc-gateway/issues/389) -- Scaling support [\#381](https://github.com/grpc-ecosystem/grpc-gateway/issues/381) -- I cannot get the default value from client side [\#380](https://github.com/grpc-ecosystem/grpc-gateway/issues/380) -- Problem with Generated annotations.proto file [\#377](https://github.com/grpc-ecosystem/grpc-gateway/issues/377) -- Release 1.3.0 [\#357](https://github.com/grpc-ecosystem/grpc-gateway/issues/357) -- swagger: Unclear comments' parser behaviour [\#352](https://github.com/grpc-ecosystem/grpc-gateway/issues/352) -- Support semicolon syntax in go\_package protobuf option [\#341](https://github.com/grpc-ecosystem/grpc-gateway/issues/341) -- Add SOAP proxy [\#339](https://github.com/grpc-ecosystem/grpc-gateway/issues/339) -- Support combination of query params and body for POSTs [\#234](https://github.com/grpc-ecosystem/grpc-gateway/issues/234) -- Interceptor [\#221](https://github.com/grpc-ecosystem/grpc-gateway/issues/221) - -**Merged pull requests:** - -- Add support for --Import\_path [\#507](https://github.com/grpc-ecosystem/grpc-gateway/pull/507) ([achew22](https://github.com/achew22)) -- Fix \#504 Missing Definitions [\#505](https://github.com/grpc-ecosystem/grpc-gateway/pull/505) ([warmans](https://github.com/warmans)) -- Maintain default delimiter of newline [\#497](https://github.com/grpc-ecosystem/grpc-gateway/pull/497) ([jacksontj](https://github.com/jacksontj)) -- Fix gen-swagger to support more well known types [\#496](https://github.com/grpc-ecosystem/grpc-gateway/pull/496) ([shouichi](https://github.com/shouichi)) -- Use golang/protobuf instead of gogo/protobuf [\#494](https://github.com/grpc-ecosystem/grpc-gateway/pull/494) ([shouichi](https://github.com/shouichi)) -- Fix stream delimiters [\#488](https://github.com/grpc-ecosystem/grpc-gateway/pull/488) ([afking](https://github.com/afking)) -- ForwardResponseStream status code errors [\#482](https://github.com/grpc-ecosystem/grpc-gateway/pull/482) ([afking](https://github.com/afking)) -- protoc-gen-grpc-gateway: flip request\_context default to true [\#474](https://github.com/grpc-ecosystem/grpc-gateway/pull/474) ([srenatus](https://github.com/srenatus)) -- grpc-gateway/generator: respect full package [\#462](https://github.com/grpc-ecosystem/grpc-gateway/pull/462) ([glerchundi](https://github.com/glerchundi)) -- Add proto marshaller for proto-over-http [\#459](https://github.com/grpc-ecosystem/grpc-gateway/pull/459) ([MatthewDolan](https://github.com/MatthewDolan)) - -## [v1.3.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3.0) (2017-11-03) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.3...v1.3.0) - -## [v1.3](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.3) (2017-11-03) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.2.2...v1.3) - -**Closed issues:** - -- Extract basic auth from URL [\#480](https://github.com/grpc-ecosystem/grpc-gateway/issues/480) -- Lack of "google/protobuf/descriptor.proto" [\#476](https://github.com/grpc-ecosystem/grpc-gateway/issues/476) -- question: how to indicate whether call is through grpc gateway [\#456](https://github.com/grpc-ecosystem/grpc-gateway/issues/456) -- How to define this restful api using pb? [\#452](https://github.com/grpc-ecosystem/grpc-gateway/issues/452) -- how to output field as an array of json values? [\#449](https://github.com/grpc-ecosystem/grpc-gateway/issues/449) -- How do I override maxMsgSize? [\#445](https://github.com/grpc-ecosystem/grpc-gateway/issues/445) -- OpenAPI spec is generated with duplicated operation IDs. [\#442](https://github.com/grpc-ecosystem/grpc-gateway/issues/442) -- This process seems to generate conflicting code with go-micro [\#440](https://github.com/grpc-ecosystem/grpc-gateway/issues/440) -- any way to let int64 marshal to int not string? [\#438](https://github.com/grpc-ecosystem/grpc-gateway/issues/438) -- Support streaming [\#435](https://github.com/grpc-ecosystem/grpc-gateway/issues/435) -- Update DO NOT EDIT header in generated files [\#433](https://github.com/grpc-ecosystem/grpc-gateway/issues/433) -- generate code use context not "golang.org/x/net/context" [\#430](https://github.com/grpc-ecosystem/grpc-gateway/issues/430) -- Replace \n with spaces in swagger definitions [\#426](https://github.com/grpc-ecosystem/grpc-gateway/issues/426) -- \[question\]Is there any example for http headers process? [\#420](https://github.com/grpc-ecosystem/grpc-gateway/issues/420) -- Is there any way to support a multipart form request? [\#410](https://github.com/grpc-ecosystem/grpc-gateway/issues/410) -- Not able to pass allow\_delete\_body to protoc-gen-grpc-gateway. [\#402](https://github.com/grpc-ecosystem/grpc-gateway/issues/402) -- returned errors should conform to google.rpc.Status [\#399](https://github.com/grpc-ecosystem/grpc-gateway/issues/399) -- Is there any way to generate python gateway code? [\#398](https://github.com/grpc-ecosystem/grpc-gateway/issues/398) -- how to handle arbitrary \(json\) structs [\#395](https://github.com/grpc-ecosystem/grpc-gateway/issues/395) -- \[question\]can give a url with query sting demo? [\#394](https://github.com/grpc-ecosystem/grpc-gateway/issues/394) -- \[question\]the swagger url generated is what? [\#393](https://github.com/grpc-ecosystem/grpc-gateway/issues/393) -- \[Question\] How do I use semantic versions? [\#392](https://github.com/grpc-ecosystem/grpc-gateway/issues/392) -- \[question\]how to run examples? [\#391](https://github.com/grpc-ecosystem/grpc-gateway/issues/391) -- Why does gateway use ServerMetadata? [\#388](https://github.com/grpc-ecosystem/grpc-gateway/issues/388) -- Can't generate code with last version [\#384](https://github.com/grpc-ecosystem/grpc-gateway/issues/384) -- is it ready for production use? [\#382](https://github.com/grpc-ecosystem/grpc-gateway/issues/382) -- Support Google Flatbuffers [\#376](https://github.com/grpc-ecosystem/grpc-gateway/issues/376) -- calling Enum by string name in requests using gogo/protobuf results in error. [\#372](https://github.com/grpc-ecosystem/grpc-gateway/issues/372) -- Definitions containing URLs with trailing slashes won't compile [\#370](https://github.com/grpc-ecosystem/grpc-gateway/issues/370) -- Should metadata annotator include the headers from incoming matcher? [\#368](https://github.com/grpc-ecosystem/grpc-gateway/issues/368) -- metadata.NewOutgoingContext is undefined [\#364](https://github.com/grpc-ecosystem/grpc-gateway/issues/364) -- Why does not gateway forward headers as-is? [\#311](https://github.com/grpc-ecosystem/grpc-gateway/issues/311) -- Question: Why passing context to RegisterMyServiceHandler is required? [\#301](https://github.com/grpc-ecosystem/grpc-gateway/issues/301) -- Allow whitelisting of particular HTTP headers to map to metadata. [\#253](https://github.com/grpc-ecosystem/grpc-gateway/issues/253) -- Swagger definitions don't handle parameters that are not explicitly required in the url [\#159](https://github.com/grpc-ecosystem/grpc-gateway/issues/159) - -**Merged pull requests:** - -- Fix wrong method names [\#603](https://github.com/grpc-ecosystem/grpc-gateway/pull/603) ([yugui](https://github.com/yugui)) -- Streaming forward handler fix chunk encoding [\#479](https://github.com/grpc-ecosystem/grpc-gateway/pull/479) ([afking](https://github.com/afking)) -- Fix logic handling primitive wrapper in URL params [\#478](https://github.com/grpc-ecosystem/grpc-gateway/pull/478) ([tgeng](https://github.com/tgeng)) -- runtime: use r.Context\(\) [\#473](https://github.com/grpc-ecosystem/grpc-gateway/pull/473) ([srenatus](https://github.com/srenatus)) -- Optional SourceCodeInfo [\#466](https://github.com/grpc-ecosystem/grpc-gateway/pull/466) ([afking](https://github.com/afking)) -- Some steps to fix Travis CI [\#461](https://github.com/grpc-ecosystem/grpc-gateway/pull/461) ([AlekSi](https://github.com/AlekSi)) -- fix 2 typos in Registry.SetPrefix's comment [\#455](https://github.com/grpc-ecosystem/grpc-gateway/pull/455) ([hectorj](https://github.com/hectorj)) -- Add Handler method to pass in client [\#454](https://github.com/grpc-ecosystem/grpc-gateway/pull/454) ([jacksontj](https://github.com/jacksontj)) -- Fallback to JSON name when matching URL parameter. [\#450](https://github.com/grpc-ecosystem/grpc-gateway/pull/450) ([tgeng](https://github.com/tgeng)) -- Update DO NOT EDIT template. [\#434](https://github.com/grpc-ecosystem/grpc-gateway/pull/434) ([AlekSi](https://github.com/AlekSi)) -- Memoise calls to fullyQualifiedNameToSwaggerName to speed it up for large registries [\#421](https://github.com/grpc-ecosystem/grpc-gateway/pull/421) ([peterebden](https://github.com/peterebden)) -- Update Swagger Codegen from 2.1.6 to 2.2.2 [\#415](https://github.com/grpc-ecosystem/grpc-gateway/pull/415) ([yugui](https://github.com/yugui)) -- Return codes.InvalidArgument to rather return HTTP 400 instead of HTTP 500 [\#409](https://github.com/grpc-ecosystem/grpc-gateway/pull/409) ([vaporz](https://github.com/vaporz)) -- improve {incoming,outgoing}HeaderMatcher logic [\#408](https://github.com/grpc-ecosystem/grpc-gateway/pull/408) ([flisky](https://github.com/flisky)) -- improve WKT handling in gateway and openapi output [\#404](https://github.com/grpc-ecosystem/grpc-gateway/pull/404) ([tmc](https://github.com/tmc)) -- Return if runtime.AnnotateContext gave error [\#403](https://github.com/grpc-ecosystem/grpc-gateway/pull/403) ([tamalsaha](https://github.com/tamalsaha)) -- jsonpb: update tests to reflect new jsonpb behavior [\#401](https://github.com/grpc-ecosystem/grpc-gateway/pull/401) ([tmc](https://github.com/tmc)) -- Reference import grpc Status to suppress unused errors. [\#387](https://github.com/grpc-ecosystem/grpc-gateway/pull/387) ([tamalsaha](https://github.com/tamalsaha)) -- ci: regen with current protoc-gen-go [\#385](https://github.com/grpc-ecosystem/grpc-gateway/pull/385) ([tmc](https://github.com/tmc)) -- Use status package for error and introduce WithProtoErrorHandler option [\#378](https://github.com/grpc-ecosystem/grpc-gateway/pull/378) ([kazegusuri](https://github.com/kazegusuri)) -- Return response headers from grpc server [\#374](https://github.com/grpc-ecosystem/grpc-gateway/pull/374) ([tamalsaha](https://github.com/tamalsaha)) -- Skip unreferenced messages in definitions. [\#371](https://github.com/grpc-ecosystem/grpc-gateway/pull/371) ([Lantame](https://github.com/Lantame)) -- Use canonical header form in default header matcher. [\#369](https://github.com/grpc-ecosystem/grpc-gateway/pull/369) ([tamalsaha](https://github.com/tamalsaha)) -- support allow\_delete\_body for protoc-gen-grpc-gateway [\#318](https://github.com/grpc-ecosystem/grpc-gateway/pull/318) ([flisky](https://github.com/flisky)) -- fixes package name override doesn't work [\#277](https://github.com/grpc-ecosystem/grpc-gateway/pull/277) ([favadi](https://github.com/favadi)) -- add custom options to allow more control of swagger/openapi output [\#145](https://github.com/grpc-ecosystem/grpc-gateway/pull/145) ([ivucica](https://github.com/ivucica)) - -## [v1.2.2](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.2) (2017-04-17) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.2.1...v1.2.2) - -**Merged pull requests:** - -- Add changelog for 1.2.2 [\#363](https://github.com/grpc-ecosystem/grpc-gateway/pull/363) ([tmc](https://github.com/tmc)) -- metadata: fix properly and change to Outgoing [\#361](https://github.com/grpc-ecosystem/grpc-gateway/pull/361) ([tmc](https://github.com/tmc)) - -## [v1.2.1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.1) (2017-04-17) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.2.0...v1.2.1) - -**Fixed bugs:** - -- reflect upstream grpc metadata api change [\#358](https://github.com/grpc-ecosystem/grpc-gateway/issues/358) - -**Closed issues:** - -- Empty value omitted [\#355](https://github.com/grpc-ecosystem/grpc-gateway/issues/355) -- Must generate reverse proxy in same package? [\#353](https://github.com/grpc-ecosystem/grpc-gateway/issues/353) -- Release 1.2.0 [\#340](https://github.com/grpc-ecosystem/grpc-gateway/issues/340) -- Cut another release [\#278](https://github.com/grpc-ecosystem/grpc-gateway/issues/278) - -**Merged pull requests:** - -- Add changelog for 1.2.1 [\#360](https://github.com/grpc-ecosystem/grpc-gateway/pull/360) ([tmc](https://github.com/tmc)) -- bugfix: reflect upstream api change. [\#359](https://github.com/grpc-ecosystem/grpc-gateway/pull/359) ([tmc](https://github.com/tmc)) - -## [v1.2.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.0) (2017-03-31) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.2.0.rc1...v1.2.0) - -**Closed issues:** - -- Problem with \*.proto as "no buildable Go source files" [\#338](https://github.com/grpc-ecosystem/grpc-gateway/issues/338) -- Invalid import during code generation [\#337](https://github.com/grpc-ecosystem/grpc-gateway/issues/337) - -**Merged pull requests:** - -- Add changelog for 1.2.0 [\#342](https://github.com/grpc-ecosystem/grpc-gateway/pull/342) ([tmc](https://github.com/tmc)) - -## [v1.2.0.rc1](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.2.0.rc1) (2017-03-24) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.1.0...v1.2.0.rc1) - -**Implemented enhancements:** - -- Support for Any types [\#80](https://github.com/grpc-ecosystem/grpc-gateway/issues/80) -- improve\(genswagger:template\):added support for google.protobuf.Timestamp [\#209](https://github.com/grpc-ecosystem/grpc-gateway/pull/209) ([EranAvidor](https://github.com/EranAvidor)) - -**Fixed bugs:** - -- Support for multi-segment elements [\#122](https://github.com/grpc-ecosystem/grpc-gateway/issues/122) - -**Closed issues:** - -- Go get breaks with autogenerated code [\#331](https://github.com/grpc-ecosystem/grpc-gateway/issues/331) -- Fresh install no longer generates necessary `google/api/annotations.pb.go` & `google/api/http.pb.go` files. [\#327](https://github.com/grpc-ecosystem/grpc-gateway/issues/327) -- Panic with query parameters [\#324](https://github.com/grpc-ecosystem/grpc-gateway/issues/324) -- Swagger-UI query parameters for enum types are sent as strings [\#320](https://github.com/grpc-ecosystem/grpc-gateway/issues/320) -- hide the object name in the response [\#317](https://github.com/grpc-ecosystem/grpc-gateway/issues/317) -- Package imported but not used [\#310](https://github.com/grpc-ecosystem/grpc-gateway/issues/310) -- Authorization headers aren't specified in Swagger.json [\#309](https://github.com/grpc-ecosystem/grpc-gateway/issues/309) -- Generating swagger version, contact name etc in generated docs [\#303](https://github.com/grpc-ecosystem/grpc-gateway/issues/303) -- Feature request: custom content type per service and rpc [\#302](https://github.com/grpc-ecosystem/grpc-gateway/issues/302) -- Reference: another RESTful api-gateway [\#299](https://github.com/grpc-ecosystem/grpc-gateway/issues/299) -- Integration with other languages is partially broken [\#298](https://github.com/grpc-ecosystem/grpc-gateway/issues/298) -- jsonpb convert int64 to integer instead of string [\#296](https://github.com/grpc-ecosystem/grpc-gateway/issues/296) -- default enum value is omitted [\#294](https://github.com/grpc-ecosystem/grpc-gateway/issues/294) -- Advice: could we simplify the flow as the below [\#292](https://github.com/grpc-ecosystem/grpc-gateway/issues/292) -- examples/browser test failure: TypeError: undefined is not a function \(evaluating 'window.location.protocol.startsWith\('chrome-extension'\)'\) [\#287](https://github.com/grpc-ecosystem/grpc-gateway/issues/287) -- ./entrypoint.go:25: undefined: api.RegisterYourServiceHandlerFromEndpoint [\#285](https://github.com/grpc-ecosystem/grpc-gateway/issues/285) -- Query params not handled in swagger file [\#284](https://github.com/grpc-ecosystem/grpc-gateway/issues/284) -- Please help: google/api/annotations.proto: File not found. [\#283](https://github.com/grpc-ecosystem/grpc-gateway/issues/283) -- Option to Allow Swagger for DELETEs with a body [\#279](https://github.com/grpc-ecosystem/grpc-gateway/issues/279) -- client declared and not used compilation error, after recent upgrade [\#276](https://github.com/grpc-ecosystem/grpc-gateway/issues/276) -- feature request / idea: generating JSONRPC2 client proxies from GRPC [\#272](https://github.com/grpc-ecosystem/grpc-gateway/issues/272) -- protoc-swagger-generator messes up the comments if there is rpc method that does not have rest [\#263](https://github.com/grpc-ecosystem/grpc-gateway/issues/263) -- Swagger Gen: underscores -\> lowerCamelCase field names and refs [\#261](https://github.com/grpc-ecosystem/grpc-gateway/issues/261) -- Timestamp as URL param causes bad request error [\#260](https://github.com/grpc-ecosystem/grpc-gateway/issues/260) -- "proto: no coders for int" printed whenever a gRPC error is returned over grpc-gateway. [\#259](https://github.com/grpc-ecosystem/grpc-gateway/issues/259) -- Compatibility with grpc.SupportPackageIsVersion4 [\#258](https://github.com/grpc-ecosystem/grpc-gateway/issues/258) -- How to use circuit breaker in this grpc gateway? [\#257](https://github.com/grpc-ecosystem/grpc-gateway/issues/257) -- cannot use example code to generate [\#255](https://github.com/grpc-ecosystem/grpc-gateway/issues/255) -- tests fail on go tip due to importing of main packages in test [\#250](https://github.com/grpc-ecosystem/grpc-gateway/issues/250) -- Add NGINX support [\#249](https://github.com/grpc-ecosystem/grpc-gateway/issues/249) -- Error when reverse proxy to gRPC server \(which is impl with Node.js\) [\#246](https://github.com/grpc-ecosystem/grpc-gateway/issues/246) -- Error output titlecase instead of lowercase [\#243](https://github.com/grpc-ecosystem/grpc-gateway/issues/243) -- Option field "\(google.api.http\)" is not a field or extension of message "ServiceOptions" [\#241](https://github.com/grpc-ecosystem/grpc-gateway/issues/241) -- Implement credentials handler in-box [\#238](https://github.com/grpc-ecosystem/grpc-gateway/issues/238) -- Proposal: Support WKT structs for URL params [\#237](https://github.com/grpc-ecosystem/grpc-gateway/issues/237) -- Example of /} in path template [\#232](https://github.com/grpc-ecosystem/grpc-gateway/issues/232) -- Serving swagger.json from runtime mux? [\#230](https://github.com/grpc-ecosystem/grpc-gateway/issues/230) -- ETCDclientv3 build error with the latest changes - github.com/grpc-ecosystem/grpc-gateway/runtime/marshal\_jsonpb.go:114: undefined: jsonpb.Unmarshaler [\#226](https://github.com/grpc-ecosystem/grpc-gateway/issues/226) -- Map in GET request [\#223](https://github.com/grpc-ecosystem/grpc-gateway/issues/223) -- HTTPS no longer works [\#220](https://github.com/grpc-ecosystem/grpc-gateway/issues/220) -- --swagger\_out plugin translates proto type int64 to string in Swagger specification [\#219](https://github.com/grpc-ecosystem/grpc-gateway/issues/219) -- Response body as a single field [\#217](https://github.com/grpc-ecosystem/grpc-gateway/issues/217) -- documentation of semantics of endpoint declarations [\#212](https://github.com/grpc-ecosystem/grpc-gateway/issues/212) -- gen-swagger does not generate PATCH method endpoints [\#211](https://github.com/grpc-ecosystem/grpc-gateway/issues/211) -- protoc-gen-grpc-gateway doesn't work correctly with option go\_package [\#207](https://github.com/grpc-ecosystem/grpc-gateway/issues/207) -- Browser Side Streaming Best Practices [\#206](https://github.com/grpc-ecosystem/grpc-gateway/issues/206) -- Does grpc-gateway support App Engine? [\#204](https://github.com/grpc-ecosystem/grpc-gateway/issues/204) -- "use of internal package" error, after moving to grpc-ecosystem [\#203](https://github.com/grpc-ecosystem/grpc-gateway/issues/203) -- Move to google.golang.org/genproto instead of shipping annotations.proto. [\#202](https://github.com/grpc-ecosystem/grpc-gateway/issues/202) -- Release v1.1.0 [\#196](https://github.com/grpc-ecosystem/grpc-gateway/issues/196) -- marshaler runtime.Marshaler does not handle io.EOF when decoding [\#195](https://github.com/grpc-ecosystem/grpc-gateway/issues/195) -- protobuf enumerated values now returned as strings instead of numbers. [\#186](https://github.com/grpc-ecosystem/grpc-gateway/issues/186) -- support annotating fields as required \(in swagger/oapi generation\)? [\#175](https://github.com/grpc-ecosystem/grpc-gateway/issues/175) -- architectural question: Can i codegen the client code for talking to the server ? [\#167](https://github.com/grpc-ecosystem/grpc-gateway/issues/167) -- Passing ENUM value as URL parameter throws error [\#166](https://github.com/grpc-ecosystem/grpc-gateway/issues/166) -- Support specifying which schemes should be output in swagger.json [\#161](https://github.com/grpc-ecosystem/grpc-gateway/issues/161) -- Use headers for routing [\#157](https://github.com/grpc-ecosystem/grpc-gateway/issues/157) -- ENUM in swagger.json makes client code failed to parse response from gateway [\#153](https://github.com/grpc-ecosystem/grpc-gateway/issues/153) -- Support map types [\#140](https://github.com/grpc-ecosystem/grpc-gateway/issues/140) -- generate OpenAPI/swagger documentation at run time? [\#138](https://github.com/grpc-ecosystem/grpc-gateway/issues/138) -- After the 1.7 release, update .travis.yaml to check the compiled proto output [\#137](https://github.com/grpc-ecosystem/grpc-gateway/issues/137) -- Getting parsed runtime.Pattern from server mux [\#127](https://github.com/grpc-ecosystem/grpc-gateway/issues/127) -- REST API without proxying [\#46](https://github.com/grpc-ecosystem/grpc-gateway/issues/46) - -**Merged pull requests:** - -- Remove an obsolete custom option [\#604](https://github.com/grpc-ecosystem/grpc-gateway/pull/604) ([yugui](https://github.com/yugui)) -- Support user configurable header forwarding & context metadata [\#336](https://github.com/grpc-ecosystem/grpc-gateway/pull/336) ([tamalsaha](https://github.com/tamalsaha)) -- Update go\_out parameter to remove comma [\#333](https://github.com/grpc-ecosystem/grpc-gateway/pull/333) ([tmc](https://github.com/tmc)) -- Update stale path in README [\#332](https://github.com/grpc-ecosystem/grpc-gateway/pull/332) ([tmc](https://github.com/tmc)) -- improve documentation regarding external dependencies [\#330](https://github.com/grpc-ecosystem/grpc-gateway/pull/330) ([CaptTofu](https://github.com/CaptTofu)) -- Return an error on invalid nested query parameters. [\#329](https://github.com/grpc-ecosystem/grpc-gateway/pull/329) ([fische](https://github.com/fische)) -- Update upstream proto files and add google.golang.org/genproto support. [\#325](https://github.com/grpc-ecosystem/grpc-gateway/pull/325) ([tmc](https://github.com/tmc)) -- Support oneof fields in query params [\#321](https://github.com/grpc-ecosystem/grpc-gateway/pull/321) ([nilium](https://github.com/nilium)) -- Do not ignore the error coming from http.ListenAndServe in examples [\#319](https://github.com/grpc-ecosystem/grpc-gateway/pull/319) ([campoy](https://github.com/campoy)) -- Look up enum value maps by their proto name [\#315](https://github.com/grpc-ecosystem/grpc-gateway/pull/315) ([nilium](https://github.com/nilium)) -- enable parsing enums from query parameters [\#314](https://github.com/grpc-ecosystem/grpc-gateway/pull/314) ([tzneal](https://github.com/tzneal)) -- Do not add imports from methods with no bindings. [\#312](https://github.com/grpc-ecosystem/grpc-gateway/pull/312) ([fische](https://github.com/fische)) -- Convert the first letter of method name to upper [\#300](https://github.com/grpc-ecosystem/grpc-gateway/pull/300) ([lipixun](https://github.com/lipixun)) -- write query parameters to swagger definition [\#297](https://github.com/grpc-ecosystem/grpc-gateway/pull/297) ([t-yuki](https://github.com/t-yuki)) -- Bump swagger-client to 2.1.28 for examples/browser [\#290](https://github.com/grpc-ecosystem/grpc-gateway/pull/290) ([tmc](https://github.com/tmc)) -- pin to version before es6ism [\#289](https://github.com/grpc-ecosystem/grpc-gateway/pull/289) ([tmc](https://github.com/tmc)) -- Prevent lack of http bindings from generating non-building output [\#286](https://github.com/grpc-ecosystem/grpc-gateway/pull/286) ([tmc](https://github.com/tmc)) -- Added support for Timestamp in URL. [\#281](https://github.com/grpc-ecosystem/grpc-gateway/pull/281) ([johansja](https://github.com/johansja)) -- add plugin param 'allow\_delete\_body' [\#280](https://github.com/grpc-ecosystem/grpc-gateway/pull/280) ([msample](https://github.com/msample)) -- Fix ruby gen command [\#275](https://github.com/grpc-ecosystem/grpc-gateway/pull/275) ([bluehallu](https://github.com/bluehallu)) -- Make grpc-gateway support enum fields in path parameter [\#273](https://github.com/grpc-ecosystem/grpc-gateway/pull/273) ([linuxerwang](https://github.com/linuxerwang)) -- remove unnecessary make\(\) [\#271](https://github.com/grpc-ecosystem/grpc-gateway/pull/271) ([tmc](https://github.com/tmc)) -- preserve field order in swagger spec [\#270](https://github.com/grpc-ecosystem/grpc-gateway/pull/270) ([tmc](https://github.com/tmc)) -- Merge \#228 [\#268](https://github.com/grpc-ecosystem/grpc-gateway/pull/268) ([tmc](https://github.com/tmc)) -- Handle methods with no bindings more carefully [\#267](https://github.com/grpc-ecosystem/grpc-gateway/pull/267) ([tmc](https://github.com/tmc)) -- describe default marshaler in README.md [\#266](https://github.com/grpc-ecosystem/grpc-gateway/pull/266) ([tmc](https://github.com/tmc)) -- Add request\_context flag to utilize \(\*http.Request\).Context\(\) in handlers [\#265](https://github.com/grpc-ecosystem/grpc-gateway/pull/265) ([tmc](https://github.com/tmc)) -- Regenerate examples [\#264](https://github.com/grpc-ecosystem/grpc-gateway/pull/264) ([tmc](https://github.com/tmc)) -- Correct runtime.errorBody protobuf field tag [\#256](https://github.com/grpc-ecosystem/grpc-gateway/pull/256) ([tmc](https://github.com/tmc)) -- Pass permanent HTTP request headers [\#252](https://github.com/grpc-ecosystem/grpc-gateway/pull/252) ([tmc](https://github.com/tmc)) -- regenerate examples, fix tests for go tip [\#248](https://github.com/grpc-ecosystem/grpc-gateway/pull/248) ([tmc](https://github.com/tmc)) -- Render the swagger request body properly [\#247](https://github.com/grpc-ecosystem/grpc-gateway/pull/247) ([dprotaso](https://github.com/dprotaso)) -- Error output should have lowercase attribute names [\#244](https://github.com/grpc-ecosystem/grpc-gateway/pull/244) ([nathanborror](https://github.com/nathanborror)) -- runtime - export prefix constants [\#236](https://github.com/grpc-ecosystem/grpc-gateway/pull/236) ([philipithomas](https://github.com/philipithomas)) -- README - Add CoreOS example [\#231](https://github.com/grpc-ecosystem/grpc-gateway/pull/231) ([philipithomas](https://github.com/philipithomas)) -- Docs - Add section about how HTTP maps to gRPC [\#227](https://github.com/grpc-ecosystem/grpc-gateway/pull/227) ([philipithomas](https://github.com/philipithomas)) -- readme: added links to additional documentation [\#222](https://github.com/grpc-ecosystem/grpc-gateway/pull/222) ([sdemos](https://github.com/sdemos)) -- Use a released version of protoc [\#216](https://github.com/grpc-ecosystem/grpc-gateway/pull/216) ([yugui](https://github.com/yugui)) -- Add contribution guideline [\#210](https://github.com/grpc-ecosystem/grpc-gateway/pull/210) ([yugui](https://github.com/yugui)) -- Allowing unknown fields to be dropped instead of returning error from… [\#208](https://github.com/grpc-ecosystem/grpc-gateway/pull/208) ([sriniven](https://github.com/sriniven)) -- Avoid Internal Server Error on zero-length input for bidi streaming [\#200](https://github.com/grpc-ecosystem/grpc-gateway/pull/200) ([yugui](https://github.com/yugui)) - -## [v1.1.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.1.0) (2016-07-23) -[Full Changelog](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/compare/v1.0.0...v1.1.0) - -**Implemented enhancements:** - -- Support oneof types of fields [\#82](https://github.com/grpc-ecosystem/grpc-gateway/issues/82) -- allow use of jsonpb for marshaling [\#79](https://github.com/grpc-ecosystem/grpc-gateway/issues/79) - -**Closed issues:** - -- Generating a gRPC stub using Gateway generates a gRPC internal error [\#198](https://github.com/grpc-ecosystem/grpc-gateway/issues/198) -- Build fails with error: use of internal package not allowed [\#197](https://github.com/grpc-ecosystem/grpc-gateway/issues/197) -- google/protobuf/descriptor.proto: File not found. [\#194](https://github.com/grpc-ecosystem/grpc-gateway/issues/194) -- please tag releases [\#189](https://github.com/grpc-ecosystem/grpc-gateway/issues/189) -- Support for path collapsing for embedded structs? [\#187](https://github.com/grpc-ecosystem/grpc-gateway/issues/187) -- \[ACTION Required\] Moving to grpc-ecosystem [\#179](https://github.com/grpc-ecosystem/grpc-gateway/issues/179) -- Ading grpc-timeout support [\#107](https://github.com/grpc-ecosystem/grpc-gateway/issues/107) -- Generation of one swagger file out of multiple protos? [\#99](https://github.com/grpc-ecosystem/grpc-gateway/issues/99) - -**Merged pull requests:** - -- Rename packages to follow the repository transfer [\#192](https://github.com/grpc-ecosystem/grpc-gateway/pull/192) ([yugui](https://github.com/yugui)) -- return err early if EOF to prevent logging in normal conditions [\#191](https://github.com/grpc-ecosystem/grpc-gateway/pull/191) ([tmc](https://github.com/tmc)) -- send Trailer header on error [\#188](https://github.com/grpc-ecosystem/grpc-gateway/pull/188) ([kazegusuri](https://github.com/kazegusuri)) -- generate swagger output for streaming endpoints with a basic note [\#183](https://github.com/grpc-ecosystem/grpc-gateway/pull/183) ([tmc](https://github.com/tmc)) - -## [v1.0.0](https://grpc-ecosystem.github.io/grpc-gateway/grpc-ecosystem/grpc-gateway/tree/v1.0.0) (2016-06-15) -**Implemented enhancements:** - -- support protobuf-over-HTTP [\#124](https://github.com/grpc-ecosystem/grpc-gateway/issues/124) -- Static mapping from proto field names to golang field names [\#86](https://github.com/grpc-ecosystem/grpc-gateway/issues/86) -- Format Errors to JSON [\#25](https://github.com/grpc-ecosystem/grpc-gateway/issues/25) -- Emit API definition in Swagger schema format [\#9](https://github.com/grpc-ecosystem/grpc-gateway/issues/9) -- Method parameter in query string [\#6](https://github.com/grpc-ecosystem/grpc-gateway/issues/6) -- Integrate authentication [\#4](https://github.com/grpc-ecosystem/grpc-gateway/issues/4) -- Add swagger support [\#68](https://github.com/grpc-ecosystem/grpc-gateway/pull/68) ([achew22](https://github.com/achew22)) -- Add runtime.WithForwardResponseOption [\#53](https://github.com/grpc-ecosystem/grpc-gateway/pull/53) ([peter-edge](https://github.com/peter-edge)) - -**Fixed bugs:** - -- recent annotation change requires req.RemoteAddr to be populated [\#177](https://github.com/grpc-ecosystem/grpc-gateway/issues/177) -- Runtime panic with CloseNotify [\#115](https://github.com/grpc-ecosystem/grpc-gateway/issues/115) -- Gateway code generation broken when rpc method with a streaming response has an input paramter [\#35](https://github.com/grpc-ecosystem/grpc-gateway/issues/35) -- URL usage of nested messages causes nil pointer in proto3 [\#32](https://github.com/grpc-ecosystem/grpc-gateway/issues/32) -- Multiple .proto files generates invalid import statements. [\#22](https://github.com/grpc-ecosystem/grpc-gateway/issues/22) - -**Closed issues:** - -- remote peer address is lost in ctx - always resolves to localhost [\#173](https://github.com/grpc-ecosystem/grpc-gateway/issues/173) -- Bidirectional streams don't concurrently Send and Recv [\#169](https://github.com/grpc-ecosystem/grpc-gateway/issues/169) -- Error: failed to import google/api/annotations.proto [\#165](https://github.com/grpc-ecosystem/grpc-gateway/issues/165) -- Test datarace in controlapi [\#163](https://github.com/grpc-ecosystem/grpc-gateway/issues/163) -- not enough arguments in call to runtime.HTTPError [\#162](https://github.com/grpc-ecosystem/grpc-gateway/issues/162) -- String-values for Enums in request object are not recognized. [\#150](https://github.com/grpc-ecosystem/grpc-gateway/issues/150) -- Handling of import public "file.proto" [\#139](https://github.com/grpc-ecosystem/grpc-gateway/issues/139) -- Does grpc-gateway support http middleware? [\#132](https://github.com/grpc-ecosystem/grpc-gateway/issues/132) -- push to web clients using WS or SSE ? [\#131](https://github.com/grpc-ecosystem/grpc-gateway/issues/131) -- protoc-gen-swagger comment parsing for documentation gen [\#128](https://github.com/grpc-ecosystem/grpc-gateway/issues/128) -- generated code has a data race [\#123](https://github.com/grpc-ecosystem/grpc-gateway/issues/123) -- panic: net/http: CloseNotify called after ServeHTTP finished [\#121](https://github.com/grpc-ecosystem/grpc-gateway/issues/121) -- CloseNotify race with ServeHTTP [\#119](https://github.com/grpc-ecosystem/grpc-gateway/issues/119) -- echo service example does not compile [\#117](https://github.com/grpc-ecosystem/grpc-gateway/issues/117) -- go vet issues in template\_test.go [\#113](https://github.com/grpc-ecosystem/grpc-gateway/issues/113) -- undefined: proto.SizeVarint [\#103](https://github.com/grpc-ecosystem/grpc-gateway/issues/103) -- Closing the HTTP connection does not cancel the Context [\#101](https://github.com/grpc-ecosystem/grpc-gateway/issues/101) -- Logging [\#92](https://github.com/grpc-ecosystem/grpc-gateway/issues/92) -- Missing default values in JSON output? [\#91](https://github.com/grpc-ecosystem/grpc-gateway/issues/91) -- Better grpc error strings [\#87](https://github.com/grpc-ecosystem/grpc-gateway/issues/87) -- Fields aren't named in the same manner as golang/protobuf [\#84](https://github.com/grpc-ecosystem/grpc-gateway/issues/84) -- Header Forwarding from server. [\#73](https://github.com/grpc-ecosystem/grpc-gateway/issues/73) -- No pattern specified in google.api.HttpRule [\#70](https://github.com/grpc-ecosystem/grpc-gateway/issues/70) -- cannot find package "google/api" [\#67](https://github.com/grpc-ecosystem/grpc-gateway/issues/67) -- Generated .pb.go with services no longer works with latest version of grpc-go. [\#62](https://github.com/grpc-ecosystem/grpc-gateway/issues/62) -- JavaScript Proxy [\#61](https://github.com/grpc-ecosystem/grpc-gateway/issues/61) -- Add HTTP error code, error status to responseStreamChunk Error [\#58](https://github.com/grpc-ecosystem/grpc-gateway/issues/58) -- Reverse the code gen idea [\#44](https://github.com/grpc-ecosystem/grpc-gateway/issues/44) -- array of maps in json [\#43](https://github.com/grpc-ecosystem/grpc-gateway/issues/43) -- Examples break with 1.5 because of import of "main" examples package [\#37](https://github.com/grpc-ecosystem/grpc-gateway/issues/37) -- Breaks with 1.5rc1 due to "internal" package name. [\#36](https://github.com/grpc-ecosystem/grpc-gateway/issues/36) -- Feature Request: Support for non-nullable nested messages. [\#20](https://github.com/grpc-ecosystem/grpc-gateway/issues/20) -- Is PascalFromSnake the right conversion to be doing? [\#19](https://github.com/grpc-ecosystem/grpc-gateway/issues/19) -- Infinite loop in generator when package name conflicts [\#17](https://github.com/grpc-ecosystem/grpc-gateway/issues/17) -- google.api.http options in multi-line format not supported [\#16](https://github.com/grpc-ecosystem/grpc-gateway/issues/16) -- Is there any plan to developing a C++ version? [\#15](https://github.com/grpc-ecosystem/grpc-gateway/issues/15) - -**Merged pull requests:** - -- Regenerate files with the latest protoc-gen-go [\#185](https://github.com/grpc-ecosystem/grpc-gateway/pull/185) ([yugui](https://github.com/yugui)) -- Add browser examples [\#184](https://github.com/grpc-ecosystem/grpc-gateway/pull/184) ([yugui](https://github.com/yugui)) -- Fix golint and go vet errors [\#182](https://github.com/grpc-ecosystem/grpc-gateway/pull/182) ([yugui](https://github.com/yugui)) -- Add integration with clients generated by swagger-codegen [\#181](https://github.com/grpc-ecosystem/grpc-gateway/pull/181) ([yugui](https://github.com/yugui)) -- Simplify example services [\#180](https://github.com/grpc-ecosystem/grpc-gateway/pull/180) ([yugui](https://github.com/yugui)) -- Avoid errors when req.RemoteAddr is empty [\#178](https://github.com/grpc-ecosystem/grpc-gateway/pull/178) ([yugui](https://github.com/yugui)) -- Feature/headers [\#176](https://github.com/grpc-ecosystem/grpc-gateway/pull/176) ([yugui](https://github.com/yugui)) -- Include HTTP req.remoteAddr in gRPC ctx [\#174](https://github.com/grpc-ecosystem/grpc-gateway/pull/174) ([mikeatlas](https://github.com/mikeatlas)) -- Update dependencies [\#171](https://github.com/grpc-ecosystem/grpc-gateway/pull/171) ([yugui](https://github.com/yugui)) -- Add bidirectional streaming support by running Send\(\) and Recv\(\) concurrently [\#170](https://github.com/grpc-ecosystem/grpc-gateway/pull/170) ([tmc](https://github.com/tmc)) -- make Authorization header check case-insensitive to comply with RFC 2616 4.2 [\#164](https://github.com/grpc-ecosystem/grpc-gateway/pull/164) ([tmc](https://github.com/tmc)) -- jsonpb: avoid duplicating upstream's struct [\#158](https://github.com/grpc-ecosystem/grpc-gateway/pull/158) ([tamird](https://github.com/tamird)) -- Generate Swagger description for service methods using proto comments. [\#156](https://github.com/grpc-ecosystem/grpc-gateway/pull/156) ([t-yuki](https://github.com/t-yuki)) -- Implement gRPC timeout support for inbound HTTP headers [\#155](https://github.com/grpc-ecosystem/grpc-gateway/pull/155) ([mwitkow](https://github.com/mwitkow)) -- Add more examples to marshalers [\#154](https://github.com/grpc-ecosystem/grpc-gateway/pull/154) ([yugui](https://github.com/yugui)) -- custom marshaler: handle `Accept` headers correctly [\#152](https://github.com/grpc-ecosystem/grpc-gateway/pull/152) ([tamird](https://github.com/tamird)) -- Simplify custom marshaler API [\#151](https://github.com/grpc-ecosystem/grpc-gateway/pull/151) ([yugui](https://github.com/yugui)) -- Fix camel case path parameter handling in swagger [\#149](https://github.com/grpc-ecosystem/grpc-gateway/pull/149) ([yugui](https://github.com/yugui)) -- Swagger dot in path template [\#148](https://github.com/grpc-ecosystem/grpc-gateway/pull/148) ([yugui](https://github.com/yugui)) -- Support map types in swagger generator [\#147](https://github.com/grpc-ecosystem/grpc-gateway/pull/147) ([yugui](https://github.com/yugui)) -- Cleanup custom marshaler [\#146](https://github.com/grpc-ecosystem/grpc-gateway/pull/146) ([yugui](https://github.com/yugui)) -- Implement custom Marshaler support, add jsonpb implemention. [\#144](https://github.com/grpc-ecosystem/grpc-gateway/pull/144) ([tmc](https://github.com/tmc)) -- Allow period in path URL templates when generating Swagger templates. [\#143](https://github.com/grpc-ecosystem/grpc-gateway/pull/143) ([ivucica](https://github.com/ivucica)) -- Link to LICENSE.txt [\#142](https://github.com/grpc-ecosystem/grpc-gateway/pull/142) ([sunkuet02](https://github.com/sunkuet02)) -- Support map types in swagger generator [\#141](https://github.com/grpc-ecosystem/grpc-gateway/pull/141) ([t-yuki](https://github.com/t-yuki)) -- Conditionally stops checking if generated file are up-to-date [\#136](https://github.com/grpc-ecosystem/grpc-gateway/pull/136) ([yugui](https://github.com/yugui)) -- Generate Swagger description for service methods using proto comments. [\#134](https://github.com/grpc-ecosystem/grpc-gateway/pull/134) ([ivucica](https://github.com/ivucica)) -- Swagger definitions now have `type` set to `object`. [\#133](https://github.com/grpc-ecosystem/grpc-gateway/pull/133) ([ivucica](https://github.com/ivucica)) -- go\_package option as go import path [\#129](https://github.com/grpc-ecosystem/grpc-gateway/pull/129) ([kazegusuri](https://github.com/kazegusuri)) -- Fix govet errors [\#126](https://github.com/grpc-ecosystem/grpc-gateway/pull/126) ([yugui](https://github.com/yugui)) -- Fix data-race in generated codes [\#125](https://github.com/grpc-ecosystem/grpc-gateway/pull/125) ([yugui](https://github.com/yugui)) -- Fix \#119 - CloseNotify race with ServeHTTP [\#120](https://github.com/grpc-ecosystem/grpc-gateway/pull/120) ([cuongdo](https://github.com/cuongdo)) -- Replace glog with grpclog [\#118](https://github.com/grpc-ecosystem/grpc-gateway/pull/118) ([cuongdo](https://github.com/cuongdo)) -- Fix a goroutine-leak in HTTP keep-alive [\#116](https://github.com/grpc-ecosystem/grpc-gateway/pull/116) ([yugui](https://github.com/yugui)) -- Fix camel case path parameter handling in swagger [\#114](https://github.com/grpc-ecosystem/grpc-gateway/pull/114) ([t-yuki](https://github.com/t-yuki)) -- gofmt -s [\#112](https://github.com/grpc-ecosystem/grpc-gateway/pull/112) ([shawnps](https://github.com/shawnps)) -- fix typo [\#111](https://github.com/grpc-ecosystem/grpc-gateway/pull/111) ([shawnps](https://github.com/shawnps)) -- fix typo [\#110](https://github.com/grpc-ecosystem/grpc-gateway/pull/110) ([shawnps](https://github.com/shawnps)) -- fixes missing swagger operation objects [\#109](https://github.com/grpc-ecosystem/grpc-gateway/pull/109) ([t-yuki](https://github.com/t-yuki)) -- Add parser and swagger support for enum, no gengateway yet [\#108](https://github.com/grpc-ecosystem/grpc-gateway/pull/108) ([t-yuki](https://github.com/t-yuki)) -- README: add protoc-gen-swagger too [\#105](https://github.com/grpc-ecosystem/grpc-gateway/pull/105) ([philips](https://github.com/philips)) -- README: Suggest go get -u by default. [\#104](https://github.com/grpc-ecosystem/grpc-gateway/pull/104) ([shurcooL](https://github.com/shurcooL)) -- Cancel context when HTTP connection is closed [\#102](https://github.com/grpc-ecosystem/grpc-gateway/pull/102) ([floridoo](https://github.com/floridoo)) -- wait test server up [\#100](https://github.com/grpc-ecosystem/grpc-gateway/pull/100) ([kazegusuri](https://github.com/kazegusuri)) -- Fix the swagger section of the README.md [\#98](https://github.com/grpc-ecosystem/grpc-gateway/pull/98) ([naibaf0](https://github.com/naibaf0)) -- Add documentation for using Swagger [\#97](https://github.com/grpc-ecosystem/grpc-gateway/pull/97) ([achew22](https://github.com/achew22)) -- Better compatibility to field names generated by protoc-gen-go [\#96](https://github.com/grpc-ecosystem/grpc-gateway/pull/96) ([yugui](https://github.com/yugui)) -- Update protoc from 3.0.0-beta1 to 3.0.0-beta2 [\#95](https://github.com/grpc-ecosystem/grpc-gateway/pull/95) ([yugui](https://github.com/yugui)) -- Better grpc error strings [\#94](https://github.com/grpc-ecosystem/grpc-gateway/pull/94) ([floridoo](https://github.com/floridoo)) -- make available header and trailer metadata [\#93](https://github.com/grpc-ecosystem/grpc-gateway/pull/93) ([kazegusuri](https://github.com/kazegusuri)) -- make grpc.DialOption configurable [\#89](https://github.com/grpc-ecosystem/grpc-gateway/pull/89) ([kazegusuri](https://github.com/kazegusuri)) -- Add request in error handlers [\#88](https://github.com/grpc-ecosystem/grpc-gateway/pull/88) ([daniellowtw](https://github.com/daniellowtw)) -- Improve PascalFromSnake behavior [\#85](https://github.com/grpc-ecosystem/grpc-gateway/pull/85) ([tmc](https://github.com/tmc)) -- Typo grcp -\> grpc [\#81](https://github.com/grpc-ecosystem/grpc-gateway/pull/81) ([daniellowtw](https://github.com/daniellowtw)) -- Add abstraction of code generator implementation [\#78](https://github.com/grpc-ecosystem/grpc-gateway/pull/78) ([yugui](https://github.com/yugui)) -- Support multivalue of metadata [\#77](https://github.com/grpc-ecosystem/grpc-gateway/pull/77) ([yugui](https://github.com/yugui)) -- Fix broken test [\#76](https://github.com/grpc-ecosystem/grpc-gateway/pull/76) ([yugui](https://github.com/yugui)) -- Added missing instruction line in README [\#75](https://github.com/grpc-ecosystem/grpc-gateway/pull/75) ([betrcode](https://github.com/betrcode)) -- Fix a complie error in generated go files [\#71](https://github.com/grpc-ecosystem/grpc-gateway/pull/71) ([yugui](https://github.com/yugui)) -- Update generated .pb.go files in third\_party [\#69](https://github.com/grpc-ecosystem/grpc-gateway/pull/69) ([peter-edge](https://github.com/peter-edge)) -- Bugfix/handling headers for `Authorization` and `Host` [\#65](https://github.com/grpc-ecosystem/grpc-gateway/pull/65) ([mwitkow](https://github.com/mwitkow)) -- Fix `error` field always in chunk response [\#64](https://github.com/grpc-ecosystem/grpc-gateway/pull/64) ([mwitkow](https://github.com/mwitkow)) -- Update .pb.go to latest version. [\#63](https://github.com/grpc-ecosystem/grpc-gateway/pull/63) ([johansja](https://github.com/johansja)) -- Run more tests in Travis CI [\#60](https://github.com/grpc-ecosystem/grpc-gateway/pull/60) ([yugui](https://github.com/yugui)) -- Added http error code and error status for responseStreamChunk error [\#59](https://github.com/grpc-ecosystem/grpc-gateway/pull/59) ([kdima](https://github.com/kdima)) -- Fix parsing of verb and final path component. [\#55](https://github.com/grpc-ecosystem/grpc-gateway/pull/55) ([hbchai](https://github.com/hbchai)) -- add grpc.WithInsecure\(\) as option for grpc.Dial call in template [\#52](https://github.com/grpc-ecosystem/grpc-gateway/pull/52) ([peter-edge](https://github.com/peter-edge)) -- update .pb.go files for latest golang proto generation [\#51](https://github.com/grpc-ecosystem/grpc-gateway/pull/51) ([peter-edge](https://github.com/peter-edge)) -- Fix a build error with the latest protoc-gen-go [\#50](https://github.com/grpc-ecosystem/grpc-gateway/pull/50) ([yugui](https://github.com/yugui)) -- Configure Travis CI [\#49](https://github.com/grpc-ecosystem/grpc-gateway/pull/49) ([yugui](https://github.com/yugui)) -- Follow a change of go package name convention in protoc-gen-go [\#48](https://github.com/grpc-ecosystem/grpc-gateway/pull/48) ([yugui](https://github.com/yugui)) -- Consider tail segments after deep wildcard [\#47](https://github.com/grpc-ecosystem/grpc-gateway/pull/47) ([yugui](https://github.com/yugui)) -- Fix typo in README [\#45](https://github.com/grpc-ecosystem/grpc-gateway/pull/45) ([jonboulle](https://github.com/jonboulle)) -- Fix undefined variable error in generated codes [\#42](https://github.com/grpc-ecosystem/grpc-gateway/pull/42) ([yugui](https://github.com/yugui)) -- Follow changes in protoc-gen-go and grpc-go [\#41](https://github.com/grpc-ecosystem/grpc-gateway/pull/41) ([yugui](https://github.com/yugui)) -- Fixes \#4 [\#40](https://github.com/grpc-ecosystem/grpc-gateway/pull/40) ([AmandaCameron](https://github.com/AmandaCameron)) -- fix examples to work with go1.5 [\#39](https://github.com/grpc-ecosystem/grpc-gateway/pull/39) ([tmc](https://github.com/tmc)) -- rename internal to utilties for 1.5 compatibility [\#38](https://github.com/grpc-ecosystem/grpc-gateway/pull/38) ([tmc](https://github.com/tmc)) -- Reflection fix of proto3 nested messages. [\#34](https://github.com/grpc-ecosystem/grpc-gateway/pull/34) ([mwitkow](https://github.com/mwitkow)) -- \[Experimental\] Make the response forwarder function customizable [\#31](https://github.com/grpc-ecosystem/grpc-gateway/pull/31) ([yugui](https://github.com/yugui)) -- Add f.Flush\(\) to runtime.ForwardResponseStream [\#30](https://github.com/grpc-ecosystem/grpc-gateway/pull/30) ([vvakame](https://github.com/vvakame)) -- Format error message in JSON [\#29](https://github.com/grpc-ecosystem/grpc-gateway/pull/29) ([yugui](https://github.com/yugui)) -- Update examples with HTTP header context annotation [\#28](https://github.com/grpc-ecosystem/grpc-gateway/pull/28) ([yugui](https://github.com/yugui)) -- Report semantic errors in the source to protoc [\#27](https://github.com/grpc-ecosystem/grpc-gateway/pull/27) ([yugui](https://github.com/yugui)) -- Add support for non-nullable nested messages. [\#21](https://github.com/grpc-ecosystem/grpc-gateway/pull/21) ([shurcooL](https://github.com/shurcooL)) -- Receive GRPC metadata from HTTP headers. [\#18](https://github.com/grpc-ecosystem/grpc-gateway/pull/18) ([crast](https://github.com/crast)) -- Implement detailed specs of google.api.http [\#14](https://github.com/grpc-ecosystem/grpc-gateway/pull/14) ([yugui](https://github.com/yugui)) -- Configure travis CI [\#13](https://github.com/grpc-ecosystem/grpc-gateway/pull/13) ([yugui](https://github.com/yugui)) -- Replace our own custom option with the one defined by Google [\#12](https://github.com/grpc-ecosystem/grpc-gateway/pull/12) ([yugui](https://github.com/yugui)) -- Remove useless context setup [\#11](https://github.com/grpc-ecosystem/grpc-gateway/pull/11) ([iamqizhao](https://github.com/iamqizhao)) -- Fix typo, path, missing semicolon. [\#10](https://github.com/grpc-ecosystem/grpc-gateway/pull/10) ([shurcooL](https://github.com/shurcooL)) -- Use a globally unique id for the custom option [\#3](https://github.com/grpc-ecosystem/grpc-gateway/pull/3) ([yugui](https://github.com/yugui)) -- implement ABitOfEverythingService [\#2](https://github.com/grpc-ecosystem/grpc-gateway/pull/2) ([mattn](https://github.com/mattn)) -- support streaming API calls [\#1](https://github.com/grpc-ecosystem/grpc-gateway/pull/1) ([yugui](https://github.com/yugui)) - - - -\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md b/examples/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md deleted file mode 100755 index 4f0c59e..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# How to contribute - -Thank you for your contribution to grpc-gateway. -Here's the recommended process of contribution. - -1. `go get github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway` -2. `cd $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway` -3. hack, hack, hack... -4. Make sure that your change follows best practices in Go - * [Effective Go](https://golang.org/doc/effective_go.html) - * [Go Code Review Comments](https://golang.org/wiki/CodeReviewComments) -5. Make sure that `make test` passes. (use swagger-codegen 2.2.2, not newer versions) -6. Sign [a Contributor License Agreement](https://cla.developers.google.com/clas) -7. Open a pull request in Github - -When you work on a larger contribution, it is also recommended that you get in touch -with us through the issue tracker. - -### Code reviews -All submissions, including submissions by project members, require review. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/ISSUE_TEMPLATE.md b/examples/github.com/grpc-ecosystem/grpc-gateway/ISSUE_TEMPLATE.md deleted file mode 100755 index 9edbaa6..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Please follow the general troubleshooting steps first: - -- [ ] Update your protoc to the [latest version](https://github.com/google/protobuf/releases) -- [ ] Update your copy of `grpc-gateway` to the latest version from github. with - `git fetch https://github.com/grpc-ecosystem/grpc-gateway master && git reset --hard FETCH_HEAD` -- [ ] Delete the `protoc-gen-grpc-gateway` and `protoc-gen-swagger` binary from your `PATH`, - and install locally built binaries. - -### Bug reports: - -Fill in the following sections with explanations of what's gone wrong. - -Steps you follow to reproduce the error: - - - -Your steps here. - -What did you expect to happen instead: - - - -Your answer here. - -What's your theory on why it isn't working: - - - -Your theory here. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt b/examples/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt deleted file mode 100755 index 3645162..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2015, Gengo, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of Gengo, Inc. nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/Makefile b/examples/github.com/grpc-ecosystem/grpc-gateway/Makefile deleted file mode 100755 index a690bb7..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/Makefile +++ /dev/null @@ -1,206 +0,0 @@ -# This is a Makefile which maintains files automatically generated but to be -# shipped together with other files. -# You don't have to rebuild these targets by yourself unless you develop -# grpc-gateway itself. - -PKG=github.com/grpc-ecosystem/grpc-gateway -GO_PLUGIN=bin/protoc-gen-go -GO_PROTOBUF_REPO=github.com/golang/protobuf -GO_PLUGIN_PKG=$(GO_PROTOBUF_REPO)/protoc-gen-go -GO_PTYPES_ANY_PKG=$(GO_PROTOBUF_REPO)/ptypes/any -SWAGGER_PLUGIN=bin/protoc-gen-swagger -SWAGGER_PLUGIN_SRC= utilities/doc.go \ - utilities/pattern.go \ - utilities/trie.go \ - protoc-gen-swagger/genswagger/generator.go \ - protoc-gen-swagger/genswagger/template.go \ - protoc-gen-swagger/main.go -SWAGGER_PLUGIN_PKG=$(PKG)/protoc-gen-swagger -GATEWAY_PLUGIN=bin/protoc-gen-grpc-gateway -GATEWAY_PLUGIN_PKG=$(PKG)/protoc-gen-grpc-gateway -GATEWAY_PLUGIN_SRC= utilities/doc.go \ - utilities/pattern.go \ - utilities/trie.go \ - protoc-gen-grpc-gateway \ - protoc-gen-grpc-gateway/descriptor \ - protoc-gen-grpc-gateway/descriptor/registry.go \ - protoc-gen-grpc-gateway/descriptor/services.go \ - protoc-gen-grpc-gateway/descriptor/types.go \ - protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go \ - protoc-gen-grpc-gateway/descriptor/grpc_api_service.go \ - protoc-gen-grpc-gateway/generator \ - protoc-gen-grpc-gateway/generator/generator.go \ - protoc-gen-grpc-gateway/gengateway \ - protoc-gen-grpc-gateway/gengateway/doc.go \ - protoc-gen-grpc-gateway/gengateway/generator.go \ - protoc-gen-grpc-gateway/gengateway/template.go \ - protoc-gen-grpc-gateway/httprule \ - protoc-gen-grpc-gateway/httprule/compile.go \ - protoc-gen-grpc-gateway/httprule/parse.go \ - protoc-gen-grpc-gateway/httprule/types.go \ - protoc-gen-grpc-gateway/main.go -GATEWAY_PLUGIN_FLAGS?= -SWAGGER_PLUGIN_FLAGS?= - -GOOGLEAPIS_DIR=third_party/googleapis -OUTPUT_DIR=_output - -RUNTIME_PROTO=runtime/internal/stream_chunk.proto -RUNTIME_GO=$(RUNTIME_PROTO:.proto=.pb.go) - -OPENAPIV2_PROTO=protoc-gen-swagger/options/openapiv2.proto protoc-gen-swagger/options/annotations.proto -OPENAPIV2_GO=$(OPENAPIV2_PROTO:.proto=.pb.go) - -PKGMAP=Mgoogle/protobuf/descriptor.proto=$(GO_PLUGIN_PKG)/descriptor,Mexamples/proto/sub/message.proto=$(PKG)/examples/proto/sub -ADDITIONAL_GW_FLAGS= -ifneq "$(GATEWAY_PLUGIN_FLAGS)" "" - ADDITIONAL_GW_FLAGS=,$(GATEWAY_PLUGIN_FLAGS) -endif -ADDITIONAL_SWG_FLAGS= -ifneq "$(SWAGGER_PLUGIN_FLAGS)" "" - ADDITIONAL_SWG_FLAGS=,$(SWAGGER_PLUGIN_FLAGS) -endif -SWAGGER_EXAMPLES=examples/proto/examplepb/echo_service.proto \ - examples/proto/examplepb/a_bit_of_everything.proto \ - examples/proto/examplepb/wrappers.proto \ - examples/proto/examplepb/unannotated_echo_service.proto -EXAMPLES=examples/proto/examplepb/echo_service.proto \ - examples/proto/examplepb/a_bit_of_everything.proto \ - examples/proto/examplepb/stream.proto \ - examples/proto/examplepb/flow_combination.proto \ - examples/proto/examplepb/wrappers.proto \ - examples/proto/examplepb/unannotated_echo_service.proto -EXAMPLE_SVCSRCS=$(EXAMPLES:.proto=.pb.go) -EXAMPLE_GWSRCS=$(EXAMPLES:.proto=.pb.gw.go) -EXAMPLE_SWAGGERSRCS=$(SWAGGER_EXAMPLES:.proto=.swagger.json) -EXAMPLE_DEPS=examples/proto/sub/message.proto examples/proto/sub2/message.proto -EXAMPLE_DEPSRCS=$(EXAMPLE_DEPS:.proto=.pb.go) - -EXAMPLE_CLIENT_DIR=examples/clients -ECHO_EXAMPLE_SPEC=examples/proto/examplepb/echo_service.swagger.json -ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/echo/api_client.go \ - $(EXAMPLE_CLIENT_DIR)/echo/api_response.go \ - $(EXAMPLE_CLIENT_DIR)/echo/configuration.go \ - $(EXAMPLE_CLIENT_DIR)/echo/echo_service_api.go \ - $(EXAMPLE_CLIENT_DIR)/echo/examplepb_simple_message.go \ - $(EXAMPLE_CLIENT_DIR)/echo/examplepb_embedded.go -ABE_EXAMPLE_SPEC=examples/proto/examplepb/a_bit_of_everything.swagger.json -ABE_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/abe/a_bit_of_everything_nested.go \ - $(EXAMPLE_CLIENT_DIR)/abe/a_bit_of_everything_service_api.go \ - $(EXAMPLE_CLIENT_DIR)/abe/api_client.go \ - $(EXAMPLE_CLIENT_DIR)/abe/api_response.go \ - $(EXAMPLE_CLIENT_DIR)/abe/camel_case_service_name_api.go \ - $(EXAMPLE_CLIENT_DIR)/abe/configuration.go \ - $(EXAMPLE_CLIENT_DIR)/abe/echo_rpc_api.go \ - $(EXAMPLE_CLIENT_DIR)/abe/echo_service_api.go \ - $(EXAMPLE_CLIENT_DIR)/abe/examplepb_a_bit_of_everything.go \ - $(EXAMPLE_CLIENT_DIR)/abe/examplepb_body.go \ - $(EXAMPLE_CLIENT_DIR)/abe/examplepb_numeric_enum.go \ - $(EXAMPLE_CLIENT_DIR)/abe/nested_deep_enum.go \ - $(EXAMPLE_CLIENT_DIR)/abe/protobuf_empty.go \ - $(EXAMPLE_CLIENT_DIR)/abe/sub_string_message.go -UNANNOTATED_ECHO_EXAMPLE_SPEC=examples/proto/examplepb/unannotated_echo_service.swagger.json -UNANNOTATED_ECHO_EXAMPLE_SRCS=$(EXAMPLE_CLIENT_DIR)/unannotatedecho/api_client.go \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/api_response.go \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/configuration.go \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/examplepb_unannotated_simple_message.go \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/unannotated_echo_service_api.go -EXAMPLE_CLIENT_SRCS=$(ECHO_EXAMPLE_SRCS) $(ABE_EXAMPLE_SRCS) $(UNANNOTATED_ECHO_EXAMPLE_SRCS) -SWAGGER_CODEGEN=swagger-codegen - -PROTOC_INC_PATH=$(dir $(shell which protoc))/../include - -generate: $(RUNTIME_GO) - -.SUFFIXES: .go .proto - -$(GO_PLUGIN): - go get $(GO_PLUGIN_PKG) - go build -o $@ $(GO_PLUGIN_PKG) - -$(RUNTIME_GO): $(RUNTIME_PROTO) $(GO_PLUGIN) - protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I $(GOPATH)/src/$(GO_PTYPES_ANY_PKG) -I. --go_out=$(PKGMAP):. $(RUNTIME_PROTO) - -$(OPENAPIV2_GO): $(OPENAPIV2_PROTO) $(GO_PLUGIN) - protoc -I $(PROTOC_INC_PATH) --plugin=$(GO_PLUGIN) -I. --go_out=$(PKGMAP):$(GOPATH)/src $(OPENAPIV2_PROTO) - -$(GATEWAY_PLUGIN): $(RUNTIME_GO) $(GATEWAY_PLUGIN_SRC) - go build -o $@ $(GATEWAY_PLUGIN_PKG) - -$(SWAGGER_PLUGIN): $(SWAGGER_PLUGIN_SRC) $(OPENAPIV2_GO) - go build -o $@ $(SWAGGER_PLUGIN_PKG) - -$(EXAMPLE_SVCSRCS): $(GO_PLUGIN) $(EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc:. $(EXAMPLES) -$(EXAMPLE_DEPSRCS): $(GO_PLUGIN) $(EXAMPLE_DEPS) - mkdir -p $(OUTPUT_DIR) - protoc -I $(PROTOC_INC_PATH) -I. --plugin=$(GO_PLUGIN) --go_out=$(PKGMAP),plugins=grpc:$(OUTPUT_DIR) $(@:.pb.go=.proto) - cp $(OUTPUT_DIR)/$(PKG)/$@ $@ || cp $(OUTPUT_DIR)/$@ $@ - -$(EXAMPLE_GWSRCS): ADDITIONAL_GW_FLAGS:=$(ADDITIONAL_GW_FLAGS),grpc_api_configuration=examples/proto/examplepb/unannotated_echo_service.yaml -$(EXAMPLE_GWSRCS): $(GATEWAY_PLUGIN) $(EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(GATEWAY_PLUGIN) --grpc-gateway_out=logtostderr=true,$(PKGMAP)$(ADDITIONAL_GW_FLAGS):. $(EXAMPLES) - -$(EXAMPLE_SWAGGERSRCS): ADDITIONAL_SWG_FLAGS:=$(ADDITIONAL_SWG_FLAGS),grpc_api_configuration=examples/proto/examplepb/unannotated_echo_service.yaml -$(EXAMPLE_SWAGGERSRCS): $(SWAGGER_PLUGIN) $(SWAGGER_EXAMPLES) - protoc -I $(PROTOC_INC_PATH) -I. -I$(GOOGLEAPIS_DIR) --plugin=$(SWAGGER_PLUGIN) --swagger_out=logtostderr=true,$(PKGMAP)$(ADDITIONAL_SWG_FLAGS):. $(SWAGGER_EXAMPLES) - -$(ECHO_EXAMPLE_SRCS): $(ECHO_EXAMPLE_SPEC) - $(SWAGGER_CODEGEN) generate -i $(ECHO_EXAMPLE_SPEC) \ - -l go -o examples/clients/echo --additional-properties packageName=echo - @rm -f $(EXAMPLE_CLIENT_DIR)/echo/README.md \ - $(EXAMPLE_CLIENT_DIR)/echo/git_push.sh \ - $(EXAMPLE_CLIENT_DIR)/echo/.travis.yml -$(ABE_EXAMPLE_SRCS): $(ABE_EXAMPLE_SPEC) - $(SWAGGER_CODEGEN) generate -i $(ABE_EXAMPLE_SPEC) \ - -l go -o examples/clients/abe --additional-properties packageName=abe - @rm -f $(EXAMPLE_CLIENT_DIR)/abe/README.md \ - $(EXAMPLE_CLIENT_DIR)/abe/git_push.sh \ - $(EXAMPLE_CLIENT_DIR)/abe/.travis.yml -$(UNANNOTATED_ECHO_EXAMPLE_SRCS): $(UNANNOTATED_ECHO_EXAMPLE_SPEC) - $(SWAGGER_CODEGEN) generate -i $(UNANNOTATED_ECHO_EXAMPLE_SPEC) \ - -l go -o examples/clients/unannotatedecho --additional-properties packageName=unannotatedecho - @rm -f $(EXAMPLE_CLIENT_DIR)/unannotatedecho/README.md \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/git_push.sh \ - $(EXAMPLE_CLIENT_DIR)/unannotatedecho/.travis.yml - -examples: $(EXAMPLE_SVCSRCS) $(EXAMPLE_GWSRCS) $(EXAMPLE_DEPSRCS) $(EXAMPLE_SWAGGERSRCS) $(EXAMPLE_CLIENT_SRCS) -test: examples - go test -race $(PKG)/... - go test -race $(PKG)/examples/integration -args -network=unix -endpoint=test.sock -changelog: - docker run --rm \ - --interactive \ - --tty \ - -e "CHANGELOG_GITHUB_TOKEN=${CHANGELOG_GITHUB_TOKEN}" \ - -v "$(PWD):/usr/local/src/your-app" \ - ferrarimarco/github-changelog-generator \ - -u grpc-ecosystem \ - -p grpc-gateway \ - --author \ - --compare-link \ - --github-site=https://grpc-ecosystem.github.io/grpc-gateway \ - --unreleased-label "**Next release**" \ - --future-release=v1.4.1 -lint: - golint --set_exit_status $(PKG)/runtime - golint --set_exit_status $(PKG)/utilities/... - golint --set_exit_status $(PKG)/protoc-gen-grpc-gateway/... - golint --set_exit_status $(PKG)/protoc-gen-swagger/... - go vet $(PKG)/runtime || true - go vet $(PKG)/utilities/... - go vet $(PKG)/protoc-gen-grpc-gateway/... - go vet $(PKG)/protoc-gen-swagger/... - -clean: - rm -f $(GATEWAY_PLUGIN) $(SWAGGER_PLUGIN) -distclean: clean - rm -f $(GO_PLUGIN) -realclean: distclean - rm -f $(EXAMPLE_SVCSRCS) $(EXAMPLE_DEPSRCS) - rm -f $(EXAMPLE_GWSRCS) - rm -f $(EXAMPLE_SWAGGERSRCS) - rm -f $(EXAMPLE_CLIENT_SRCS) - rm -f $(OPENAPIV2_GO) - -.PHONY: generate examples test lint clean distclean realclean diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/README.md b/examples/github.com/grpc-ecosystem/grpc-gateway/README.md deleted file mode 100755 index ccb7d74..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/README.md +++ /dev/null @@ -1,252 +0,0 @@ -# grpc-gateway - -[![Build Status](https://travis-ci.org/grpc-ecosystem/grpc-gateway.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/grpc-gateway) - -grpc-gateway is a plugin of [protoc](http://github.com/google/protobuf). -It reads [gRPC](http://github.com/grpc/grpc-common) service definition, -and generates a reverse-proxy server which translates a RESTful JSON API into gRPC. -This server is generated according to [custom options](https://cloud.google.com/service-management/reference/rpc/google.api#http) in your gRPC definition. - -It helps you to provide your APIs in both gRPC and RESTful style at the same time. - -![architecture introduction diagram](https://docs.google.com/drawings/d/12hp4CPqrNPFhattL_cIoJptFvlAqm5wLQ0ggqI5mkCg/pub?w=749&h=370) - -## Check out our [documentation](https://grpc-ecosystem.github.io/grpc-gateway/)! - -## Background -gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. -However, you might still want to provide a traditional RESTful API as well. Reasons can range from maintaining backwards-compatibility, supporting languages or clients not well supported by gRPC to simply maintaining the aesthetics and tooling involved with a RESTful architecture. - -This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library. - -## Installation -First you need to install ProtocolBuffers 3.0.0-beta-3 or later. - -```sh -mkdir tmp -cd tmp -git clone https://github.com/google/protobuf -cd protobuf -./autogen.sh -./configure -make -make check -sudo make install -``` - -Then, `go get -u` as usual the following packages: - -```sh -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -go get -u github.com/golang/protobuf/protoc-gen-go -``` - -## Usage -Make sure that your `$GOPATH/bin` is in your `$PATH`. - -1. Define your service in gRPC - - your_service.proto: - ```protobuf - syntax = "proto3"; - package example; - message StringMessage { - string value = 1; - } - - service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} - } - ``` -2. Add a [custom option](https://cloud.google.com/service-management/reference/rpc/google.api#http) to the .proto file - - your_service.proto: - ```diff - syntax = "proto3"; - package example; - + - +import "google/api/annotations.proto"; - + - message StringMessage { - string value = 1; - } - - service YourService { - - rpc Echo(StringMessage) returns (StringMessage) {} - + rpc Echo(StringMessage) returns (StringMessage) { - + option (google.api.http) = { - + post: "/v1/example/echo" - + body: "*" - + }; - + } - } - ``` - - If you do not want to modify the proto file for use with grpc-gateway you can alternatively use an external [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) file. [Check our documentation](https://grpc-ecosystem.github.io/grpc-gateway/docs/grpcapiconfiguration.html) for more information. - -3. Generate gRPC stub - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --go_out=plugins=grpc:. \ - path/to/your_service.proto - ``` - - It will generate a stub file `path/to/your_service.pb.go`. -4. Implement your service in gRPC as usual - 1. (Optional) Generate gRPC stub in the language you want. - - e.g. - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --ruby_out=. \ - path/to/your/service_proto - - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --plugin=protoc-gen-grpc=grpc_ruby_plugin \ - --grpc-ruby_out=. \ - path/to/your/service.proto - ``` - 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. - 3. Implement your service - -5. Generate reverse-proxy - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --grpc-gateway_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - - It will generate a reverse proxy `path/to/your_service.pb.gw.go`. - - Note: After generating the code for each of the stubs, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs. - -6. Write an entrypoint - - Now you need to write an entrypoint of the proxy server. - ```go - package main - - import ( - "flag" - "net/http" - - "github.com/golang/glog" - "golang.org/x/net/context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - gw "path/to/your_service_package" - ) - - var ( - echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService") - ) - - func run() error { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - mux := runtime.NewServeMux() - opts := []grpc.DialOption{grpc.WithInsecure()} - err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) - if err != nil { - return err - } - - return http.ListenAndServe(":8080", mux) - } - - func main() { - flag.Parse() - defer glog.Flush() - - if err := run(); err != nil { - glog.Fatal(err) - } - } - ``` - -7. (Optional) Generate swagger definitions - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --swagger_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - -## Parameters and flags -`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path. -They are compatible to [the parameters with same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters). - -In addition we also support the `request_context` parameter in order to use the `http.Request`'s Context (only for Go 1.7 and above). -This parameter can be useful to pass request scoped context between the gateway and the gRPC service. - -`protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags. - -## More Examples -More examples are available under `examples` directory. -* `proto/examplepb/echo_service.proto`, `proto/examplepb/a_bit_of_everything.proto`, `proto/examplepb/unannotated_echo_service.proto`: service definition - * `proto/examplepb/echo_service.pb.go`, `proto/examplepb/a_bit_of_everything.pb.go`, `proto/examplepb/unannotated_echo_service.pb.go`: [generated] stub of the service - * `proto/examplepb/echo_service.pb.gw.go`, `proto/examplepb/a_bit_of_everything.pb.gw.go`, `proto/examplepb/uannotated_echo_service.pb.gw.go`: [generated] reverse proxy for the service - * `proto/examplepb/unannotated_echo_service.yaml`: gRPC API Configuration for ```unannotated_echo_service.proto``` -* `server/main.go`: service implementation -* `main.go`: entrypoint of the generated reverse proxy - -To use the same port for custom HTTP handlers (e.g. serving `swagger.json`), gRPC-gateway, and a gRPC server, see [this code example by CoreOS](https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go) (and its accompanying [blog post](https://coreos.com/blog/gRPC-protobufs-swagger.html)) - -## Features -### Supported -* Generating JSON API handlers -* Method parameters in request body -* Method parameters in request path -* Method parameters in query string -* Enum fields in path parameter (including repeated enum fields). -* Mapping streaming APIs to newline-delimited JSON streams -* Mapping HTTP headers with `Grpc-Metadata-` prefix to gRPC metadata (prefixed with `grpcgateway-`) -* Optionally emitting API definition for [Swagger](http://swagger.io). -* Setting [gRPC timeouts](http://www.grpc.io/docs/guides/wire.html) through inbound HTTP `Grpc-Timeout` header. -* Partial support for [gRPC API Configuration]((https://cloud.google.com/endpoints/docs/grpc/grpc-service-config)) files as an alternative to annotation. - -### Want to support -But not yet. -* Optionally generating the entrypoint. #8 -* `import_path` parameter - -### No plan to support -But patch is welcome. -* Method parameters in HTTP headers -* Handling trailer metadata -* Encoding request/response body in XML -* True bi-directional streaming. (Probably impossible?) - -# Mapping gRPC to HTTP - -* [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15) -* HTTP request source IP is added as `X-Forwarded-For` gRPC request header -* HTTP request host is added as `X-Forwarded-Host` gRPC request header -* HTTP `Authorization` header is added as `authorization` gRPC request header -* Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header -* HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (prefixed with `grpcgateway-`) -* While configurable, the default {un,}marshaling uses [jsonpb](https://godoc.org/github.com/golang/protobuf/jsonpb) with `OrigName: true`. - - -# Contribution -See [CONTRIBUTING.md](http://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md). - -# License -grpc-gateway is licensed under the BSD 3-Clause License. -See [LICENSE.txt](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt) for more details. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/WORKSPACE b/examples/github.com/grpc-ecosystem/grpc-gateway/WORKSPACE deleted file mode 100755 index 225d018..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/WORKSPACE +++ /dev/null @@ -1,53 +0,0 @@ -workspace(name = "grpc_ecosystem_grpc_gateway") - -http_archive( - name = "io_bazel_rules_go", - url = "https://github.com/bazelbuild/rules_go/releases/download/0.10.3/rules_go-0.10.3.tar.gz", - sha256 = "feba3278c13cde8d67e341a837f69a029f698d7a27ddbb2a202be7a10b22142a", -) - -http_archive( - name = "bazel_gazelle", - url = "https://github.com/bazelbuild/bazel-gazelle/releases/download/0.10.1/bazel-gazelle-0.10.1.tar.gz", - sha256 = "d03625db67e9fb0905bbd206fa97e32ae9da894fe234a493e7517fd25faec914", -) - -load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains") - -go_rules_dependencies() - -go_register_toolchains() - -load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") - -gazelle_dependencies() - -load("@io_bazel_rules_go//go:def.bzl", "go_repository") - -go_repository( - name = "com_github_rogpeppe_fastuuid", - commit = "6724a57986aff9bff1a1770e9347036def7c89f6", - importpath = "github.com/rogpeppe/fastuuid", -) - -go_repository( - name = "com_github_go_resty_resty", - commit = "f8815663de1e64d57cdd4ee9e2b2fa96977a030e", - importpath = "github.com/go-resty/resty", -) - -go_repository( - name = "com_github_ghodss_yaml", - commit = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7", - importpath = "github.com/ghodss/yaml", -) - -go_repository( - name = "in_gopkg_yaml_v2", - commit = "eb3733d160e74a9c7e442f435eb3bea458e1d19f", - importpath = "gopkg.in/yaml.v2", -) - -load("//:repositories.bzl", "repositories") - -repositories() diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/bin/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/bin/.gitignore deleted file mode 100755 index f20d08c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/bin/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/protoc-gen-go -/protoc-gen-grpc-gateway -/protoc-gen-swagger diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/bin/coverage b/examples/github.com/grpc-ecosystem/grpc-gateway/bin/coverage deleted file mode 100755 index 65bbe95..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/bin/coverage +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -set -euo pipefail -USE_BAZEL=${USE_BAZEL:-false} -> coverage.txt - -if [ "${USE_BAZEL}" = true ]; then - # TODO(yugui) Support bazel - exit 0 -fi - -for d in $(go list ./... | grep -v vendor); do - go test -race -coverprofile=profile.out -covermode=atomic $d - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi -done diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel deleted file mode 100755 index 1eddaaf..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel +++ /dev/null @@ -1,26 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//:generators"]) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "parse_req.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/codegenerator", - deps = [ - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = ["parse_req_test.go"], - deps = [ - ":go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go deleted file mode 100755 index 3645317..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package codegenerator contains reusable functions used by the code generators. -*/ -package codegenerator diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go b/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go deleted file mode 100755 index e74575b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go +++ /dev/null @@ -1,23 +0,0 @@ -package codegenerator - -import ( - "fmt" - "io" - "io/ioutil" - - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" -) - -// ParseRequest parses a code generator request from a proto Message. -func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) { - input, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("failed to read code generator request: %v", err) - } - req := new(plugin.CodeGeneratorRequest) - if err = proto.Unmarshal(input, req); err != nil { - return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err) - } - return req, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req_test.go deleted file mode 100755 index 5f37aad..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package codegenerator_test - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/codegenerator" -) - -var parseReqTests = []struct { - name string - in io.Reader - out *plugin.CodeGeneratorRequest - err error -}{ - { - "Empty input should produce empty output", - mustGetReader(&plugin.CodeGeneratorRequest{}), - &plugin.CodeGeneratorRequest{}, - nil, - }, - { - "Invalid reader should produce error", - &invalidReader{}, - nil, - fmt.Errorf("failed to read code generator request: invalid reader"), - }, - { - "Invalid proto message should produce error", - strings.NewReader("{}"), - nil, - fmt.Errorf("failed to unmarshal code generator request: unexpected EOF"), - }, -} - -func TestParseRequest(t *testing.T) { - for _, tt := range parseReqTests { - t.Run(tt.name, func(t *testing.T) { - out, err := codegenerator.ParseRequest(tt.in) - if !reflect.DeepEqual(err, tt.err) { - t.Errorf("got %v, want %v", err, tt.err) - } - if err == nil && !reflect.DeepEqual(*out, *tt.out) { - t.Errorf("got %v, want %v", *out, *tt.out) - } - }) - } -} - -func mustGetReader(pb proto.Message) io.Reader { - b, err := proto.Marshal(pb) - if err != nil { - panic(err) - } - return bytes.NewBuffer(b) -} - -type invalidReader struct { -} - -func (*invalidReader) Read(p []byte) (int, error) { - return 0, fmt.Errorf("invalid reader") -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/.gitignore deleted file mode 100755 index ca35be0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_site diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile deleted file mode 100755 index 5e3964f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile +++ /dev/null @@ -1,9 +0,0 @@ -source 'https://rubygems.org' - -group :development, :test do - gem "github-pages", group: :jekyll_plugins - gem 'jekyll', '~> 3.7.0' - gem 'jekyll-redirect-from', '~> 0.13.0' - gem 'jekyll-sitemap', '~> 1.2.0' - gem 'jekyll-toc', '~> 0.5.1' -end diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile.lock b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile.lock deleted file mode 100755 index 6bc4cb1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/Gemfile.lock +++ /dev/null @@ -1,256 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - activesupport (4.2.9) - i18n (~> 0.7) - minitest (~> 5.1) - thread_safe (~> 0.3, >= 0.3.4) - tzinfo (~> 1.1) - addressable (2.5.2) - public_suffix (>= 2.0.2, < 4.0) - coffee-script (2.4.1) - coffee-script-source - execjs - coffee-script-source (1.11.1) - colorator (1.1.0) - commonmarker (0.17.9) - ruby-enum (~> 0.5) - concurrent-ruby (1.0.5) - em-websocket (0.5.1) - eventmachine (>= 0.12.9) - http_parser.rb (~> 0.6.0) - ethon (0.11.0) - ffi (>= 1.3.0) - eventmachine (1.2.5) - execjs (2.7.0) - faraday (0.14.0) - multipart-post (>= 1.2, < 3) - ffi (1.9.23) - forwardable-extended (2.6.0) - gemoji (3.0.0) - github-pages (182) - activesupport (= 4.2.9) - github-pages-health-check (= 1.4.0) - jekyll (= 3.7.3) - jekyll-avatar (= 0.5.0) - jekyll-coffeescript (= 1.1.1) - jekyll-commonmark-ghpages (= 0.1.5) - jekyll-default-layout (= 0.1.4) - jekyll-feed (= 0.9.3) - jekyll-gist (= 1.5.0) - jekyll-github-metadata (= 2.9.4) - jekyll-mentions (= 1.3.0) - jekyll-optional-front-matter (= 0.3.0) - jekyll-paginate (= 1.1.0) - jekyll-readme-index (= 0.2.0) - jekyll-redirect-from (= 0.13.0) - jekyll-relative-links (= 0.5.3) - jekyll-remote-theme (= 0.2.3) - jekyll-sass-converter (= 1.5.2) - jekyll-seo-tag (= 2.4.0) - jekyll-sitemap (= 1.2.0) - jekyll-swiss (= 0.4.0) - jekyll-theme-architect (= 0.1.1) - jekyll-theme-cayman (= 0.1.1) - jekyll-theme-dinky (= 0.1.1) - jekyll-theme-hacker (= 0.1.1) - jekyll-theme-leap-day (= 0.1.1) - jekyll-theme-merlot (= 0.1.1) - jekyll-theme-midnight (= 0.1.1) - jekyll-theme-minimal (= 0.1.1) - jekyll-theme-modernist (= 0.1.1) - jekyll-theme-primer (= 0.5.3) - jekyll-theme-slate (= 0.1.1) - jekyll-theme-tactile (= 0.1.1) - jekyll-theme-time-machine (= 0.1.1) - jekyll-titles-from-headings (= 0.5.1) - jemoji (= 0.9.0) - kramdown (= 1.16.2) - liquid (= 4.0.0) - listen (= 3.1.5) - mercenary (~> 0.3) - minima (= 2.4.1) - nokogiri (>= 1.8.1, < 2.0) - rouge (= 2.2.1) - terminal-table (~> 1.4) - github-pages-health-check (1.4.0) - addressable (~> 2.3) - net-dns (~> 0.8) - octokit (~> 4.0) - public_suffix (~> 2.0) - typhoeus (~> 1.3) - html-pipeline (2.7.1) - activesupport (>= 2) - nokogiri (>= 1.4) - http_parser.rb (0.6.0) - i18n (0.9.5) - concurrent-ruby (~> 1.0) - jekyll (3.7.3) - addressable (~> 2.4) - colorator (~> 1.0) - em-websocket (~> 0.5) - i18n (~> 0.7) - jekyll-sass-converter (~> 1.0) - jekyll-watch (~> 2.0) - kramdown (~> 1.14) - liquid (~> 4.0) - mercenary (~> 0.3.3) - pathutil (~> 0.9) - rouge (>= 1.7, < 4) - safe_yaml (~> 1.0) - jekyll-avatar (0.5.0) - jekyll (~> 3.0) - jekyll-coffeescript (1.1.1) - coffee-script (~> 2.2) - coffee-script-source (~> 1.11.1) - jekyll-commonmark (1.2.0) - commonmarker (~> 0.14) - jekyll (>= 3.0, < 4.0) - jekyll-commonmark-ghpages (0.1.5) - commonmarker (~> 0.17.6) - jekyll-commonmark (~> 1) - rouge (~> 2) - jekyll-default-layout (0.1.4) - jekyll (~> 3.0) - jekyll-feed (0.9.3) - jekyll (~> 3.3) - jekyll-gist (1.5.0) - octokit (~> 4.2) - jekyll-github-metadata (2.9.4) - jekyll (~> 3.1) - octokit (~> 4.0, != 4.4.0) - jekyll-mentions (1.3.0) - activesupport (~> 4.0) - html-pipeline (~> 2.3) - jekyll (~> 3.0) - jekyll-optional-front-matter (0.3.0) - jekyll (~> 3.0) - jekyll-paginate (1.1.0) - jekyll-readme-index (0.2.0) - jekyll (~> 3.0) - jekyll-redirect-from (0.13.0) - jekyll (~> 3.3) - jekyll-relative-links (0.5.3) - jekyll (~> 3.3) - jekyll-remote-theme (0.2.3) - jekyll (~> 3.5) - rubyzip (>= 1.2.1, < 3.0) - typhoeus (>= 0.7, < 2.0) - jekyll-sass-converter (1.5.2) - sass (~> 3.4) - jekyll-seo-tag (2.4.0) - jekyll (~> 3.3) - jekyll-sitemap (1.2.0) - jekyll (~> 3.3) - jekyll-swiss (0.4.0) - jekyll-theme-architect (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-cayman (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-dinky (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-hacker (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-leap-day (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-merlot (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-midnight (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-minimal (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-modernist (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-primer (0.5.3) - jekyll (~> 3.5) - jekyll-github-metadata (~> 2.9) - jekyll-seo-tag (~> 2.0) - jekyll-theme-slate (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-tactile (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-theme-time-machine (0.1.1) - jekyll (~> 3.5) - jekyll-seo-tag (~> 2.0) - jekyll-titles-from-headings (0.5.1) - jekyll (~> 3.3) - jekyll-toc (0.5.2) - nokogiri (~> 1.6) - jekyll-watch (2.0.0) - listen (~> 3.0) - jemoji (0.9.0) - activesupport (~> 4.0, >= 4.2.9) - gemoji (~> 3.0) - html-pipeline (~> 2.2) - jekyll (~> 3.0) - kramdown (1.16.2) - liquid (4.0.0) - listen (3.1.5) - rb-fsevent (~> 0.9, >= 0.9.4) - rb-inotify (~> 0.9, >= 0.9.7) - ruby_dep (~> 1.2) - mercenary (0.3.6) - mini_portile2 (2.3.0) - minima (2.4.1) - jekyll (~> 3.5) - jekyll-feed (~> 0.9) - jekyll-seo-tag (~> 2.1) - minitest (5.11.3) - multipart-post (2.0.0) - net-dns (0.8.0) - nokogiri (1.8.2) - mini_portile2 (~> 2.3.0) - octokit (4.8.0) - sawyer (~> 0.8.0, >= 0.5.3) - pathutil (0.16.1) - forwardable-extended (~> 2.6) - public_suffix (2.0.5) - rb-fsevent (0.10.3) - rb-inotify (0.9.10) - ffi (>= 0.5.0, < 2) - rouge (2.2.1) - ruby-enum (0.7.2) - i18n - ruby_dep (1.5.0) - rubyzip (1.2.1) - safe_yaml (1.0.4) - sass (3.5.6) - sass-listen (~> 4.0.0) - sass-listen (4.0.0) - rb-fsevent (~> 0.9, >= 0.9.4) - rb-inotify (~> 0.9, >= 0.9.7) - sawyer (0.8.1) - addressable (>= 2.3.5, < 2.6) - faraday (~> 0.8, < 1.0) - terminal-table (1.8.0) - unicode-display_width (~> 1.1, >= 1.1.1) - thread_safe (0.3.6) - typhoeus (1.3.0) - ethon (>= 0.9.0) - tzinfo (1.2.5) - thread_safe (~> 0.1) - unicode-display_width (1.3.0) - -PLATFORMS - ruby - -DEPENDENCIES - github-pages - jekyll (~> 3.7.0) - jekyll-redirect-from (~> 0.13.0) - jekyll-sitemap (~> 1.2.0) - jekyll-toc (~> 0.5.1) - -BUNDLED WITH - 1.15.4 diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_config.yaml b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_config.yaml deleted file mode 100755 index 4803199..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_config.yaml +++ /dev/null @@ -1,19 +0,0 @@ -theme: jekyll-theme-architect - -repository: grpc-ecosystem/grpc-gateway - -collections: - docs: - output: true - -defaults: - - scope: - path: "" - values: - layout: "default" - -plugins: - - jekyll-toc - -exclude: - - run.sh diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/background.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/background.md deleted file mode 100755 index 63463a1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/background.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -category: documentation ---- - -# Background - -gRPC is great -- it generates API clients and server stubs in many programming languages, it is fast, easy-to-use, bandwidth-efficient and its design is combat-proven by Google. -However, you might still want to provide a traditional RESTful API as well. Reasons can range from maintaining backwards-compatibility, supporting languages or clients not well supported by gRPC to simply maintaining the aesthetics and tooling involved with a RESTful architecture. - -This project aims to provide that HTTP+JSON interface to your gRPC service. A small amount of configuration in your service to attach HTTP semantics is all that's needed to generate a reverse-proxy with this library. - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/customizingyourgateway.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/customizingyourgateway.md deleted file mode 100755 index 758611f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/customizingyourgateway.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Customizing your gateway -category: documentation -order: 101 ---- - -# Customizing your gateway - -## Message serialization - -You might want to serialize request/response messages in MessagePack instead of JSON, for example. - -1. Write a custom implementation of [`Marshaler`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#Marshaler) -2. Register your marshaler with [`WithMarshalerOption`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithMarshalerOption) - e.g. - ```go - var m your.MsgPackMarshaler - mux := runtime.NewServeMux(runtime.WithMarshalerOption("application/x-msgpack", m)) - ``` - -You can see [the default implementation for JSON](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/marshal_jsonpb.go) for reference. - -## Mapping from HTTP request headers to gRPC client metadata -You might not like [the default mapping rule](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#DefaultHeaderMatcher) and might want to pass through all the HTTP headers, for example. - -1. Write a [`HeaderMatcherFunc`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#HeaderMatcherFunc). -2. Register the function with [`WithIncomingHeaderMatcher`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithIncomingHeaderMatcher) - - e.g. - ```go - func yourMatcher(headerName string) (mdName string, ok bool) { - ... - } - ... - mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(yourMatcher)) - - ``` - -## Mapping from gRPC server metadata to HTTP response headers -ditto. Use [`WithOutgoingHeaderMatcher`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithOutgoingHeaderMatcher) - -## Mutate response messages or set response headers -You might want to return a subset of response fields as HTTP response headers; -You might want to simply set an application-specific token in a header. -Or you might want to mutate the response messages to be returned. - -1. Write a filter function. - ```go - func myFilter(ctx context.Context, w http.ResponseWriter, resp proto.Message) error { - w.Header().Set("X-My-Tracking-Token", resp.Token) - resp.Token = "" - return nil - } - ``` -2. Register the filter with [`WithForwardResponseOption`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#WithForwardResponseOption) - - e.g. - ```go - mux := runtime.NewServeMux(runtime.WithForwardResponseOption(myFilter)) - ``` - -## Error handler -http://mycodesmells.com/post/grpc-gateway-error-handler - -## Replace a response forwarder per method -You might want to keep the behavior of the current marshaler but change only a message forwarding of a certain API method. - -1. write a custom forwarder which is compatible to [`ForwardResponseMessage`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#ForwardResponseMessage) or [`ForwardResponseStream`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#ForwardResponseStream). -2. replace the default forwarder of the method with your one. - - e.g. add `forwarder_overwrite.go` into the go package of the generated code, - ```go - package generated - - import ( - "net/http" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - ) - - func forwardCheckoutResp(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { - if someCondition(resp) { - http.Error(w, "not enough credit", http. StatusPaymentRequired) - return - } - runtime.ForwardResponseMessage(ctx, mux, marshaler, w, req, resp, opts...) - } - - func init() { - forward_MyService_Checkout_0 = forwardCheckoutResp - } - ``` diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/cygwin.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/cygwin.md deleted file mode 100755 index 5e0a37f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/cygwin.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -category: documentation -title: Installation for Cygwin -order: 1000 ---- - -#Installation for Cygwin - -![cygwin-logo](https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Cygwin_logo.svg/145px-Cygwin_logo.svg.png) -## Installation -First you need to install the [Go language](https://golang.org/dl/). Please install the latest version, not the one that is listed here. - - wget -N https://storage.googleapis.com/golang/go1.8.1.windows-amd64.msi - msiexec /i go1.8.1.windows-amd64.msi /passive /promptrestart - -Then you need to install [ProtocolBuffers 3.0.0-beta-3](https://github.com/google/protobuf/releases) or later. Use the windows release while no native cygwin protoc with version 3 is available yet. - - wget -N https://github.com/google/protobuf/releases/download/v3.2.0/protoc-3.2.0-win32.zip` - 7z x protoc-3.2.0-win32.zip -o/usr/local/ - -Then you need to setup your Go workspace. Create the workspace dir. - - mkdir /home/user/go - mkdir /home/user/go/bin - mkdir /home/user/go/pkg - mkdir /home/user/go/src - -From an elevated cmd.exe prompt set the GOPATH variable in windows and add the `$GOPATH/bin` directory to your path using `reg add` instead of `setx` because [setx can truncated your PATH variable to 1024 characters](https://encrypted.google.com/search?hl=en&q=setx%20truncates%20PATH%201024#safe=off&hl=en&q=setx+truncated+PATH+1024). - - setx GOPATH c:\path\to\your\cygwin\home\user\go /M - set pathkey="HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" - for /F "usebackq skip=2 tokens=2*" %A IN (`reg query %pathkey% /v Path`) do (reg add %pathkey% /f /v Path /t REG_SZ /d "%B;c:\path\to\your\cygwin\home\user\go\bin") - -Then `go get -u -v` the following packages: - - go get -u -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway - go get -u -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger - go get -u -v github.com/golang/protobuf/protoc-gen-go - -This will probably fail with similar output. - - github.com/grpc-ecosystem/grpc-gateway (download) - # cd .; git clone https://github.com/grpc-ecosystem/grpc-gateway C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway - Cloning into 'C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway'... - fatal: Invalid path '/home/user/go/C:\path\to\your\cygwin\home\user\go\src\github.com\grpc-ecosystem\grpc-gateway': No such file or directory - package github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway: exit status 128 - -To fix this you need to run the `go get -u -v` commands and look for all lines starting with `# cd .; `. -Copy and paste these lines into your shell and change the clone destination directories. - - git clone https://github.com/grpc-ecosystem/grpc-gateway $(cygpath -u $GOPATH)/src/github.com/grpc-ecosystem/grpc-gateway - git clone https://github.com/golang/glog $(cygpath -u $GOPATH)/src/github.com/golang/glog - git clone https://github.com/golang/protobuf $(cygpath -u $GOPATH)/src/github.com/golang/protobuf - git clone https://github.com/google/go-genproto $(cygpath -u $GOPATH)/src/google.golang.org/genproto - -Once the clone operations are finished the `go get -u -v` commands shouldn't give you an error anymore. - -## Usage -Follow the [instuctions](https://github.com/grpc-ecosystem/grpc-gateway#usage) in the [README](https://github.com/grpc-ecosystem/grpc-gateway). - -Adjust steps 3, 5 and 7 like this. protoc expects native windows paths. - - protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=plugins=grpc:. ./path/to/your_service.proto - protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:. ./path/to/your_service.proto - protoc -I. -I$(cygpath -w /usr/local/include) -I${GOPATH}/src -I${GOPATH}/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --swagger_out=logtostderr=true:. ./path/to/your_service.proto - -Then `cd` into the directory where your entry-point `main.go` file is located and run - - go get -v - -This will fail like during the Installation. Look for all lines starting with `# cd .; ` and copy and paste these lines into your shell and change the clone destination directories. - - git clone https://go.googlesource.com/net $(cygpath -u $GOPATH)/src/golang.org/x/net - git clone https://go.googlesource.com/text $(cygpath -u $GOPATH)/src/golang.org/x/text - git clone https://github.com/grpc/grpc-go $(cygpath -u $GOPATH)/src/google.golang.org/grpc - -Once the clone operations are finished the `go get -v` commands shouldn't give you an error anymore. - -Then run - - go install - -to compile and install your grpc-gateway service into `$GOPATH/bin`. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/examples.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/examples.md deleted file mode 100755 index 78d93d7..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/examples.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -category: documentation ---- - -# Examples - -Examples are available under `examples` directory. -* `proto/examplepb/echo_service.proto`, `proto/examplepb/a_bit_of_everything.proto`, `proto/examplepb/unannotated_echo_service.proto`: service definition - * `proto/examplepb/echo_service.pb.go`, `proto/examplepb/a_bit_of_everything.pb.go`, `proto/examplepb/unannotated_echo_service.pb.go`: [generated] stub of the service - * `proto/examplepb/echo_service.pb.gw.go`, `proto/examplepb/a_bit_of_everything.pb.gw.go`, `proto/examplepb/uannotated_echo_service.pb.gw.go`: [generated] reverse proxy for the service - * `proto/examplepb/unannotated_echo_service.yaml`: gRPC API Configuration for ```unannotated_echo_service.proto``` -* `server/main.go`: service implementation -* `main.go`: entrypoint of the generated reverse proxy - -To use the same port for custom HTTP handlers (e.g. serving `swagger.json`), gRPC-gateway, and a gRPC server, see [this code example by CoreOS](https://github.com/philips/grpc-gateway-example/blob/master/cmd/serve.go) (and its accompanying [blog post](https://coreos.com/blog/gRPC-protobufs-swagger.html)) - - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/faq.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/faq.md deleted file mode 100755 index 766c402..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/faq.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -category: documentation -title: FAQ ---- - -# FAQ - -## How can I write the annotations which grpc-gateway requires? -Grpc-gateway follows the spec of [`google.api.HttpRule`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto). -So first check out the documentation if it is feasible in the spec. - -See also [a past discussion](https://groups.google.com/d/msg/grpc-io/Xqx80hG0D44/VNCDHjeE6pUJ) in grpc-io mailing list. - -## I want to support a certain style of HTTP request but the code generated by grpc-gateway does not. How can I support this style? -See the question above at first. - -Grpc-gateway is intended to cover 80% of use cases without forcing you to write comprehensive but complicated annotations. So grpc-gateway itself does not always cover all the use cases you have by design. In other words, grpc-gateway automates typical boring boilerplate mapping between gRPC and HTTP/1 communication, but it does not do arbitrarily complex custom mappings for you. - -On the other hand, you can still add whatever you want as a middleware which wraps [`runtime.ServeMux`](http://godoc.org/github.com/grpc-ecosystem/grpc-gateway/runtime#ServeMux). Since `runtime.ServeMux` is just a standard [`http.Handler`](http://golang.org/pkg/http#Handler), you can easily write a custom wrapper of `runtime.ServeMux`, leveraged with existing third-party libraries in Go. -e.g. https://github.com/grpc-ecosystem/grpc-gateway/blob/master/examples/main.go - -## My gRPC server is written in (Scala|C++|Ruby|Haskell|....). Is there a (Scala|C++|Ruby|Haskell|....) version of grpc-gateway? - -AFAIK, no. But it should not be a big issue because the reverse-proxy which grpc-gateway generates usually works as an independent process and communicates with your gRPC server over TCP or a unix-domain socket. - -## Why are the models in the swagger specification prefixed with the last part of the proto package name? - -The reason to generate the prefixes is that we don't have a guaranteed unique namespace. If two packages produce different Foo messages then we will have trouble. - -## Why not strip the prefix? - -When a message is added which happens to conflict with another message (e.g. by importing a message with the same name from a different package) it will break code that is very far away from the code that changed. This is in an effort to adhere to the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/features.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/features.md deleted file mode 100755 index 0bae360..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/features.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -category: documentation ---- - -# Features - -## Supported -* Generating JSON API handlers -* Method parameters in request body -* Method parameters in request path -* Method parameters in query string -* Enum fields in path parameter (including repeated enum fields). -* Mapping streaming APIs to newline-delimited JSON streams -* Mapping HTTP headers with `Grpc-Metadata-` prefix to gRPC metadata (prefixed with `grpcgateway-`) -* Optionally emitting API definition for [Swagger](http://swagger.io). -* Setting [gRPC timeouts](http://www.grpc.io/docs/guides/wire.html) through inbound HTTP `Grpc-Timeout` header. -* Partial support for [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) files as an alternative to annotation. - -## Want to support -But not yet. -* Optionally generating the entrypoint. #8 -* `import_path` parameter - -## No plan to support -But patch is welcome. -* Method parameters in HTTP headers -* Handling trailer metadata -* Encoding request/response body in XML -* True bi-directional streaming. (Probably impossible?) - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/grpcapiconfiguration.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/grpcapiconfiguration.md deleted file mode 100755 index 6547e7d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/grpcapiconfiguration.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Usage without annotations (gRPC API Configuration) -category: documentation -order: 100 ---- - -# gRPC API Configuration -In some sitations annotating the .proto file of a service is not an option. For example you might not have control over the .proto file or you might want to expose the same gRPC API multiple times in completely different ways. - -Google Cloud Platform offers a way to do this for services hosted with them called ["gRPC API Configuration"](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config). It can be used to define the behavior of a gRPC API service without modifications to the service itself in the form of [YAML](https://en.wikipedia.org/wiki/YAML) configuration files. - -grpc-gateway generators implement the [HTTP rules part](https://cloud.google.com/endpoints/docs/grpc-service-config/reference/rpc/google.api#httprule) of this specification. This allows you to take a completely unannotated service proto file, add a YAML file describing its HTTP endpoints and use them together like a annotated proto file with the grpc-gateway generators. - -## Usage of gRPC API Configuration YAML files -The following is equivalent to the basic [usage example](usage.html) but without direct annotation for grpc-gateway in the .proto file. Only some steps require minor changes to use a gRPC API Configuration YAML file instead: - -1. Define your service in gRPC as usual - - your_service.proto: - ```protobuf - syntax = "proto3"; - package example; - message StringMessage { - string value = 1; - } - - service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} - } - ``` - -2. Instead of annotating the .proto file in this step leave it untouched and create a `your_service.yaml` with the following content: - ```yaml - type: google.api.Service - config_version: 3 - - http: - rules: - - selector: example.YourService.Echo - post: /v1/example/echo - body: "*" - ``` - Use a [linter](http://www.yamllint.com/) to validate your YAML. - -3. Generate gRPC stub as before - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --go_out=plugins=grpc:. \ - path/to/your_service.proto - ``` - - It will generate a stub file `path/to/your_service.pb.go`. -4. Implement your service in gRPC as usual - 1. (Optional) Generate gRPC stub in the language you want. - - e.g. - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --ruby_out=. \ - path/to/your/service_proto - - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --plugin=protoc-gen-grpc=grpc_ruby_plugin \ - --grpc-ruby_out=. \ - path/to/your/service.proto - ``` - 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. - 3. Implement your service - -5. Generate reverse-proxy. Here we have to pass the path to the `your_service.yaml` in addition to the .proto file: - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --grpc-gateway_out=logtostderr=true,grpc_api_configuration=path/to/your_service.yaml:. \ - path/to/your_service.proto - ``` - - This will generate a reverse proxy `path/to/your_service.pb.gw.go` that is identical to the one produced for the annotated proto. - - Note: After generating the code for each of the stubs, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs. - -6. Write an entrypoint - - Now you need to write an entrypoint of the proxy server. This step is the same whether the file is annotated or not. - ```go - package main - - import ( - "flag" - "net/http" - - "github.com/golang/glog" - "golang.org/x/net/context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - gw "path/to/your_service_package" - ) - - var ( - echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService") - ) - - func run() error { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - mux := runtime.NewServeMux() - opts := []grpc.DialOption{grpc.WithInsecure()} - err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) - if err != nil { - return err - } - - return http.ListenAndServe(":8080", mux) - } - - func main() { - flag.Parse() - defer glog.Flush() - - if err := run(); err != nil { - glog.Fatal(err) - } - } - ``` - -7. (Optional) Generate swagger definitions - -Swagger generation in this step is equivalent to gateway generation. Again pass the path to the yaml file in addition to the proto: - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --swagger_out=logtostderr=true,grpc_api_configuration=path/to/your_service.yaml:. \ - path/to/your_service.proto - ``` - -All other steps work as before. If you want you can remove the googleapis include path in step 3 and 4 as the unannotated proto no longer requires them. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/usage.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/usage.md deleted file mode 100755 index 8862c52..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_docs/usage.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -category: documentation ---- - -# How do I use this? - -## Installation -First you need to install ProtocolBuffers 3.0.0-beta-3 or later. - -```sh -mkdir tmp -cd tmp -git clone https://github.com/google/protobuf -cd protobuf -./autogen.sh -./configure -make -make check -sudo make install -``` - -Then, `go get -u` as usual the following packages: - -```sh -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -go get -u github.com/golang/protobuf/protoc-gen-go -``` - -## Usage -Make sure that your `$GOPATH/bin` is in your `$PATH`. - -1. Define your service in gRPC - - your_service.proto: - ```protobuf - syntax = "proto3"; - package example; - message StringMessage { - string value = 1; - } - - service YourService { - rpc Echo(StringMessage) returns (StringMessage) {} - } - ``` -2. Add a [custom option](https://cloud.google.com/service-management/reference/rpc/google.api#http) to the .proto file - - your_service.proto: - ```diff - syntax = "proto3"; - package example; - + - +import "google/api/annotations.proto"; - + - message StringMessage { - string value = 1; - } - - service YourService { - - rpc Echo(StringMessage) returns (StringMessage) {} - + rpc Echo(StringMessage) returns (StringMessage) { - + option (google.api.http) = { - + post: "/v1/example/echo" - + body: "*" - + }; - + } - } - ``` - - If you do not want to modify the proto file for use with grpc-gateway you can alternatively use an external [gRPC API Configuration](https://cloud.google.com/endpoints/docs/grpc/grpc-service-config) file. [Check our documentation](grpcapiconfiguration.html) for more information. - -3. Generate gRPC stub - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --go_out=plugins=grpc:. \ - path/to/your_service.proto - ``` - - It will generate a stub file `path/to/your_service.pb.go`. -4. Implement your service in gRPC as usual - 1. (Optional) Generate gRPC stub in the language you want. - - e.g. - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --ruby_out=. \ - path/to/your/service_proto - - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --plugin=protoc-gen-grpc=grpc_ruby_plugin \ - --grpc-ruby_out=. \ - path/to/your/service.proto - ``` - 2. Add the googleapis-common-protos gem (or your language equivalent) as a dependency to your project. - 3. Implement your service - -5. Generate reverse-proxy - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --grpc-gateway_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - - It will generate a reverse proxy `path/to/your_service.pb.gw.go`. - - Note: After generating the code for each of the stubs, in order to build the code, you will want to run ```go get .``` from the directory containing the stubs. - -6. Write an entrypoint - - Now you need to write an entrypoint of the proxy server. - ```go - package main - - import ( - "flag" - "net/http" - - "github.com/golang/glog" - "golang.org/x/net/context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" - - gw "path/to/your_service_package" - ) - - var ( - echoEndpoint = flag.String("echo_endpoint", "localhost:9090", "endpoint of YourService") - ) - - func run() error { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - mux := runtime.NewServeMux() - opts := []grpc.DialOption{grpc.WithInsecure()} - err := gw.RegisterYourServiceHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts) - if err != nil { - return err - } - - return http.ListenAndServe(":8080", mux) - } - - func main() { - flag.Parse() - defer glog.Flush() - - if err := run(); err != nil { - glog.Fatal(err) - } - } - ``` - -7. (Optional) Generate swagger definitions - - ```sh - protoc -I/usr/local/include -I. \ - -I$GOPATH/src \ - -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \ - --swagger_out=logtostderr=true:. \ - path/to/your_service.proto - ``` - -## Parameters and flags -`protoc-gen-grpc-gateway` supports custom mapping from Protobuf `import` to Golang import path. -They are compatible to [the parameters with same names in `protoc-gen-go`](https://github.com/golang/protobuf#parameters). - -In addition we also support the `request_context` parameter in order to use the `http.Request`'s Context (only for Go 1.7 and above). -This parameter can be useful to pass request scoped context between the gateway and the gRPC service. - -`protoc-gen-grpc-gateway` also supports some more command line flags to control logging. You can give these flags together with parameters above. Run `protoc-gen-grpc-gateway --help` for more details about the flags. - -# Mapping gRPC to HTTP - -* [How gRPC error codes map to HTTP status codes in the response](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go#L15) -* HTTP request source IP is added as `X-Forwarded-For` gRPC request header -* HTTP request host is added as `X-Forwarded-Host` gRPC request header -* HTTP `Authorization` header is added as `authorization` gRPC request header -* Remaining Permanent HTTP header keys (as specified by the IANA [here](http://www.iana.org/assignments/message-headers/message-headers.xhtml) are prefixed with `grpcgateway-` and added with their values to gRPC request header -* HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata (prefixed with `grpcgateway-`) -* While configurable, the default {un,}marshaling uses [jsonpb](https://godoc.org/github.com/golang/protobuf/jsonpb) with `OrigName: true`. - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_layouts/default.html b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_layouts/default.html deleted file mode 100755 index 1e45e5f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/_layouts/default.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - -{% seo %} - - - -
-
- -

{{ site.title | default: site.github.repository_name }}

-
-

{{ site.description | default: site.github.project_tagline }}

- {% if site.github.is_project_page %} - View project on GitHub - {% endif %} - {% if site.github.is_user_page %} - Follow me on GitHub - {% endif %} -
-
- -
-
-
- {{ content | toc }} -
- - -
-
- - {% if site.google_analytics %} - - {% endif %} - - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/index.md b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/index.md deleted file mode 100755 index 47b6ec0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# grpc-gateway - -[![Build Status](https://travis-ci.org/grpc-ecosystem/grpc-gateway.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/grpc-gateway) - -grpc-gateway is a plugin of [protoc](http://github.com/google/protobuf). -It reads [gRPC](http://github.com/grpc/grpc-common) service definition, -and generates a reverse-proxy server which translates a RESTful JSON API into gRPC. -This server is generated according to [custom options](https://cloud.google.com/service-management/reference/rpc/google.api#http) in your gRPC definition. - -It helps you to provide your APIs in both gRPC and RESTful style at the same time. - -![architecture introduction diagram](https://docs.google.com/drawings/d/12hp4CPqrNPFhattL_cIoJptFvlAqm5wLQ0ggqI5mkCg/pub?w=749&h=370) - -To learn more about us check out our documentation on: - -* [Our background](_docs/background.md) -* [Installation and usage](_docs/usage.md) -* [Examples](_docs/examples.md) -* [Features](_docs/features.md) - - -# Contribution -See [CONTRIBUTING.md](http://github.com/grpc-ecosystem/grpc-gateway/blob/master/CONTRIBUTING.md). - -# License -grpc-gateway is licensed under the BSD 3-Clause License. -See [LICENSE.txt](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt) for more details. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/run.sh b/examples/github.com/grpc-ecosystem/grpc-gateway/docs/run.sh deleted file mode 100755 index b9b5a2c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/docs/run.sh +++ /dev/null @@ -1,28 +0,0 @@ -#! /bin/bash - -set -e - -JEKYLL_VERSION=3.5 -BUNDLE_DIR="/tmp/grpc-gateway-bundle" - -if [ ! -d "${BUNDLE_DIR}" ]; then - mkdir "${BUNDLE_DIR}" - - # Run this to update the Gemsfile.lock - docker run --rm \ - --volume="${PWD}:/srv/jekyll" \ - -e "JEKYLL_UID=$(id -u)" \ - -e "JEKYLL_GID=$(id -g)" \ - --volume="/tmp/grpc-gateway-bundle:/usr/local/bundle" \ - -it "jekyll/builder:${JEKYLL_VERSION}" \ - bundle update -fi - -docker run --rm \ - --volume="${PWD}:/srv/jekyll" \ - -p 35729:35729 -p 4000:4000 \ - -e "JEKYLL_UID=$(id -u)" \ - -e "JEKYLL_GID=$(id -g)" \ - --volume="/tmp/grpc-gateway-bundle:/usr/local/bundle" \ - -it "jekyll/builder:${JEKYLL_VERSION}" \ - jekyll serve diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/README.md b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/README.md deleted file mode 100755 index b7b486f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# One way to run the example - -```bash -# Handle dependencies -$ dep init -``` - -Follow the guides from this [README.md](./browser/README.md) to run the server and gateway. -```bash -# Make sure you are in the correct directory: -# $GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/examples -$ cd examples/browser -$ pwd - -# Install gulp -$ npm install -g gulp-cli -$ npm install -$ gulp - -# Run -$ gulp bower -$ gulp backends -``` - -Then you can use curl or a browser to test: - -```bash -# List all apis -$ curl http://localhost:8080/swagger/echo_service.swagger.json - -# Visit the apis -$ curl -XPOST http://localhost:8080/v1/example/echo/foo -{"id":"foo"} - -$ curl http://localhost:8080/v1/example/echo/foo/123 -{"id":"foo","num":"123"} - -``` - -So you have visited the apis by HTTP successfully. You can also try other apis. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/.gitignore deleted file mode 100755 index 1dcc590..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/bower_components -/node_modules -/package-lock.json diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/README.md b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/README.md deleted file mode 100755 index be4fbd3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Browser example - -This directory contains an example use of grpc-gateway with web browsers. -The following commands automatically runs integration tests with phantomjs. - -```shell-session -$ npm install -g gulp-cli -$ npm install -$ gulp -``` - -## Other examples - -### Very simple example -Run -```shell-session -$ gulp bower -$ gulp backends -``` - -then, open `index.html`. - - -### Integration test with your browser - -Run -```shell-session -$ gulp serve -``` - -then, open `http://localhost:8000` with your browser. diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/a_bit_of_everything_service.spec.js b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/a_bit_of_everything_service.spec.js deleted file mode 100755 index edcbebe..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/a_bit_of_everything_service.spec.js +++ /dev/null @@ -1,185 +0,0 @@ -'use strict'; - -var SwaggerClient = require('swagger-client'); - -describe('ABitOfEverythingService', function() { - var client; - - beforeEach(function(done) { - new SwaggerClient({ - url: "http://localhost:8080/swagger/a_bit_of_everything.swagger.json", - usePromise: true, - }).then(function(c) { - client = c; - }).catch(function(err) { - done.fail(err); - }).then(done); - }); - - describe('Create', function() { - var created; - var expected = { - float_value: 1.5, - double_value: 2.5, - int64_value: "4294967296", - uint64_value: "9223372036854775807", - int32_value: -2147483648, - fixed64_value: "9223372036854775807", - fixed32_value: 4294967295, - bool_value: true, - string_value: "strprefix/foo", - uint32_value: 4294967295, - sfixed32_value: 2147483647, - sfixed64_value: "-4611686018427387904", - sint32_value: 2147483647, - sint64_value: "4611686018427387903", - nonConventionalNameValue: "camelCase", - }; - - beforeEach(function(done) { - client.ABitOfEverythingService.Create(expected).then(function(resp) { - created = resp.obj; - }).catch(function(err) { - done.fail(err); - }).then(done); - }); - - it('should assign id', function() { - expect(created.uuid).not.toBe(""); - }); - - it('should echo the request back', function() { - delete created.uuid; - expect(created).toEqual(expected); - }); - }); - - describe('CreateBody', function() { - var created; - var expected = { - float_value: 1.5, - double_value: 2.5, - int64_value: "4294967296", - uint64_value: "9223372036854775807", - int32_value: -2147483648, - fixed64_value: "9223372036854775807", - fixed32_value: 4294967295, - bool_value: true, - string_value: "strprefix/foo", - uint32_value: 4294967295, - sfixed32_value: 2147483647, - sfixed64_value: "-4611686018427387904", - sint32_value: 2147483647, - sint64_value: "4611686018427387903", - nonConventionalNameValue: "camelCase", - - nested: [ - { name: "bar", amount: 10 }, - { name: "baz", amount: 20 }, - ], - repeated_string_value: ["a", "b", "c"], - oneof_string: "x", - // TODO(yugui) Support enum by name - map_value: { a: 1, b: 2 }, - mapped_string_value: { a: "x", b: "y" }, - mapped_nested_value: { - a: { name: "x", amount: 1 }, - b: { name: "y", amount: 2 }, - }, - }; - - beforeEach(function(done) { - client.ABitOfEverythingService.CreateBody({ - body: expected, - }).then(function(resp) { - created = resp.obj; - }).catch(function(err) { - done.fail(err); - }).then(done); - }); - - it('should assign id', function() { - expect(created.uuid).not.toBe(""); - }); - - it('should echo the request back', function() { - delete created.uuid; - expect(created).toEqual(expected); - }); - }); - - describe('lookup', function() { - var created; - var expected = { - bool_value: true, - string_value: "strprefix/foo", - }; - - beforeEach(function(done) { - client.ABitOfEverythingService.CreateBody({ - body: expected, - }).then(function(resp) { - created = resp.obj; - }).catch(function(err) { - fail(err); - }).finally(done); - }); - - it('should look up an object by uuid', function(done) { - client.ABitOfEverythingService.Lookup({ - uuid: created.uuid - }).then(function(resp) { - expect(resp.obj).toEqual(created); - }).catch(function(err) { - fail(err.errObj); - }).finally(done); - }); - - it('should fail if no such object', function(done) { - client.ABitOfEverythingService.Lookup({ - uuid: 'not_exist', - }).then(function(resp) { - fail('expected failure but succeeded'); - }).catch(function(err) { - expect(err.status).toBe(404); - }).finally(done); - }); - }); - - describe('Delete', function() { - var created; - var expected = { - bool_value: true, - string_value: "strprefix/foo", - }; - - beforeEach(function(done) { - client.ABitOfEverythingService.CreateBody({ - body: expected, - }).then(function(resp) { - created = resp.obj; - }).catch(function(err) { - fail(err); - }).finally(done); - }); - - it('should delete an object by id', function(done) { - client.ABitOfEverythingService.Delete({ - uuid: created.uuid - }).then(function(resp) { - expect(resp.obj).toEqual({}); - }).catch(function(err) { - fail(err.errObj); - }).then(function() { - return client.ABitOfEverythingService.Lookup({ - uuid: created.uuid - }); - }).then(function(resp) { - fail('expected failure but succeeded'); - }). catch(function(err) { - expect(err.status).toBe(404); - }).finally(done); - }); - }); -}); - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bin/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bin/.gitignore deleted file mode 100755 index a68d087..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bin/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/* -!/.gitignore diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bower.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bower.json deleted file mode 100755 index 2454691..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/bower.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "grpc-gateway-example-browser", - "description": "Example use of grpc-gateway from browser", - "main": "index.js", - "authors": [ - "Yuki Yugui Sonoda " - ], - "license": "SEE LICENSE IN LICENSE file", - "homepage": "https://github.com/grpc-ecosystem/grpc-gateway", - "private": true, - "dependencies": { - "swagger-js": "~> 2.1" - }, - "ignore": [ - "**/.*", - "node_modules", - "bower_components", - "test", - "tests" - ] -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/echo_service.spec.js b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/echo_service.spec.js deleted file mode 100755 index 97888c3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/echo_service.spec.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var SwaggerClient = require('swagger-client'); - -describe('EchoService', function() { - var client; - - beforeEach(function(done) { - new SwaggerClient({ - url: "http://localhost:8080/swagger/echo_service.swagger.json", - usePromise: true, - }).then(function(c) { - client = c; - done(); - }); - }); - - describe('Echo', function() { - it('should echo the request back', function(done) { - client.EchoService.Echo( - {id: "foo"}, - {responseContentType: "application/json"} - ).then(function(resp) { - expect(resp.obj).toEqual({id: "foo"}); - }).catch(function(err) { - done.fail(err); - }).then(done); - }); - }); - - describe('EchoBody', function() { - it('should echo the request back', function(done) { - client.EchoService.EchoBody( - {body: {id: "foo"}}, - {responseContentType: "application/json"} - ).then(function(resp) { - expect(resp.obj).toEqual({id: "foo"}); - }).catch(function(err) { - done.fail(err); - }).then(done); - }); - }); -}); diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/gulpfile.js b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/gulpfile.js deleted file mode 100755 index 233afed..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/gulpfile.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; - -var gulp = require('gulp'); - -var path = require('path'); - -var bower = require('gulp-bower'); -var exit = require('gulp-exit'); -var gprocess = require('gulp-process'); -var shell = require('gulp-shell'); -var jasmineBrowser = require('gulp-jasmine-browser'); -var webpack = require('webpack-stream'); - -gulp.task('bower', function(){ - return bower(); -}); - -gulp.task('server', shell.task([ - 'go build -o bin/example-server github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server', -])); - -gulp.task('gateway', shell.task([ - 'go build -o bin/example-gw github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server', -])); - -gulp.task('serve-server', ['server'], function(){ - gprocess.start('server-server', 'bin/example-server', [ - '--logtostderr', - ]); - gulp.watch('bin/example-server', ['serve-server']); -}); - -gulp.task('serve-gateway', ['gateway', 'serve-server'], function(){ - gprocess.start('gateway-server', 'bin/example-gw', [ - '--logtostderr', '--swagger_dir', path.join(__dirname, "../proto/examplepb"), - ]); - gulp.watch('bin/example-gw', ['serve-gateway']); -}); - -gulp.task('backends', ['serve-gateway', 'serve-server']); - -var specFiles = ['*.spec.js']; -gulp.task('test', ['backends'], function(done) { - return gulp.src(specFiles) - .pipe(webpack({output: {filename: 'spec.js'}})) - .pipe(jasmineBrowser.specRunner({ - console: true, - sourceMappedStacktrace: true, - })) - .pipe(jasmineBrowser.headless({ - findOpenPort: true, - catch: true, - throwFailures: true, - })) - .on('error', function(err) { - done(err); - process.exit(1); - }) - .pipe(exit()); -}); - -gulp.task('serve', ['backends'], function(done) { - var JasminePlugin = require('gulp-jasmine-browser/webpack/jasmine-plugin'); - var plugin = new JasminePlugin(); - - return gulp.src(specFiles) - .pipe(webpack({ - output: {filename: 'spec.js'}, - watch: true, - plugins: [plugin], - })) - .pipe(jasmineBrowser.specRunner({ - sourceMappedStacktrace: true, - })) - .pipe(jasmineBrowser.server({ - port: 8000, - whenReady: plugin.whenReady, - })); -}); - -gulp.task('default', ['test']); diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/index.html b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/index.html deleted file mode 100755 index 7817451..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - -
- - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/package.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/package.json deleted file mode 100755 index 963f4cd..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/browser/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "grpc-gateway-example", - "version": "1.0.0", - "description": "Example use of grpc-gateway from browser", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "SEE LICENSE IN LICENSE.txt", - "devDependencies": { - "bower": "^1.7.9", - "gulp": "^3.9.1", - "gulp-bower": "0.0.13", - "gulp-exit": "0.0.2", - "gulp-jasmine-browser": "^1.3.2", - "gulp-process": "^0.1.2", - "gulp-shell": "^0.5.2", - "jasmine": "^2.4.1", - "phantomjs": "^2.1.7", - "swagger-client": "^2.1.28", - "webpack-stream": "^3.2.0" - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.gitignore deleted file mode 100755 index 2f88269..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/docs diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.swagger-codegen-ignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.swagger-codegen-ignore deleted file mode 100755 index 6c7b69a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/.swagger-codegen-ignore +++ /dev/null @@ -1 +0,0 @@ -.gitignore diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/BUILD.bazel deleted file mode 100755 index fad5b66..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/BUILD.bazel +++ /dev/null @@ -1,25 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "a_bit_of_everything_nested.go", - "a_bit_of_everything_service_api.go", - "api_client.go", - "api_response.go", - "camel_case_service_name_api.go", - "configuration.go", - "echo_rpc_api.go", - "echo_service_api.go", - "examplepb_a_bit_of_everything.go", - "examplepb_body.go", - "examplepb_numeric_enum.go", - "nested_deep_enum.go", - "protobuf_empty.go", - "sub_string_message.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe", - deps = ["@com_github_go_resty_resty//:go_default_library"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_nested.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_nested.go deleted file mode 100755 index 095e8c5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_nested.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -// Nested is nested type. -type ABitOfEverythingNested struct { - - // name is nested field. - Name string `json:"name,omitempty"` - - Amount int64 `json:"amount,omitempty"` - - Ok NestedDeepEnum `json:"ok,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_service_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_service_api.go deleted file mode 100755 index 19c6fda..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/a_bit_of_everything_service_api.go +++ /dev/null @@ -1,938 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "net/url" - "strings" - "time" - "encoding/json" - "fmt" -) - -type ABitOfEverythingServiceApi struct { - Configuration *Configuration -} - -func NewABitOfEverythingServiceApi() *ABitOfEverythingServiceApi { - configuration := NewConfiguration() - return &ABitOfEverythingServiceApi{ - Configuration: configuration, - } -} - -func NewABitOfEverythingServiceApiWithBasePath(basePath string) *ABitOfEverythingServiceApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &ABitOfEverythingServiceApi{ - Configuration: configuration, - } -} - -/** - * - * - * @param floatValue - * @param doubleValue - * @param int64Value - * @param uint64Value - * @param int32Value - * @param fixed64Value - * @param fixed32Value - * @param boolValue - * @param stringValue - * @param uint32Value - * @param sfixed32Value - * @param sfixed64Value - * @param sint32Value - * @param sint64Value - * @param nonConventionalNameValue - * @return *ExamplepbABitOfEverything - */ -func (a ABitOfEverythingServiceApi) Create(floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, uint32Value int64, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, nonConventionalNameValue string) (*ExamplepbABitOfEverything, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}" - localVarPath = strings.Replace(localVarPath, "{"+"float_value"+"}", fmt.Sprintf("%v", floatValue), -1) - localVarPath = strings.Replace(localVarPath, "{"+"double_value"+"}", fmt.Sprintf("%v", doubleValue), -1) - localVarPath = strings.Replace(localVarPath, "{"+"int64_value"+"}", fmt.Sprintf("%v", int64Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"uint64_value"+"}", fmt.Sprintf("%v", uint64Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"int32_value"+"}", fmt.Sprintf("%v", int32Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"fixed64_value"+"}", fmt.Sprintf("%v", fixed64Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"fixed32_value"+"}", fmt.Sprintf("%v", fixed32Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"bool_value"+"}", fmt.Sprintf("%v", boolValue), -1) - localVarPath = strings.Replace(localVarPath, "{"+"string_value"+"}", fmt.Sprintf("%v", stringValue), -1) - localVarPath = strings.Replace(localVarPath, "{"+"uint32_value"+"}", fmt.Sprintf("%v", uint32Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"sfixed32_value"+"}", fmt.Sprintf("%v", sfixed32Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"sfixed64_value"+"}", fmt.Sprintf("%v", sfixed64Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"sint32_value"+"}", fmt.Sprintf("%v", sint32Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"sint64_value"+"}", fmt.Sprintf("%v", sint64Value), -1) - localVarPath = strings.Replace(localVarPath, "{"+"nonConventionalNameValue"+"}", fmt.Sprintf("%v", nonConventionalNameValue), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbABitOfEverything) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Create", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param body - * @return *ExamplepbABitOfEverything - */ -func (a ABitOfEverythingServiceApi) CreateBody(body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ExamplepbABitOfEverything) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "CreateBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param singleNestedName - * @param body - * @return *ExamplepbABitOfEverything - */ -func (a ABitOfEverythingServiceApi) DeepPathEcho(singleNestedName string, body ExamplepbABitOfEverything) (*ExamplepbABitOfEverything, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{single_nested.name}" - localVarPath = strings.Replace(localVarPath, "{"+"single_nested.name"+"}", fmt.Sprintf("%v", singleNestedName), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ExamplepbABitOfEverything) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "DeepPathEcho", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param uuid - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) Delete(uuid string) (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Delete") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}" - localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Delete", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) ErrorWithDetails() (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/errorwithdetails" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "ErrorWithDetails", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param id - * @param body - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) GetMessageWithBody(id string, body ExamplepbBody) (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/withbody/{id}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetMessageWithBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param uuid - * @param singleNestedName name is nested field. - * @param singleNestedAmount - * @param singleNestedOk - FALSE: FALSE is false. - TRUE: TRUE is true. - * @param floatValue - * @param doubleValue - * @param int64Value - * @param uint64Value - * @param int32Value - * @param fixed64Value - * @param fixed32Value - * @param boolValue - * @param stringValue - * @param bytesValue - * @param uint32Value - * @param enumValue - ZERO: ZERO means 0 - ONE: ONE means 1 - * @param sfixed32Value - * @param sfixed64Value - * @param sint32Value - * @param sint64Value - * @param repeatedStringValue - * @param oneofString - * @param nonConventionalNameValue - * @param timestampValue - * @param repeatedEnumValue repeated enum value. it is comma-separated in query. - ZERO: ZERO means 0 - ONE: ONE means 1 - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) GetQuery(uuid string, singleNestedName string, singleNestedAmount int64, singleNestedOk string, floatValue float32, doubleValue float64, int64Value string, uint64Value string, int32Value int32, fixed64Value string, fixed32Value int64, boolValue bool, stringValue string, bytesValue string, uint32Value int64, enumValue string, sfixed32Value int32, sfixed64Value string, sint32Value int32, sint64Value string, repeatedStringValue []string, oneofString string, nonConventionalNameValue string, timestampValue time.Time, repeatedEnumValue []string) (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/query/{uuid}" - localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("single_nested.name", a.Configuration.APIClient.ParameterToString(singleNestedName, "")) - localVarQueryParams.Add("single_nested.amount", a.Configuration.APIClient.ParameterToString(singleNestedAmount, "")) - localVarQueryParams.Add("single_nested.ok", a.Configuration.APIClient.ParameterToString(singleNestedOk, "")) - localVarQueryParams.Add("float_value", a.Configuration.APIClient.ParameterToString(floatValue, "")) - localVarQueryParams.Add("double_value", a.Configuration.APIClient.ParameterToString(doubleValue, "")) - localVarQueryParams.Add("int64_value", a.Configuration.APIClient.ParameterToString(int64Value, "")) - localVarQueryParams.Add("uint64_value", a.Configuration.APIClient.ParameterToString(uint64Value, "")) - localVarQueryParams.Add("int32_value", a.Configuration.APIClient.ParameterToString(int32Value, "")) - localVarQueryParams.Add("fixed64_value", a.Configuration.APIClient.ParameterToString(fixed64Value, "")) - localVarQueryParams.Add("fixed32_value", a.Configuration.APIClient.ParameterToString(fixed32Value, "")) - localVarQueryParams.Add("bool_value", a.Configuration.APIClient.ParameterToString(boolValue, "")) - localVarQueryParams.Add("string_value", a.Configuration.APIClient.ParameterToString(stringValue, "")) - localVarQueryParams.Add("bytes_value", a.Configuration.APIClient.ParameterToString(bytesValue, "")) - localVarQueryParams.Add("uint32_value", a.Configuration.APIClient.ParameterToString(uint32Value, "")) - localVarQueryParams.Add("enum_value", a.Configuration.APIClient.ParameterToString(enumValue, "")) - localVarQueryParams.Add("sfixed32_value", a.Configuration.APIClient.ParameterToString(sfixed32Value, "")) - localVarQueryParams.Add("sfixed64_value", a.Configuration.APIClient.ParameterToString(sfixed64Value, "")) - localVarQueryParams.Add("sint32_value", a.Configuration.APIClient.ParameterToString(sint32Value, "")) - localVarQueryParams.Add("sint64_value", a.Configuration.APIClient.ParameterToString(sint64Value, "")) - var repeatedStringValueCollectionFormat = "csv" - localVarQueryParams.Add("repeated_string_value", a.Configuration.APIClient.ParameterToString(repeatedStringValue, repeatedStringValueCollectionFormat)) - - localVarQueryParams.Add("oneof_string", a.Configuration.APIClient.ParameterToString(oneofString, "")) - localVarQueryParams.Add("nonConventionalNameValue", a.Configuration.APIClient.ParameterToString(nonConventionalNameValue, "")) - localVarQueryParams.Add("timestamp_value", a.Configuration.APIClient.ParameterToString(timestampValue, "")) - var repeatedEnumValueCollectionFormat = "csv" - localVarQueryParams.Add("repeated_enum_value", a.Configuration.APIClient.ParameterToString(repeatedEnumValue, repeatedEnumValueCollectionFormat)) - - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetQuery", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param uuid - * @return *ExamplepbABitOfEverything - */ -func (a ABitOfEverythingServiceApi) Lookup(uuid string) (*ExamplepbABitOfEverything, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}" - localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbABitOfEverything) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Lookup", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param name - * @param body - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) PostWithEmptyBody(name string, body ExamplepbBody) (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/postwithemptybody/{name}" - localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "PostWithEmptyBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) Timeout() (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/timeout" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Timeout", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * - * - * @param uuid - * @param body - * @return *ProtobufEmpty - */ -func (a ABitOfEverythingServiceApi) Update(uuid string, body ExamplepbABitOfEverything) (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Put") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/{uuid}" - localVarPath = strings.Replace(localVarPath, "{"+"uuid"+"}", fmt.Sprintf("%v", uuid), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Update", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_client.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_client.go deleted file mode 100755 index bf3e21a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_client.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "bytes" - "fmt" - "path/filepath" - "reflect" - "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" -) - -type APIClient struct { - config *Configuration -} - -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { - - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - - if len(accepts) == 0 { - return "" - } - if contains(accepts, "application/json") { - return "application/json" - } - return strings.Join(accepts, ",") -} - -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } - - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient -} - -func (c *APIClient) prepareRequest( - rClient *resty.Client, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) *resty.Request { - - - request := rClient.R() - request.SetBody(postBody) - - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) - } - - // add header parameter, if any - if len(headerParams) > 0 { - request.SetHeaders(headerParams) - } - - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) - } - - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) - } - - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) - } - return request -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_response.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_response.go deleted file mode 100755 index ee1315f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/api_response.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "net/http" -) - -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - // Operation is the name of the swagger operation. - Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. - Payload []byte `json:"-"` -} - -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/camel_case_service_name_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/camel_case_service_name_api.go deleted file mode 100755 index 43c92f7..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/camel_case_service_name_api.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "net/url" - "strings" - "encoding/json" -) - -type CamelCaseServiceNameApi struct { - Configuration *Configuration -} - -func NewCamelCaseServiceNameApi() *CamelCaseServiceNameApi { - configuration := NewConfiguration() - return &CamelCaseServiceNameApi{ - Configuration: configuration, - } -} - -func NewCamelCaseServiceNameApiWithBasePath(basePath string) *CamelCaseServiceNameApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &CamelCaseServiceNameApi{ - Configuration: configuration, - } -} - -/** - * - * - * @return *ProtobufEmpty - */ -func (a CamelCaseServiceNameApi) Empty() (*ProtobufEmpty, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/empty" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ProtobufEmpty) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Empty", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/configuration.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/configuration.go deleted file mode 100755 index ccc319c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/configuration.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "encoding/base64" - "net/http" - "time" -) - - -type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` -} - -func NewConfiguration() *Configuration { - cfg := &Configuration{ - BasePath: "http://localhost", - DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), - UserAgent: "Swagger-Codegen/1.0.0/go", - APIClient: &APIClient{}, - } - - cfg.APIClient.config = cfg - return cfg -} - -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_rpc_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_rpc_api.go deleted file mode 100755 index 8afbbdd..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_rpc_api.go +++ /dev/null @@ -1,265 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "net/url" - "strings" - "encoding/json" - "fmt" -) - -type EchoRpcApi struct { - Configuration *Configuration -} - -func NewEchoRpcApi() *EchoRpcApi { - configuration := NewConfiguration() - return &EchoRpcApi{ - Configuration: configuration, - } -} - -func NewEchoRpcApiWithBasePath(basePath string) *EchoRpcApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &EchoRpcApi{ - Configuration: configuration, - } -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param value - * @return *SubStringMessage - */ -func (a EchoRpcApi) Echo(value string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/echo/{value}" - localVarPath = strings.Replace(localVarPath, "{"+"value"+"}", fmt.Sprintf("%v", value), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param body - * @return *SubStringMessage - */ -func (a EchoRpcApi) Echo2(body string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/echo" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param value - * @return *SubStringMessage - */ -func (a EchoRpcApi) Echo3(value string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/echo" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("value", a.Configuration.APIClient.ParameterToString(value, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_service_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_service_api.go deleted file mode 100755 index 5681777..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/echo_service_api.go +++ /dev/null @@ -1,265 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "net/url" - "strings" - "encoding/json" - "fmt" -) - -type EchoServiceApi struct { - Configuration *Configuration -} - -func NewEchoServiceApi() *EchoServiceApi { - configuration := NewConfiguration() - return &EchoServiceApi{ - Configuration: configuration, - } -} - -func NewEchoServiceApiWithBasePath(basePath string) *EchoServiceApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &EchoServiceApi{ - Configuration: configuration, - } -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param value - * @return *SubStringMessage - */ -func (a EchoServiceApi) Echo(value string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/a_bit_of_everything/echo/{value}" - localVarPath = strings.Replace(localVarPath, "{"+"value"+"}", fmt.Sprintf("%v", value), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param body - * @return *SubStringMessage - */ -func (a EchoServiceApi) Echo2(body string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/echo" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Summary: Echo rpc - * Description Echo - * - * @param value - * @return *SubStringMessage - */ -func (a EchoServiceApi) Echo3(value string) (*SubStringMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v2/example/echo" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // authentication '(OAuth2)' required - // oauth required - if a.Configuration.AccessToken != ""{ - localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken - } - // authentication '(BasicAuth)' required - // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() - } - // authentication '(ApiKeyAuth)' required - // set key with prefix in header - localVarHeaderParams["X-API-Key"] = a.Configuration.GetAPIKeyWithPrefix("X-API-Key") - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("value", a.Configuration.APIClient.ParameterToString(value, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", "application/x-foo-mime", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - "application/x-foo-mime", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(SubStringMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_a_bit_of_everything.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_a_bit_of_everything.go deleted file mode 100755 index cb6fb3a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_a_bit_of_everything.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -import ( - "time" -) - -type ExamplepbABitOfEverything struct { - - SingleNested ABitOfEverythingNested `json:"single_nested,omitempty"` - - Uuid string `json:"uuid,omitempty"` - - Nested []ABitOfEverythingNested `json:"nested,omitempty"` - - FloatValue float32 `json:"float_value,omitempty"` - - DoubleValue float64 `json:"double_value,omitempty"` - - Int64Value string `json:"int64_value,omitempty"` - - Uint64Value string `json:"uint64_value,omitempty"` - - Int32Value int32 `json:"int32_value,omitempty"` - - Fixed64Value string `json:"fixed64_value,omitempty"` - - Fixed32Value int64 `json:"fixed32_value,omitempty"` - - BoolValue bool `json:"bool_value,omitempty"` - - StringValue string `json:"string_value,omitempty"` - - BytesValue string `json:"bytes_value,omitempty"` - - Uint32Value int64 `json:"uint32_value,omitempty"` - - EnumValue ExamplepbNumericEnum `json:"enum_value,omitempty"` - - Sfixed32Value int32 `json:"sfixed32_value,omitempty"` - - Sfixed64Value string `json:"sfixed64_value,omitempty"` - - Sint32Value int32 `json:"sint32_value,omitempty"` - - Sint64Value string `json:"sint64_value,omitempty"` - - RepeatedStringValue []string `json:"repeated_string_value,omitempty"` - - OneofEmpty ProtobufEmpty `json:"oneof_empty,omitempty"` - - OneofString string `json:"oneof_string,omitempty"` - - MapValue map[string]ExamplepbNumericEnum `json:"map_value,omitempty"` - - MappedStringValue map[string]string `json:"mapped_string_value,omitempty"` - - MappedNestedValue map[string]ABitOfEverythingNested `json:"mapped_nested_value,omitempty"` - - NonConventionalNameValue string `json:"nonConventionalNameValue,omitempty"` - - TimestampValue time.Time `json:"timestamp_value,omitempty"` - - RepeatedEnumValue []ExamplepbNumericEnum `json:"repeated_enum_value,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_body.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_body.go deleted file mode 100755 index 13f4c2d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_body.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -type ExamplepbBody struct { - - Name string `json:"name,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_numeric_enum.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_numeric_enum.go deleted file mode 100755 index e953bbe..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/examplepb_numeric_enum.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -// NumericEnum is one or zero. - ZERO: ZERO means 0 - ONE: ONE means 1 -type ExamplepbNumericEnum struct { -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/nested_deep_enum.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/nested_deep_enum.go deleted file mode 100755 index e5fc17d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/nested_deep_enum.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -// DeepEnum is one or zero. - FALSE: FALSE is false. - TRUE: TRUE is true. -type NestedDeepEnum struct { -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/protobuf_empty.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/protobuf_empty.go deleted file mode 100755 index 97c7bf6..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/protobuf_empty.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. -type ProtobufEmpty struct { -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/sub_string_message.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/sub_string_message.go deleted file mode 100755 index 2a0874f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe/sub_string_message.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * A Bit of Everything - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * OpenAPI spec version: 1.0 - * Contact: none@example.com - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package abe - -type SubStringMessage struct { - - Value string `json:"value,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.gitignore deleted file mode 100755 index 2f88269..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/docs diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.swagger-codegen-ignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.swagger-codegen-ignore deleted file mode 100755 index 6c7b69a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/.swagger-codegen-ignore +++ /dev/null @@ -1 +0,0 @@ -.gitignore diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/BUILD.bazel deleted file mode 100755 index 090b56a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/BUILD.bazel +++ /dev/null @@ -1,17 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "api_client.go", - "api_response.go", - "configuration.go", - "echo_service_api.go", - "examplepb_embedded.go", - "examplepb_simple_message.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo", - deps = ["@com_github_go_resty_resty//:go_default_library"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_client.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_client.go deleted file mode 100755 index 7a51714..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_client.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -import ( - "bytes" - "fmt" - "path/filepath" - "reflect" - "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" -) - -type APIClient struct { - config *Configuration -} - -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { - - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - - if len(accepts) == 0 { - return "" - } - if contains(accepts, "application/json") { - return "application/json" - } - return strings.Join(accepts, ",") -} - -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } - - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient -} - -func (c *APIClient) prepareRequest( - rClient *resty.Client, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) *resty.Request { - - - request := rClient.R() - request.SetBody(postBody) - - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) - } - - // add header parameter, if any - if len(headerParams) > 0 { - request.SetHeaders(headerParams) - } - - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) - } - - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) - } - - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) - } - return request -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_response.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_response.go deleted file mode 100755 index 8b0d07c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/api_response.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -import ( - "net/http" -) - -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - // Operation is the name of the swagger operation. - Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. - Payload []byte `json:"-"` -} - -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/configuration.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/configuration.go deleted file mode 100755 index 9a75a30..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/configuration.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -import ( - "encoding/base64" - "net/http" - "time" -) - - -type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` -} - -func NewConfiguration() *Configuration { - cfg := &Configuration{ - BasePath: "http://localhost", - DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), - UserAgent: "Swagger-Codegen/1.0.0/go", - APIClient: &APIClient{}, - } - - cfg.APIClient.config = cfg - return cfg -} - -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/echo_service_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/echo_service_api.go deleted file mode 100755 index 775d0b3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/echo_service_api.go +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -import ( - "net/url" - "strings" - "encoding/json" - "fmt" -) - -type EchoServiceApi struct { - Configuration *Configuration -} - -func NewEchoServiceApi() *EchoServiceApi { - configuration := NewConfiguration() - return &EchoServiceApi{ - Configuration: configuration, - } -} - -func NewEchoServiceApiWithBasePath(basePath string) *EchoServiceApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &EchoServiceApi{ - Configuration: configuration, - } -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) Echo(id string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @param num - * @param lineNum - * @param lang - * @param statusProgress - * @param statusNote - * @param en - * @param noProgress - * @param noNote - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) Echo2(id string, num string, lineNum string, lang string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}/{num}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, "")) - localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, "")) - localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, "")) - localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, "")) - localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, "")) - localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, "")) - localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @param num - * @param lang - * @param lineNum - * @param statusProgress - * @param statusNote - * @param en - * @param noProgress - * @param noNote - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) Echo3(id string, num string, lang string, lineNum string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}/{num}/{lang}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) - localVarPath = strings.Replace(localVarPath, "{"+"lang"+"}", fmt.Sprintf("%v", lang), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, "")) - localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, "")) - localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, "")) - localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, "")) - localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, "")) - localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo3", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @param lineNum - * @param statusNote - * @param num - * @param lang - * @param statusProgress - * @param en - * @param noProgress - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) Echo4(id string, lineNum string, statusNote string, num string, lang string, statusProgress string, en string, noProgress string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo1/{id}/{line_num}/{status.note}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - localVarPath = strings.Replace(localVarPath, "{"+"line_num"+"}", fmt.Sprintf("%v", lineNum), -1) - localVarPath = strings.Replace(localVarPath, "{"+"status.note"+"}", fmt.Sprintf("%v", statusNote), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, "")) - localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, "")) - localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, "")) - localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, "")) - localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo4", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param noNote - * @param id Id represents the message identifier. - * @param num - * @param lineNum - * @param lang - * @param statusProgress - * @param en - * @param noProgress - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) Echo5(noNote string, id string, num string, lineNum string, lang string, statusProgress string, en string, noProgress string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo2/{no.note}" - localVarPath = strings.Replace(localVarPath, "{"+"no.note"+"}", fmt.Sprintf("%v", noNote), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, "")) - localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, "")) - localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, "")) - localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, "")) - localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, "")) - localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, "")) - localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo5", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * EchoBody method receives a simple message and returns it. - * - * @param body - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) EchoBody(body ExamplepbSimpleMessage) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo_body" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "EchoBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * EchoDelete method receives a simple message and returns it. - * - * @param id Id represents the message identifier. - * @param num - * @param lineNum - * @param lang - * @param statusProgress - * @param statusNote - * @param en - * @param noProgress - * @param noNote - * @return *ExamplepbSimpleMessage - */ -func (a EchoServiceApi) EchoDelete(id string, num string, lineNum string, lang string, statusProgress string, statusNote string, en string, noProgress string, noNote string) (*ExamplepbSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Delete") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo_delete" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, "")) - localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, "")) - localVarQueryParams.Add("line_num", a.Configuration.APIClient.ParameterToString(lineNum, "")) - localVarQueryParams.Add("lang", a.Configuration.APIClient.ParameterToString(lang, "")) - localVarQueryParams.Add("status.progress", a.Configuration.APIClient.ParameterToString(statusProgress, "")) - localVarQueryParams.Add("status.note", a.Configuration.APIClient.ParameterToString(statusNote, "")) - localVarQueryParams.Add("en", a.Configuration.APIClient.ParameterToString(en, "")) - localVarQueryParams.Add("no.progress", a.Configuration.APIClient.ParameterToString(noProgress, "")) - localVarQueryParams.Add("no.note", a.Configuration.APIClient.ParameterToString(noNote, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "EchoDelete", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_embedded.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_embedded.go deleted file mode 100755 index 4b5fe26..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_embedded.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -// Embedded represents a message embedded in SimpleMessage. -type ExamplepbEmbedded struct { - - Progress string `json:"progress,omitempty"` - - Note string `json:"note,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_simple_message.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_simple_message.go deleted file mode 100755 index 366a687..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo/examplepb_simple_message.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Echo Service - * - * Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package echo - -// SimpleMessage represents a simple message sent to the Echo service. -type ExamplepbSimpleMessage struct { - - // Id represents the message identifier. - Id string `json:"id,omitempty"` - - Num string `json:"num,omitempty"` - - LineNum string `json:"line_num,omitempty"` - - Lang string `json:"lang,omitempty"` - - Status ExamplepbEmbedded `json:"status,omitempty"` - - En string `json:"en,omitempty"` - - No ExamplepbEmbedded `json:"no,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.gitignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.gitignore deleted file mode 100755 index 2f88269..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/docs diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.swagger-codegen-ignore b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.swagger-codegen-ignore deleted file mode 100755 index 6c7b69a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/.swagger-codegen-ignore +++ /dev/null @@ -1 +0,0 @@ -.gitignore diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/BUILD.bazel deleted file mode 100755 index 611c6c7..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/BUILD.bazel +++ /dev/null @@ -1,16 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "api_client.go", - "api_response.go", - "configuration.go", - "examplepb_unannotated_simple_message.go", - "unannotated_echo_service_api.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho", - deps = ["@com_github_go_resty_resty//:go_default_library"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_client.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_client.go deleted file mode 100755 index aa4c1f1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_client.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * examples/proto/examplepb/unannotated_echo_service.proto - * - * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package unannotatedecho - -import ( - "bytes" - "fmt" - "path/filepath" - "reflect" - "strings" - "net/url" - "io/ioutil" - "github.com/go-resty/resty" -) - -type APIClient struct { - config *Configuration -} - -func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { - - if len(contentTypes) == 0 { - return "" - } - if contains(contentTypes, "application/json") { - return "application/json" - } - return contentTypes[0] // use the first content type specified in 'consumes' -} - -func (c *APIClient) SelectHeaderAccept(accepts []string) string { - - if len(accepts) == 0 { - return "" - } - if contains(accepts, "application/json") { - return "application/json" - } - return strings.Join(accepts, ",") -} - -func contains(haystack []string, needle string) bool { - for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { - return true - } - } - return false -} - -func (c *APIClient) CallAPI(path string, method string, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) (*resty.Response, error) { - - rClient := c.prepareClient() - request := c.prepareRequest(rClient, postBody, headerParams, queryParams, formParams, fileName, fileBytes) - - switch strings.ToUpper(method) { - case "GET": - response, err := request.Get(path) - return response, err - case "POST": - response, err := request.Post(path) - return response, err - case "PUT": - response, err := request.Put(path) - return response, err - case "PATCH": - response, err := request.Patch(path) - return response, err - case "DELETE": - response, err := request.Delete(path) - return response, err - } - - return nil, fmt.Errorf("invalid method %v", method) -} - -func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { - delimiter := "" - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," - } - - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") - } - - return fmt.Sprintf("%v", obj) -} - -func (c *APIClient) prepareClient() *resty.Client { - - rClient := resty.New() - - rClient.SetDebug(c.config.Debug) - if c.config.Transport != nil { - rClient.SetTransport(c.config.Transport) - } - - if c.config.Timeout != nil { - rClient.SetTimeout(*c.config.Timeout) - } - rClient.SetLogger(ioutil.Discard) - return rClient -} - -func (c *APIClient) prepareRequest( - rClient *resty.Client, - postBody interface{}, - headerParams map[string]string, - queryParams url.Values, - formParams map[string]string, - fileName string, - fileBytes []byte) *resty.Request { - - - request := rClient.R() - request.SetBody(postBody) - - if c.config.UserAgent != "" { - request.SetHeader("User-Agent", c.config.UserAgent) - } - - // add header parameter, if any - if len(headerParams) > 0 { - request.SetHeaders(headerParams) - } - - // add query parameter, if any - if len(queryParams) > 0 { - request.SetMultiValueQueryParams(queryParams) - } - - // add form parameter, if any - if len(formParams) > 0 { - request.SetFormData(formParams) - } - - if len(fileBytes) > 0 && fileName != "" { - _, fileNm := filepath.Split(fileName) - request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) - } - return request -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_response.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_response.go deleted file mode 100755 index 8d7af71..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/api_response.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * examples/proto/examplepb/unannotated_echo_service.proto - * - * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package unannotatedecho - -import ( - "net/http" -) - -type APIResponse struct { - *http.Response `json:"-"` - Message string `json:"message,omitempty"` - // Operation is the name of the swagger operation. - Operation string `json:"operation,omitempty"` - // RequestURL is the request URL. This value is always available, even if the - // embedded *http.Response is nil. - RequestURL string `json:"url,omitempty"` - // Method is the HTTP method used for the request. This value is always - // available, even if the embedded *http.Response is nil. - Method string `json:"method,omitempty"` - // Payload holds the contents of the response body (which may be nil or empty). - // This is provided here as the raw response.Body() reader will have already - // been drained. - Payload []byte `json:"-"` -} - -func NewAPIResponse(r *http.Response) *APIResponse { - - response := &APIResponse{Response: r} - return response -} - -func NewAPIResponseWithError(errorMessage string) *APIResponse { - - response := &APIResponse{Message: errorMessage} - return response -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/configuration.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/configuration.go deleted file mode 100755 index d8ed5f0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/configuration.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * examples/proto/examplepb/unannotated_echo_service.proto - * - * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package unannotatedecho - -import ( - "encoding/base64" - "net/http" - "time" -) - - -type Configuration struct { - Username string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` - APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` - APIKey map[string]string `json:"APIKey,omitempty"` - Debug bool `json:"debug,omitempty"` - DebugFile string `json:"debugFile,omitempty"` - OAuthToken string `json:"oAuthToken,omitempty"` - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - AccessToken string `json:"accessToken,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - APIClient *APIClient - Transport *http.Transport - Timeout *time.Duration `json:"timeout,omitempty"` -} - -func NewConfiguration() *Configuration { - cfg := &Configuration{ - BasePath: "http://localhost", - DefaultHeader: make(map[string]string), - APIKey: make(map[string]string), - APIKeyPrefix: make(map[string]string), - UserAgent: "Swagger-Codegen/1.0.0/go", - APIClient: &APIClient{}, - } - - cfg.APIClient.config = cfg - return cfg -} - -func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) -} - -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} - -func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { - if c.APIKeyPrefix[APIKeyIdentifier] != "" { - return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] - } - - return c.APIKey[APIKeyIdentifier] -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/examplepb_unannotated_simple_message.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/examplepb_unannotated_simple_message.go deleted file mode 100755 index 7791baa..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/examplepb_unannotated_simple_message.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * examples/proto/examplepb/unannotated_echo_service.proto - * - * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package unannotatedecho - -// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. -type ExamplepbUnannotatedSimpleMessage struct { - - // Id represents the message identifier. - Id string `json:"id,omitempty"` - - Num string `json:"num,omitempty"` - - Duration string `json:"duration,omitempty"` -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/unannotated_echo_service_api.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/unannotated_echo_service_api.go deleted file mode 100755 index 99f02f0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho/unannotated_echo_service_api.go +++ /dev/null @@ -1,290 +0,0 @@ -/* - * examples/proto/examplepb/unannotated_echo_service.proto - * - * Unannotated Echo Service Similar to echo_service.proto but without annotations. See unannotated_echo_service.yaml for the equivalent of the annotations in gRPC API configuration format. Echo Service API consists of a single service which returns a message. - * - * OpenAPI spec version: version not set - * - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package unannotatedecho - -import ( - "net/url" - "strings" - "encoding/json" - "fmt" -) - -type UnannotatedEchoServiceApi struct { - Configuration *Configuration -} - -func NewUnannotatedEchoServiceApi() *UnannotatedEchoServiceApi { - configuration := NewConfiguration() - return &UnannotatedEchoServiceApi{ - Configuration: configuration, - } -} - -func NewUnannotatedEchoServiceApiWithBasePath(basePath string) *UnannotatedEchoServiceApi { - configuration := NewConfiguration() - configuration.BasePath = basePath - - return &UnannotatedEchoServiceApi{ - Configuration: configuration, - } -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @return *ExamplepbUnannotatedSimpleMessage - */ -func (a UnannotatedEchoServiceApi) Echo(id string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbUnannotatedSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * Echo method receives a simple message and returns it. - * The message posted as the id parameter will also be returned. - * - * @param id - * @param num - * @param duration - * @return *ExamplepbUnannotatedSimpleMessage - */ -func (a UnannotatedEchoServiceApi) Echo2(id string, num string, duration string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Get") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo/{id}/{num}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) - localVarPath = strings.Replace(localVarPath, "{"+"num"+"}", fmt.Sprintf("%v", num), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("duration", a.Configuration.APIClient.ParameterToString(duration, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbUnannotatedSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "Echo2", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * EchoBody method receives a simple message and returns it. - * - * @param body - * @return *ExamplepbUnannotatedSimpleMessage - */ -func (a UnannotatedEchoServiceApi) EchoBody(body ExamplepbUnannotatedSimpleMessage) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Post") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo_body" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - localVarPostBody = &body - var successPayload = new(ExamplepbUnannotatedSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "EchoBody", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - -/** - * EchoDelete method receives a simple message and returns it. - * - * @param id Id represents the message identifier. - * @param num - * @param duration - * @return *ExamplepbUnannotatedSimpleMessage - */ -func (a UnannotatedEchoServiceApi) EchoDelete(id string, num string, duration string) (*ExamplepbUnannotatedSimpleMessage, *APIResponse, error) { - - var localVarHttpMethod = strings.ToUpper("Delete") - // create path and map variables - localVarPath := a.Configuration.BasePath + "/v1/example/echo_delete" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := make(map[string]string) - var localVarPostBody interface{} - var localVarFileName string - var localVarFileBytes []byte - // add default headers if any - for key := range a.Configuration.DefaultHeader { - localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] - } - localVarQueryParams.Add("id", a.Configuration.APIClient.ParameterToString(id, "")) - localVarQueryParams.Add("num", a.Configuration.APIClient.ParameterToString(num, "")) - localVarQueryParams.Add("duration", a.Configuration.APIClient.ParameterToString(duration, "")) - - // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } - - // set Content-Type header - localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - // to determine the Accept header - localVarHttpHeaderAccepts := []string{ - "application/json", - } - - // set Accept header - localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - var successPayload = new(ExamplepbUnannotatedSimpleMessage) - localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - - var localVarURL, _ = url.Parse(localVarPath) - localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "EchoDelete", Method: localVarHttpMethod, RequestURL: localVarURL.String()} - if localVarHttpResponse != nil { - localVarAPIResponse.Response = localVarHttpResponse.RawResponse - localVarAPIResponse.Payload = localVarHttpResponse.Body() - } - - if err != nil { - return successPayload, localVarAPIResponse, err - } - err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) - return successPayload, localVarAPIResponse, err -} - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/BUILD.bazel deleted file mode 100755 index 0f7c505..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/BUILD.bazel +++ /dev/null @@ -1,18 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -go_library( - name = "go_default_library", - srcs = ["main.go"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server", - visibility = ["//visibility:private"], - deps = [ - "//examples/gateway:go_default_library", - "@com_github_golang_glog//:go_default_library", - ], -) - -go_binary( - name = "example-gateway-server", - embed = [":go_default_library"], - visibility = ["//visibility:public"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/main.go deleted file mode 100755 index 0273ffb..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-gateway-server/main.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Command example-gateway-server is an example reverse-proxy implementation -whose HTTP handler is generated by grpc-gateway. -*/ -package main - -import ( - "context" - "flag" - - "github.com/golang/glog" - "github.com/grpc-ecosystem/grpc-gateway/examples/gateway" -) - -var ( - endpoint = flag.String("endpoint", "localhost:9090", "endpoint of the gRPC service") - network = flag.String("network", "tcp", `one of "tcp" or "unix". Must be consistent to -endpoint`) - swaggerDir = flag.String("swagger_dir", "examples/proto/examplepb", "path to the directory which contains swagger definitions") -) - -func main() { - flag.Parse() - defer glog.Flush() - - ctx := context.Background() - opts := gateway.Options{ - Addr: ":8080", - GRPCServer: gateway.Endpoint{ - Network: *network, - Addr: *endpoint, - }, - SwaggerDir: *swaggerDir, - } - if err := gateway.Run(ctx, opts); err != nil { - glog.Fatal(err) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/BUILD.bazel deleted file mode 100755 index 1c66416..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/BUILD.bazel +++ /dev/null @@ -1,19 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") - -package(default_visibility = ["//visibility:private"]) - -go_library( - name = "go_default_library", - srcs = ["main.go"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server", - deps = [ - "//examples/server:go_default_library", - "@com_github_golang_glog//:go_default_library", - ], -) - -go_binary( - name = "example-server", - embed = [":go_default_library"], - visibility = ["//visibility:public"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/main.go deleted file mode 100755 index 7f6c45f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/cmd/example-grpc-server/main.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Command example-grpc-server is an example grpc server -to be called by example-gateway-server. -*/ -package main - -import ( - "context" - "flag" - - "github.com/golang/glog" - "github.com/grpc-ecosystem/grpc-gateway/examples/server" -) - -var ( - addr = flag.String("addr", ":9090", "endpoint of the gRPC service") - network = flag.String("network", "tcp", "a valid network type which is consistent to -addr") -) - -func main() { - flag.Parse() - defer glog.Flush() - - ctx := context.Background() - if err := server.Run(ctx, *network, *addr); err != nil { - glog.Fatal(err) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/BUILD.bazel deleted file mode 100755 index 393a7c4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/BUILD.bazel +++ /dev/null @@ -1,20 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "gateway.go", - "handlers.go", - "main.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/gateway", - visibility = ["//visibility:public"], - deps = [ - "//examples/proto/examplepb:go_default_library", - "//runtime:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@org_golang_google_grpc//:go_default_library", - "@org_golang_google_grpc//connectivity:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/doc.go deleted file mode 100755 index a9ca836..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package gateway is an example of grpc-gateway server -package gateway diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/gateway.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/gateway.go deleted file mode 100755 index ffdbe2c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/gateway.go +++ /dev/null @@ -1,57 +0,0 @@ -package gateway - -import ( - "context" - "fmt" - "net" - "net/http" - "time" - - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc" -) - -// newGateway returns a new gateway server which translates HTTP into gRPC. -func newGateway(ctx context.Context, conn *grpc.ClientConn, opts []gwruntime.ServeMuxOption) (http.Handler, error) { - - mux := gwruntime.NewServeMux(opts...) - - for _, f := range []func(context.Context, *gwruntime.ServeMux, *grpc.ClientConn) error{ - examplepb.RegisterEchoServiceHandler, - examplepb.RegisterStreamServiceHandler, - examplepb.RegisterABitOfEverythingServiceHandler, - examplepb.RegisterFlowCombinationHandler, - } { - if err := f(ctx, mux, conn); err != nil { - return nil, err - } - } - return mux, nil -} - -func dial(ctx context.Context, network, addr string) (*grpc.ClientConn, error) { - switch network { - case "tcp": - return dialTCP(ctx, addr) - case "unix": - return dialUnix(ctx, addr) - default: - return nil, fmt.Errorf("unsupported network type %q", network) - } -} - -// dialTCP creates a client connection via TCP. -// "addr" must be a valid TCP address with a port number. -func dialTCP(ctx context.Context, addr string) (*grpc.ClientConn, error) { - return grpc.DialContext(ctx, addr, grpc.WithInsecure()) -} - -// dialUnix creates a client connection via a unix domain socket. -// "addr" must be a valid path to the socket. -func dialUnix(ctx context.Context, addr string) (*grpc.ClientConn, error) { - d := func(addr string, timeout time.Duration) (net.Conn, error) { - return net.DialTimeout("unix", addr, timeout) - } - return grpc.DialContext(ctx, addr, grpc.WithInsecure(), grpc.WithDialer(d)) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/handlers.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/handlers.go deleted file mode 100755 index d52580f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/handlers.go +++ /dev/null @@ -1,61 +0,0 @@ -package gateway - -import ( - "fmt" - "net/http" - "path" - "strings" - - "github.com/golang/glog" - "google.golang.org/grpc" - "google.golang.org/grpc/connectivity" -) - -func swaggerServer(dir string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !strings.HasSuffix(r.URL.Path, ".swagger.json") { - glog.Errorf("Not Found: %s", r.URL.Path) - http.NotFound(w, r) - return - } - - glog.Infof("Serving %s", r.URL.Path) - p := strings.TrimPrefix(r.URL.Path, "/swagger/") - p = path.Join(dir, p) - http.ServeFile(w, r, p) - } -} - -// allowCORS allows Cross Origin Resoruce Sharing from any origin. -// Don't do this without consideration in production systems. -func allowCORS(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if origin := r.Header.Get("Origin"); origin != "" { - w.Header().Set("Access-Control-Allow-Origin", origin) - if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" { - preflightHandler(w, r) - return - } - } - h.ServeHTTP(w, r) - }) -} - -func preflightHandler(w http.ResponseWriter, r *http.Request) { - headers := []string{"Content-Type", "Accept"} - w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ",")) - methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"} - w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ",")) - glog.Infof("preflight request for %s", r.URL.Path) -} - -func healthzServer(conn *grpc.ClientConn) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain") - if s := conn.GetState(); s != connectivity.Ready { - http.Error(w, fmt.Sprintf("grpc server is %s", s), http.StatusBadGateway) - return - } - fmt.Fprintln(w, "ok") - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/main.go deleted file mode 100755 index ea8c683..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/gateway/main.go +++ /dev/null @@ -1,77 +0,0 @@ -package gateway - -import ( - "context" - "net/http" - - "github.com/golang/glog" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -// Endpoint describes a gRPC endpoint -type Endpoint struct { - Network, Addr string -} - -// Options is a set of options to be passed to Run -type Options struct { - // Addr is the address to listen - Addr string - - // GRPCServer defines an endpoint of a gRPC service - GRPCServer Endpoint - - // SwaggerDir is a path to a directory from which the server - // serves swagger specs. - SwaggerDir string - - // Mux is a list of options to be passed to the grpc-gateway multiplexer - Mux []gwruntime.ServeMuxOption -} - -// Run starts a HTTP server and blocks while running if successful. -// The server will be shutdown when "ctx" is canceled. -func Run(ctx context.Context, opts Options) error { - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - conn, err := dial(ctx, opts.GRPCServer.Network, opts.GRPCServer.Addr) - if err != nil { - return err - } - go func() { - <-ctx.Done() - if err := conn.Close(); err != nil { - glog.Errorf("Failed to close a client connection to the gRPC server: %v", err) - } - }() - - mux := http.NewServeMux() - mux.HandleFunc("/swagger/", swaggerServer(opts.SwaggerDir)) - mux.HandleFunc("/healthz", healthzServer(conn)) - - gw, err := newGateway(ctx, conn, opts.Mux) - if err != nil { - return err - } - mux.Handle("/", gw) - - s := &http.Server{ - Addr: opts.Addr, - Handler: allowCORS(mux), - } - go func() { - <-ctx.Done() - glog.Infof("Shutting down the http server") - if err := s.Shutdown(context.Background()); err != nil { - glog.Errorf("Failed to shutdown http server: %v", err) - } - }() - - glog.Infof("Starting listening at %s", opts.Addr) - if err := s.ListenAndServe(); err != http.ErrServerClosed { - glog.Errorf("Failed to listen and serve: %v", err) - return err - } - return nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/BUILD.bazel deleted file mode 100755 index c603d01..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/BUILD.bazel +++ /dev/null @@ -1,27 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_test") - -go_test( - name = "go_default_xtest", - srcs = [ - "client_test.go", - "integration_test.go", - "main_test.go", - "proto_error_test.go", - ], - deps = [ - "//examples/clients/abe:go_default_library", - "//examples/clients/echo:go_default_library", - "//examples/clients/unannotatedecho:go_default_library", - "//examples/gateway:go_default_library", - "//examples/proto/examplepb:go_default_library", - "//examples/proto/sub:go_default_library", - "//examples/server:go_default_library", - "//runtime:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//ptypes/empty:go_default_library", - "@org_golang_google_genproto//googleapis/rpc/status:go_default_library", - "@org_golang_google_grpc//codes:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/client_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/client_test.go deleted file mode 100755 index b49a2f3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/client_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package integration_test - -import ( - "reflect" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/examples/clients/abe" - "github.com/grpc-ecosystem/grpc-gateway/examples/clients/echo" - "github.com/grpc-ecosystem/grpc-gateway/examples/clients/unannotatedecho" -) - -func TestClientIntegration(t *testing.T) { -} - -func TestEchoClient(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - cl := echo.NewEchoServiceApiWithBasePath("http://localhost:8080") - resp, _, err := cl.Echo("foo") - if err != nil { - t.Errorf(`cl.Echo("foo") failed with %v; want success`, err) - } - if got, want := resp.Id, "foo"; got != want { - t.Errorf("resp.Id = %q; want %q", got, want) - } -} - -func TestEchoBodyClient(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - cl := echo.NewEchoServiceApiWithBasePath("http://localhost:8080") - req := echo.ExamplepbSimpleMessage{Id: "foo"} - resp, _, err := cl.EchoBody(req) - if err != nil { - t.Errorf("cl.EchoBody(%#v) failed with %v; want success", req, err) - } - if got, want := resp.Id, "foo"; got != want { - t.Errorf("resp.Id = %q; want %q", got, want) - } -} - -func TestAbitOfEverythingClient(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - cl := abe.NewABitOfEverythingServiceApiWithBasePath("http://localhost:8080") - testABEClientCreate(t, cl) - testABEClientCreateBody(t, cl) -} - -func testABEClientCreate(t *testing.T, cl *abe.ABitOfEverythingServiceApi) { - want := &abe.ExamplepbABitOfEverything{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: "4294967296", - Uint64Value: "9223372036854775807", - Int32Value: -2147483648, - Fixed64Value: "9223372036854775807", - Fixed32Value: 4294967295, - BoolValue: true, - StringValue: "strprefix/foo", - Uint32Value: 4294967295, - Sfixed32Value: 2147483647, - Sfixed64Value: "-4611686018427387904", - Sint32Value: 2147483647, - Sint64Value: "4611686018427387903", - NonConventionalNameValue: "camelCase", - } - resp, _, err := cl.Create( - want.FloatValue, - want.DoubleValue, - want.Int64Value, - want.Uint64Value, - want.Int32Value, - want.Fixed64Value, - want.Fixed32Value, - want.BoolValue, - want.StringValue, - want.Uint32Value, - want.Sfixed32Value, - want.Sfixed64Value, - want.Sint32Value, - want.Sint64Value, - want.NonConventionalNameValue, - ) - if err != nil { - t.Errorf("cl.Create(%#v) failed with %v; want success", want, err) - } - if resp.Uuid == "" { - t.Errorf("resp.Uuid is empty; want not empty") - } - resp.Uuid = "" - if got := resp; !reflect.DeepEqual(got, want) { - t.Errorf("resp = %#v; want %#v", got, want) - } -} - -func testABEClientCreateBody(t *testing.T, cl *abe.ABitOfEverythingServiceApi) { - t.Log("TODO: support enum") - return - - want := abe.ExamplepbABitOfEverything{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: "4294967296", - Uint64Value: "9223372036854775807", - Int32Value: -2147483648, - Fixed64Value: "9223372036854775807", - Fixed32Value: 4294967295, - BoolValue: true, - StringValue: "strprefix/foo", - Uint32Value: 4294967295, - Sfixed32Value: 2147483647, - Sfixed64Value: "-4611686018427387904", - Sint32Value: 2147483647, - Sint64Value: "4611686018427387903", - NonConventionalNameValue: "camelCase", - - Nested: []abe.ABitOfEverythingNested{ - { - Name: "bar", - Amount: 10, - }, - { - Name: "baz", - Amount: 20, - }, - }, - RepeatedStringValue: []string{"a", "b", "c"}, - OneofString: "x", - MapValue: map[string]abe.ExamplepbNumericEnum{ - // "a": abe.ExamplepbNumericEnum_ONE, - // "b": abe.ExamplepbNumericEnum_ZERO, - }, - MappedStringValue: map[string]string{ - "a": "x", - "b": "y", - }, - MappedNestedValue: map[string]abe.ABitOfEverythingNested{ - "a": {Name: "x", Amount: 1}, - "b": {Name: "y", Amount: 2}, - }, - } - resp, _, err := cl.CreateBody(want) - if err != nil { - t.Errorf("cl.CreateBody(%#v) failed with %v; want success", want, err) - } - if resp.Uuid == "" { - t.Errorf("resp.Uuid is empty; want not empty") - } - resp.Uuid = "" - if got := resp; !reflect.DeepEqual(got, want) { - t.Errorf("resp = %#v; want %#v", got, want) - } -} - -func TestUnannotatedEchoClient(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - cl := unannotatedecho.NewUnannotatedEchoServiceApiWithBasePath("http://localhost:8080") - resp, _, err := cl.Echo("foo") - if err != nil { - t.Errorf(`cl.Echo("foo") failed with %v; want success`, err) - } - if got, want := resp.Id, "foo"; got != want { - t.Errorf("resp.Id = %q; want %q", got, want) - } -} - -func TestUnannotatedEchoBodyClient(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - cl := unannotatedecho.NewUnannotatedEchoServiceApiWithBasePath("http://localhost:8080") - req := unannotatedecho.ExamplepbUnannotatedSimpleMessage{Id: "foo"} - resp, _, err := cl.EchoBody(req) - if err != nil { - t.Errorf("cl.EchoBody(%#v) failed with %v; want success", req, err) - } - if got, want := resp.Id, "foo"; got != want { - t.Errorf("resp.Id = %q; want %q", got, want) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/integration_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/integration_test.go deleted file mode 100755 index 0c2885c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/integration_test.go +++ /dev/null @@ -1,982 +0,0 @@ -package integration_test - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" - "sync" - "testing" - - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - gw "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc/codes" -) - -type errorBody struct { - Error string `json:"error"` - Code int `json:"code"` - Details []interface{} `json:"details"` -} - -func TestEcho(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - testEcho(t, 8080, "application/json") - testEchoOneof(t, 8080, "application/json") - testEchoOneof1(t, 8080, "application/json") - testEchoOneof2(t, 8080, "application/json") - testEchoBody(t, 8080) -} - -func TestForwardResponseOption(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - go func() { - if err := runGateway( - ctx, - ":8081", - runtime.WithForwardResponseOption( - func(_ context.Context, w http.ResponseWriter, _ proto.Message) error { - w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1.1+json") - return nil - }, - ), - ); err != nil { - t.Errorf("runGateway() failed with %v; want success", err) - return - } - }() - if err := waitForGateway(ctx, 8081); err != nil { - t.Errorf("waitForGateway(ctx, 8081) failed with %v; want success", err) - } - testEcho(t, 8081, "application/vnd.docker.plugins.v1.1+json") -} - -func testEcho(t *testing.T, port int, contentType string) { - url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", port) - resp, err := http.Post(url, "application/json", strings.NewReader("{}")) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got, want := msg.Id, "myid"; got != want { - t.Errorf("msg.Id = %q; want %q", got, want) - } - - if value := resp.Header.Get("Content-Type"); value != contentType { - t.Errorf("Content-Type was %s, wanted %s", value, contentType) - } -} - -func testEchoOneof(t *testing.T, port int, contentType string) { - url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid/10/golang", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got, want := msg.GetLang(), "golang"; got != want { - t.Errorf("msg.GetLang() = %q; want %q", got, want) - } - - if value := resp.Header.Get("Content-Type"); value != contentType { - t.Errorf("Content-Type was %s, wanted %s", value, contentType) - } -} - -func testEchoOneof1(t *testing.T, port int, contentType string) { - url := fmt.Sprintf("http://localhost:%d/v1/example/echo1/myid/10/golang", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got, want := msg.GetStatus().GetNote(), "golang"; got != want { - t.Errorf("msg.GetStatus().GetNote() = %q; want %q", got, want) - } - - if value := resp.Header.Get("Content-Type"); value != contentType { - t.Errorf("Content-Type was %s, wanted %s", value, contentType) - } -} - -func testEchoOneof2(t *testing.T, port int, contentType string) { - url := fmt.Sprintf("http://localhost:%d/v1/example/echo2/golang", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got, want := msg.GetNo().GetNote(), "golang"; got != want { - t.Errorf("msg.GetNo().GetNote() = %q; want %q", got, want) - } - - if value := resp.Header.Get("Content-Type"); value != contentType { - t.Errorf("Content-Type was %s, wanted %s", value, contentType) - } -} - -func testEchoBody(t *testing.T, port int) { - sent := gw.SimpleMessage{Id: "example"} - var m jsonpb.Marshaler - payload, err := m.MarshalToString(&sent) - if err != nil { - t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", payload, err) - } - - url := fmt.Sprintf("http://localhost:%d/v1/example/echo_body", port) - resp, err := http.Post(url, "", strings.NewReader(payload)) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var received gw.SimpleMessage - if err := jsonpb.UnmarshalString(string(buf), &received); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got, want := received, sent; !reflect.DeepEqual(got, want) { - t.Errorf("msg.Id = %q; want %q", got, want) - } - - if got, want := resp.Header.Get("Grpc-Metadata-Foo"), "foo1"; got != want { - t.Errorf("Grpc-Metadata-Foo was %q, wanted %q", got, want) - } - if got, want := resp.Header.Get("Grpc-Metadata-Bar"), "bar1"; got != want { - t.Errorf("Grpc-Metadata-Bar was %q, wanted %q", got, want) - } - - if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { - t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { - t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) - } -} - -func TestABE(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - testABECreate(t, 8080) - testABECreateBody(t, 8080) - testABEBulkCreate(t, 8080) - testABELookup(t, 8080) - testABELookupNotFound(t, 8080) - testABEList(t, 8080) - testABEBulkEcho(t, 8080) - testABEBulkEchoZeroLength(t, 8080) - testAdditionalBindings(t, 8080) -} - -func testABECreate(t *testing.T, port int) { - want := gw.ABitOfEverything{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: 4294967296, - Uint64Value: 9223372036854775807, - Int32Value: -2147483648, - Fixed64Value: 9223372036854775807, - Fixed32Value: 4294967295, - BoolValue: true, - StringValue: "strprefix/foo", - Uint32Value: 4294967295, - Sfixed32Value: 2147483647, - Sfixed64Value: -4611686018427387904, - Sint32Value: 2147483647, - Sint64Value: 4611686018427387903, - NonConventionalNameValue: "camelCase", - } - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/%f/%f/%d/separator/%d/%d/%d/%d/%v/%s/%d/%d/%d/%d/%d/%s", port, want.FloatValue, want.DoubleValue, want.Int64Value, want.Uint64Value, want.Int32Value, want.Fixed64Value, want.Fixed32Value, want.BoolValue, want.StringValue, want.Uint32Value, want.Sfixed32Value, want.Sfixed64Value, want.Sint32Value, want.Sint64Value, want.NonConventionalNameValue) - - resp, err := http.Post(url, "application/json", strings.NewReader("{}")) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if msg.Uuid == "" { - t.Error("msg.Uuid is empty; want not empty") - } - msg.Uuid = "" - if got := msg; !reflect.DeepEqual(got, want) { - t.Errorf("msg= %v; want %v", &got, &want) - } -} - -func testABECreateBody(t *testing.T, port int) { - want := gw.ABitOfEverything{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: 4294967296, - Uint64Value: 9223372036854775807, - Int32Value: -2147483648, - Fixed64Value: 9223372036854775807, - Fixed32Value: 4294967295, - BoolValue: true, - StringValue: "strprefix/foo", - Uint32Value: 4294967295, - Sfixed32Value: 2147483647, - Sfixed64Value: -4611686018427387904, - Sint32Value: 2147483647, - Sint64Value: 4611686018427387903, - NonConventionalNameValue: "camelCase", - - Nested: []*gw.ABitOfEverything_Nested{ - { - Name: "bar", - Amount: 10, - }, - { - Name: "baz", - Amount: 20, - }, - }, - RepeatedStringValue: []string{"a", "b", "c"}, - OneofValue: &gw.ABitOfEverything_OneofString{ - OneofString: "x", - }, - MapValue: map[string]gw.NumericEnum{ - "a": gw.NumericEnum_ONE, - "b": gw.NumericEnum_ZERO, - }, - MappedStringValue: map[string]string{ - "a": "x", - "b": "y", - }, - MappedNestedValue: map[string]*gw.ABitOfEverything_Nested{ - "a": {Name: "x", Amount: 1}, - "b": {Name: "y", Amount: 2}, - }, - } - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - var m jsonpb.Marshaler - payload, err := m.MarshalToString(&want) - if err != nil { - t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", want, err) - } - - resp, err := http.Post(url, "application/json", strings.NewReader(payload)) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg gw.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if msg.Uuid == "" { - t.Error("msg.Uuid is empty; want not empty") - } - msg.Uuid = "" - if got := msg; !reflect.DeepEqual(got, want) { - t.Errorf("msg= %v; want %v", &got, &want) - } -} - -func testABEBulkCreate(t *testing.T, port int) { - count := 0 - r, w := io.Pipe() - go func(w io.WriteCloser) { - defer func() { - if cerr := w.Close(); cerr != nil { - t.Errorf("w.Close() failed with %v; want success", cerr) - } - }() - for _, val := range []string{ - "foo", "bar", "baz", "qux", "quux", - } { - want := gw.ABitOfEverything{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: 4294967296, - Uint64Value: 9223372036854775807, - Int32Value: -2147483648, - Fixed64Value: 9223372036854775807, - Fixed32Value: 4294967295, - BoolValue: true, - StringValue: fmt.Sprintf("strprefix/%s", val), - Uint32Value: 4294967295, - Sfixed32Value: 2147483647, - Sfixed64Value: -4611686018427387904, - Sint32Value: 2147483647, - Sint64Value: 4611686018427387903, - NonConventionalNameValue: "camelCase", - - Nested: []*gw.ABitOfEverything_Nested{ - { - Name: "hoge", - Amount: 10, - }, - { - Name: "fuga", - Amount: 20, - }, - }, - } - var m jsonpb.Marshaler - if err := m.Marshal(w, &want); err != nil { - t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err) - } - if _, err := io.WriteString(w, "\n"); err != nil { - t.Errorf("w.Write(%q) failed with %v; want success", "\n", err) - return - } - count++ - } - }(w) - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/bulk", port) - resp, err := http.Post(url, "application/json", r) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg empty.Empty - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - - if got, want := resp.Header.Get("Grpc-Metadata-Count"), fmt.Sprintf("%d", count); got != want { - t.Errorf("Grpc-Metadata-Count was %q, wanted %q", got, want) - } - - if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { - t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { - t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) - } -} - -func testABELookup(t *testing.T, port int) { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - cresp, err := http.Post(url, "application/json", strings.NewReader(` - {"bool_value": true, "string_value": "strprefix/example"} - `)) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer cresp.Body.Close() - buf, err := ioutil.ReadAll(cresp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(cresp.Body) failed with %v; want success", err) - return - } - if got, want := cresp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - return - } - - var want gw.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &want); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &want) failed with %v; want success", buf, err) - return - } - - url = fmt.Sprintf("%s/%s", url, want.Uuid) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - - buf, err = ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - var msg gw.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - if got := msg; !reflect.DeepEqual(got, want) { - t.Errorf("msg= %v; want %v", &got, &want) - } - - if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), want.Uuid; got != want { - t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) - } -} - -func testABELookupNotFound(t *testing.T, port int) { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - uuid := "not_exist" - url = fmt.Sprintf("%s/%s", url, uuid) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusNotFound; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - return - } - - var msg errorBody - if err := json.Unmarshal(buf, &msg); err != nil { - t.Errorf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) - return - } - - if got, want := msg.Code, int(codes.NotFound); got != want { - t.Errorf("msg.Code = %d; want %d", got, want) - return - } - - if got, want := msg.Error, "not found"; got != want { - t.Errorf("msg.Error = %s; want %s", got, want) - return - } - - if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), uuid; got != want { - t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { - t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { - t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) - } -} - -func testABEList(t *testing.T, port int) { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - - dec := json.NewDecoder(resp.Body) - var i int - for i = 0; ; i++ { - var item struct { - Result json.RawMessage `json:"result"` - Error map[string]interface{} `json:"error"` - } - err := dec.Decode(&item) - if err == io.EOF { - break - } - if err != nil { - t.Errorf("dec.Decode(&item) failed with %v; want success; i = %d", err, i) - } - if len(item.Error) != 0 { - t.Errorf("item.Error = %#v; want empty; i = %d", item.Error, i) - continue - } - var msg gw.ABitOfEverything - if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", item.Result, err) - } - } - if i <= 0 { - t.Errorf("i == %d; want > 0", i) - } - - value := resp.Header.Get("Grpc-Metadata-Count") - if value == "" { - t.Errorf("Grpc-Metadata-Count should not be empty") - } - - count, err := strconv.Atoi(value) - if err != nil { - t.Errorf("failed to Atoi %q: %v", value, err) - } - - if count <= 0 { - t.Errorf("count == %d; want > 0", count) - } -} - -func testABEBulkEcho(t *testing.T, port int) { - reqr, reqw := io.Pipe() - var wg sync.WaitGroup - var want []*sub.StringMessage - wg.Add(1) - go func() { - defer wg.Done() - defer reqw.Close() - var m jsonpb.Marshaler - for i := 0; i < 1000; i++ { - msg := sub.StringMessage{Value: proto.String(fmt.Sprintf("message %d", i))} - buf, err := m.MarshalToString(&msg) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) - return - } - if _, err := fmt.Fprintln(reqw, buf); err != nil { - t.Errorf("fmt.Fprintln(reqw, %q) failed with %v; want success", buf, err) - return - } - want = append(want, &msg) - } - }() - - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port) - req, err := http.NewRequest("POST", url, reqr) - if err != nil { - t.Errorf("http.NewRequest(%q, %q, reqr) failed with %v; want success", "POST", url, err) - return - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Transfer-Encoding", "chunked") - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("http.Post(%q, %q, req) failed with %v; want success", url, "application/json", err) - return - } - defer resp.Body.Close() - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - } - - var got []*sub.StringMessage - wg.Add(1) - go func() { - defer wg.Done() - - dec := json.NewDecoder(resp.Body) - for i := 0; ; i++ { - var item struct { - Result json.RawMessage `json:"result"` - Error map[string]interface{} `json:"error"` - } - err := dec.Decode(&item) - if err == io.EOF { - break - } - if err != nil { - t.Errorf("dec.Decode(&item) failed with %v; want success; i = %d", err, i) - } - if len(item.Error) != 0 { - t.Errorf("item.Error = %#v; want empty; i = %d", item.Error, i) - continue - } - var msg sub.StringMessage - if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &msg) failed with %v; want success", item.Result, err) - } - got = append(got, &msg) - } - }() - - wg.Wait() - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want %v", got, want) - } -} - -func testABEBulkEchoZeroLength(t *testing.T, port int) { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo", port) - req, err := http.NewRequest("POST", url, bytes.NewReader(nil)) - if err != nil { - t.Errorf("http.NewRequest(%q, %q, bytes.NewReader(nil)) failed with %v; want success", "POST", url, err) - return - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Transfer-Encoding", "chunked") - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("http.Post(%q, %q, req) failed with %v; want success", url, "application/json", err) - return - } - defer resp.Body.Close() - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - } - - dec := json.NewDecoder(resp.Body) - var item struct { - Result json.RawMessage `json:"result"` - Error map[string]interface{} `json:"error"` - } - if err := dec.Decode(&item); err == nil { - t.Errorf("dec.Decode(&item) succeeded; want io.EOF; item = %#v", item) - } else if err != io.EOF { - t.Errorf("dec.Decode(&item) failed with %v; want success", err) - return - } -} - -func testAdditionalBindings(t *testing.T, port int) { - for i, f := range []func() *http.Response{ - func() *http.Response { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything/echo/hello", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return nil - } - return resp - }, - func() *http.Response { - url := fmt.Sprintf("http://localhost:%d/v2/example/echo", port) - resp, err := http.Post(url, "application/json", strings.NewReader(`"hello"`)) - if err != nil { - t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", url, "application/json", `"hello"`, err) - return nil - } - return resp - }, - func() *http.Response { - r, w := io.Pipe() - go func() { - defer w.Close() - w.Write([]byte(`"hello"`)) - }() - url := fmt.Sprintf("http://localhost:%d/v2/example/echo", port) - resp, err := http.Post(url, "application/json", r) - if err != nil { - t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", url, "application/json", `"hello"`, err) - return nil - } - return resp - }, - func() *http.Response { - url := fmt.Sprintf("http://localhost:%d/v2/example/echo?value=hello", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return nil - } - return resp - }, - } { - resp := f() - if resp == nil { - continue - } - - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success; i=%d", err, i) - return - } - if got, want := resp.StatusCode, http.StatusOK; got != want { - t.Errorf("resp.StatusCode = %d; want %d; i=%d", got, want, i) - t.Logf("%s", buf) - } - - var msg sub.StringMessage - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success; %d", buf, err, i) - return - } - if got, want := msg.GetValue(), "hello"; got != want { - t.Errorf("msg.GetValue() = %q; want %q", got, want) - } - } -} - -func TestTimeout(t *testing.T) { - url := "http://localhost:8080/v2/example/timeout" - req, err := http.NewRequest("GET", url, nil) - if err != nil { - t.Errorf(`http.NewRequest("GET", %q, nil) failed with %v; want success`, url, err) - return - } - req.Header.Set("Grpc-Timeout", "10m") - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Errorf("http.DefaultClient.Do(%#v) failed with %v; want success", req, err) - return - } - defer resp.Body.Close() - - if got, want := resp.StatusCode, http.StatusGatewayTimeout; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - } -} - -func TestErrorWithDetails(t *testing.T) { - url := "http://localhost:8080/v2/example/errorwithdetails" - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatalf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - } - - if got, want := resp.StatusCode, http.StatusInternalServerError; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - } - - var msg errorBody - if err := json.Unmarshal(buf, &msg); err != nil { - t.Fatalf("json.Unmarshal(%s, &msg) failed with %v; want success", buf, err) - } - - if got, want := msg.Code, int(codes.Unknown); got != want { - t.Errorf("msg.Code = %d; want %d", got, want) - } - if got, want := msg.Error, "with details"; got != want { - t.Errorf("msg.Error = %s; want %s", got, want) - } - if got, want := len(msg.Details), 1; got != want { - t.Fatalf("len(msg.Details) = %q; want %q", got, want) - } - - details, ok := msg.Details[0].(map[string]interface{}) - if got, want := ok, true; got != want { - t.Fatalf("msg.Details[0] got type: %T, want %T", msg.Details[0], map[string]interface{}{}) - } - typ, ok := details["@type"].(string) - if got, want := ok, true; got != want { - t.Fatalf("msg.Details[0][\"@type\"] got type: %T, want %T", typ, "") - } - if got, want := details["@type"], "type.googleapis.com/google.rpc.DebugInfo"; got != want { - t.Errorf("msg.Details[\"@type\"] = %q; want %q", got, want) - } - if got, want := details["detail"], "error debug details"; got != want { - t.Errorf("msg.Details[\"detail\"] = %q; want %q", got, want) - } - entries, ok := details["stack_entries"].([]interface{}) - if got, want := ok, true; got != want { - t.Fatalf("msg.Details[0][\"stack_entries\"] got type: %T, want %T", entries, []string{}) - } - entry, ok := entries[0].(string) - if got, want := ok, true; got != want { - t.Fatalf("msg.Details[0][\"stack_entries\"][0] got type: %T, want %T", entry, "") - } - if got, want := entries[0], "foo:1"; got != want { - t.Errorf("msg.Details[\"stack_entries\"][0] = %q; want %q", got, want) - } -} - -func TestPostWithEmptyBody(t *testing.T) { - url := "http://localhost:8080/v2/example/postwithemptybody/name" - rep, err := http.Post(url, "application/json", nil) - - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - - if rep.StatusCode != http.StatusOK { - t.Errorf("http.Post(%q) response code is %d; want %d", url, - rep.StatusCode, http.StatusOK) - return - } -} - -func TestUnknownPath(t *testing.T) { - url := "http://localhost:8080" - resp, err := http.Post(url, "application/json", strings.NewReader("{}")) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusNotFound; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } -} - -func TestMethodNotAllowed(t *testing.T) { - url := "http://localhost:8080/v1/example/echo/myid" - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusMethodNotAllowed; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } -} - -func TestInvalidArgument(t *testing.T) { - url := "http://localhost:8080/v1/example/echo/myid/not_int64" - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusBadRequest; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/main_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/main_test.go deleted file mode 100755 index d9ff64c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/main_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package integration_test - -import ( - "context" - "flag" - "fmt" - "net/http" - "os" - "testing" - "time" - - "github.com/golang/glog" - "github.com/grpc-ecosystem/grpc-gateway/examples/gateway" - server "github.com/grpc-ecosystem/grpc-gateway/examples/server" - gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -var ( - endpoint = flag.String("endpoint", "localhost:9090", "endpoint of the gRPC service") - network = flag.String("network", "tcp", `one of "tcp" or "unix". Must be consistent to -endpoint`) - swaggerDir = flag.String("swagger_dir", "examples/proto/examplepb", "path to the directory which contains swagger definitions") -) - -func runGateway(ctx context.Context, addr string, opts ...gwruntime.ServeMuxOption) error { - return gateway.Run(ctx, gateway.Options{ - Addr: addr, - GRPCServer: gateway.Endpoint{ - Network: *network, - Addr: *endpoint, - }, - SwaggerDir: *swaggerDir, - Mux: opts, - }) -} - -func waitForGateway(ctx context.Context, port uint16) error { - ch := time.After(10 * time.Second) - - var err error - for { - if r, err := http.Get(fmt.Sprintf("http://localhost:%d/healthz", port)); err == nil { - if r.StatusCode == http.StatusOK { - return nil - } - err = fmt.Errorf("server localhost:%d returned an unexpected status %d", port, r.StatusCode) - } - - glog.Infof("Waiting for localhost:%d to get ready", port) - select { - case <-ctx.Done(): - return err - case <-ch: - return err - case <-time.After(10 * time.Millisecond): - } - } -} - -func runServers(ctx context.Context) <-chan error { - ch := make(chan error, 2) - go func() { - if err := server.Run(ctx, *network, *endpoint); err != nil { - ch <- fmt.Errorf("cannot run grpc service: %v", err) - } - }() - go func() { - if err := runGateway(ctx, ":8080"); err != nil { - ch <- fmt.Errorf("cannot run gateway service: %v", err) - } - }() - return ch -} - -func TestMain(m *testing.M) { - flag.Parse() - defer glog.Flush() - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - errCh := runServers(ctx) - - ch := make(chan int, 1) - go func() { - if err := waitForGateway(ctx, 8080); err != nil { - glog.Errorf("waitForGateway(ctx, 8080) failed with %v; want success", err) - } - ch <- m.Run() - }() - - select { - case err := <-errCh: - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - case status := <-ch: - cancel() - os.Exit(status) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/proto_error_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/proto_error_test.go deleted file mode 100755 index 84a631f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/integration/proto_error_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package integration_test - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "strings" - "testing" - "time" - - "github.com/golang/protobuf/jsonpb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" -) - -func runServer(ctx context.Context, t *testing.T, port uint16) { - opt := runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler) - if err := runGateway(ctx, fmt.Sprintf(":%d", port), opt); err != nil { - t.Errorf("runGateway() failed with %v; want success", err) - } -} - -func TestWithProtoErrorHandler(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - const port = 8082 - go runServer(ctx, t, port) - if err := waitForGateway(ctx, 8082); err != nil { - t.Errorf("waitForGateway(ctx, 8082) failed with %v; want success", err) - } - testEcho(t, port, "application/json") - testEchoBody(t, port) -} - -func TestABEWithProtoErrorHandler(t *testing.T) { - if testing.Short() { - t.Skip() - return - } - - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - const port = 8083 - go runServer(ctx, t, port) - if err := waitForGateway(ctx, 8083); err != nil { - t.Errorf("waitForGateway(ctx, 8083) failed with %v; want success", err) - } - - testABECreate(t, port) - testABECreateBody(t, port) - testABEBulkCreate(t, port) - testABELookup(t, port) - testABELookupNotFoundWithProtoError(t, port) - testABEList(t, port) - testABEBulkEcho(t, port) - testABEBulkEchoZeroLength(t, port) - testAdditionalBindings(t, port) -} - -func testABELookupNotFoundWithProtoError(t *testing.T, port uint16) { - url := fmt.Sprintf("http://localhost:%d/v1/example/a_bit_of_everything", port) - uuid := "not_exist" - url = fmt.Sprintf("%s/%s", url, uuid) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Get(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusNotFound; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - return - } - - var msg spb.Status - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - - if got, want := msg.Code, int32(codes.NotFound); got != want { - t.Errorf("msg.Code = %d; want %d", got, want) - return - } - - if got, want := msg.Message, "not found"; got != want { - t.Errorf("msg.Message = %s; want %s", got, want) - return - } - - if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), uuid; got != want { - t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { - t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) - } - if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { - t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) - } -} - -func TestUnknownPathWithProtoError(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - const port = 8084 - go runServer(ctx, t, port) - if err := waitForGateway(ctx, 8084); err != nil { - t.Errorf("waitForGateway(ctx, 8084) failed with %v; want success", err) - } - - url := fmt.Sprintf("http://localhost:%d", port) - resp, err := http.Post(url, "application/json", strings.NewReader("{}")) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusNotImplemented; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg spb.Status - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - - if got, want := msg.Code, int32(codes.Unimplemented); got != want { - t.Errorf("msg.Code = %d; want %d", got, want) - return - } - - if msg.Message == "" { - t.Errorf("msg.Message should not be empty") - return - } -} - -func TestMethodNotAllowedWithProtoError(t *testing.T) { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - const port = 8085 - go runServer(ctx, t, port) - - // Waiting for the server's getting available. - // TODO(yugui) find a better way to wait - time.Sleep(100 * time.Millisecond) - - url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", port) - resp, err := http.Get(url) - if err != nil { - t.Errorf("http.Post(%q) failed with %v; want success", url, err) - return - } - defer resp.Body.Close() - buf, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) - return - } - - if got, want := resp.StatusCode, http.StatusNotImplemented; got != want { - t.Errorf("resp.StatusCode = %d; want %d", got, want) - t.Logf("%s", buf) - } - - var msg spb.Status - if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { - t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) - return - } - - if got, want := msg.Code, int32(codes.Unimplemented); got != want { - t.Errorf("msg.Code = %d; want %d", got, want) - return - } - - if msg.Message == "" { - t.Errorf("msg.Message should not be empty") - return - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/BUILD.bazel deleted file mode 100755 index 066ccd4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/BUILD.bazel +++ /dev/null @@ -1,64 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") -load("@grpc_ecosystem_grpc_gateway//protoc-gen-swagger:defs.bzl", "protoc_gen_swagger") - -package(default_visibility = ["//visibility:public"]) - -# gazelle:exclude a_bit_of_everything.pb.gw.go -# gazelle:exclude echo_service.pb.gw.go -# gazelle:exclude flow_combination.pb.gw.go -# gazelle:exclude stream.pb.gw.go -# gazelle:exclude wrappers.pb.gw.go - -proto_library( - name = "examplepb_proto", - srcs = [ - "a_bit_of_everything.proto", - "echo_service.proto", - "flow_combination.proto", - "stream.proto", - "unannotated_echo_service.proto", - "wrappers.proto", - ], - deps = [ - "//examples/proto/sub:sub_proto", - "//examples/proto/sub2:sub2_proto", - "//protoc-gen-swagger/options:options_proto", - "@com_github_googleapis_googleapis//google/api:api_proto", - "@com_google_protobuf//:duration_proto", - "@com_google_protobuf//:empty_proto", - "@com_google_protobuf//:timestamp_proto", - "@com_google_protobuf//:wrappers_proto", - ], -) - -go_proto_library( - name = "examplepb_go_proto", - compilers = [ - "@io_bazel_rules_go//proto:go_grpc", - "//protoc-gen-grpc-gateway:go_gen_grpc_gateway", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb", - proto = ":examplepb_proto", - deps = [ - "//examples/proto/sub:go_default_library", - "//examples/proto/sub2:go_default_library", - "//protoc-gen-swagger/options:go_default_library", - "@com_github_golang_protobuf//ptypes/duration:go_default_library", - "@com_github_golang_protobuf//ptypes/empty:go_default_library", - "@com_github_golang_protobuf//ptypes/timestamp:go_default_library", - "@com_github_golang_protobuf//ptypes/wrappers:go_default_library", - "@com_github_googleapis_googleapis//google/api:go_default_library", - ], -) - -go_library( - name = "go_default_library", - embed = [":examplepb_go_proto"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb", -) - -protoc_gen_swagger( - name = "expamplepb_protoc_gen_swagger", - proto = ":examplepb_proto", -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.go deleted file mode 100755 index 520dae9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.go +++ /dev/null @@ -1,1330 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/a_bit_of_everything.proto - -package examplepb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" -import empty "github.com/golang/protobuf/ptypes/empty" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" -import sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" -import sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2" -import _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// NumericEnum is one or zero. -type NumericEnum int32 - -const ( - // ZERO means 0 - NumericEnum_ZERO NumericEnum = 0 - // ONE means 1 - NumericEnum_ONE NumericEnum = 1 -) - -var NumericEnum_name = map[int32]string{ - 0: "ZERO", - 1: "ONE", -} -var NumericEnum_value = map[string]int32{ - "ZERO": 0, - "ONE": 1, -} - -func (x NumericEnum) String() string { - return proto.EnumName(NumericEnum_name, int32(x)) -} -func (NumericEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{0} -} - -// DeepEnum is one or zero. -type ABitOfEverything_Nested_DeepEnum int32 - -const ( - // FALSE is false. - ABitOfEverything_Nested_FALSE ABitOfEverything_Nested_DeepEnum = 0 - // TRUE is true. - ABitOfEverything_Nested_TRUE ABitOfEverything_Nested_DeepEnum = 1 -) - -var ABitOfEverything_Nested_DeepEnum_name = map[int32]string{ - 0: "FALSE", - 1: "TRUE", -} -var ABitOfEverything_Nested_DeepEnum_value = map[string]int32{ - "FALSE": 0, - "TRUE": 1, -} - -func (x ABitOfEverything_Nested_DeepEnum) String() string { - return proto.EnumName(ABitOfEverything_Nested_DeepEnum_name, int32(x)) -} -func (ABitOfEverything_Nested_DeepEnum) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{0, 0, 0} -} - -// Intentionaly complicated message type to cover much features of Protobuf. -// NEXT ID: 30 -type ABitOfEverything struct { - SingleNested *ABitOfEverything_Nested `protobuf:"bytes,25,opt,name=single_nested,json=singleNested" json:"single_nested,omitempty"` - Uuid string `protobuf:"bytes,1,opt,name=uuid" json:"uuid,omitempty"` - Nested []*ABitOfEverything_Nested `protobuf:"bytes,2,rep,name=nested" json:"nested,omitempty"` - FloatValue float32 `protobuf:"fixed32,3,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue float64 `protobuf:"fixed64,4,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - Int64Value int64 `protobuf:"varint,5,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` - Int32Value int32 `protobuf:"varint,7,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Fixed64Value uint64 `protobuf:"fixed64,8,opt,name=fixed64_value,json=fixed64Value" json:"fixed64_value,omitempty"` - Fixed32Value uint32 `protobuf:"fixed32,9,opt,name=fixed32_value,json=fixed32Value" json:"fixed32_value,omitempty"` - BoolValue bool `protobuf:"varint,10,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - StringValue string `protobuf:"bytes,11,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - BytesValue []byte `protobuf:"bytes,29,opt,name=bytes_value,json=bytesValue,proto3" json:"bytes_value,omitempty"` - Uint32Value uint32 `protobuf:"varint,13,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` - EnumValue NumericEnum `protobuf:"varint,14,opt,name=enum_value,json=enumValue,enum=grpc.gateway.examples.examplepb.NumericEnum" json:"enum_value,omitempty"` - Sfixed32Value int32 `protobuf:"fixed32,15,opt,name=sfixed32_value,json=sfixed32Value" json:"sfixed32_value,omitempty"` - Sfixed64Value int64 `protobuf:"fixed64,16,opt,name=sfixed64_value,json=sfixed64Value" json:"sfixed64_value,omitempty"` - Sint32Value int32 `protobuf:"zigzag32,17,opt,name=sint32_value,json=sint32Value" json:"sint32_value,omitempty"` - Sint64Value int64 `protobuf:"zigzag64,18,opt,name=sint64_value,json=sint64Value" json:"sint64_value,omitempty"` - RepeatedStringValue []string `protobuf:"bytes,19,rep,name=repeated_string_value,json=repeatedStringValue" json:"repeated_string_value,omitempty"` - // Types that are valid to be assigned to OneofValue: - // *ABitOfEverything_OneofEmpty - // *ABitOfEverything_OneofString - OneofValue isABitOfEverything_OneofValue `protobuf_oneof:"oneof_value"` - MapValue map[string]NumericEnum `protobuf:"bytes,22,rep,name=map_value,json=mapValue" json:"map_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=grpc.gateway.examples.examplepb.NumericEnum"` - MappedStringValue map[string]string `protobuf:"bytes,23,rep,name=mapped_string_value,json=mappedStringValue" json:"mapped_string_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - MappedNestedValue map[string]*ABitOfEverything_Nested `protobuf:"bytes,24,rep,name=mapped_nested_value,json=mappedNestedValue" json:"mapped_nested_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - NonConventionalNameValue string `protobuf:"bytes,26,opt,name=nonConventionalNameValue" json:"nonConventionalNameValue,omitempty"` - TimestampValue *timestamp.Timestamp `protobuf:"bytes,27,opt,name=timestamp_value,json=timestampValue" json:"timestamp_value,omitempty"` - // repeated enum value. it is comma-separated in query - RepeatedEnumValue []NumericEnum `protobuf:"varint,28,rep,packed,name=repeated_enum_value,json=repeatedEnumValue,enum=grpc.gateway.examples.examplepb.NumericEnum" json:"repeated_enum_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ABitOfEverything) Reset() { *m = ABitOfEverything{} } -func (m *ABitOfEverything) String() string { return proto.CompactTextString(m) } -func (*ABitOfEverything) ProtoMessage() {} -func (*ABitOfEverything) Descriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{0} -} -func (m *ABitOfEverything) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ABitOfEverything.Unmarshal(m, b) -} -func (m *ABitOfEverything) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ABitOfEverything.Marshal(b, m, deterministic) -} -func (dst *ABitOfEverything) XXX_Merge(src proto.Message) { - xxx_messageInfo_ABitOfEverything.Merge(dst, src) -} -func (m *ABitOfEverything) XXX_Size() int { - return xxx_messageInfo_ABitOfEverything.Size(m) -} -func (m *ABitOfEverything) XXX_DiscardUnknown() { - xxx_messageInfo_ABitOfEverything.DiscardUnknown(m) -} - -var xxx_messageInfo_ABitOfEverything proto.InternalMessageInfo - -type isABitOfEverything_OneofValue interface { - isABitOfEverything_OneofValue() -} - -type ABitOfEverything_OneofEmpty struct { - OneofEmpty *empty.Empty `protobuf:"bytes,20,opt,name=oneof_empty,json=oneofEmpty,oneof"` -} -type ABitOfEverything_OneofString struct { - OneofString string `protobuf:"bytes,21,opt,name=oneof_string,json=oneofString,oneof"` -} - -func (*ABitOfEverything_OneofEmpty) isABitOfEverything_OneofValue() {} -func (*ABitOfEverything_OneofString) isABitOfEverything_OneofValue() {} - -func (m *ABitOfEverything) GetOneofValue() isABitOfEverything_OneofValue { - if m != nil { - return m.OneofValue - } - return nil -} - -func (m *ABitOfEverything) GetSingleNested() *ABitOfEverything_Nested { - if m != nil { - return m.SingleNested - } - return nil -} - -func (m *ABitOfEverything) GetUuid() string { - if m != nil { - return m.Uuid - } - return "" -} - -func (m *ABitOfEverything) GetNested() []*ABitOfEverything_Nested { - if m != nil { - return m.Nested - } - return nil -} - -func (m *ABitOfEverything) GetFloatValue() float32 { - if m != nil { - return m.FloatValue - } - return 0 -} - -func (m *ABitOfEverything) GetDoubleValue() float64 { - if m != nil { - return m.DoubleValue - } - return 0 -} - -func (m *ABitOfEverything) GetInt64Value() int64 { - if m != nil { - return m.Int64Value - } - return 0 -} - -func (m *ABitOfEverything) GetUint64Value() uint64 { - if m != nil { - return m.Uint64Value - } - return 0 -} - -func (m *ABitOfEverything) GetInt32Value() int32 { - if m != nil { - return m.Int32Value - } - return 0 -} - -func (m *ABitOfEverything) GetFixed64Value() uint64 { - if m != nil { - return m.Fixed64Value - } - return 0 -} - -func (m *ABitOfEverything) GetFixed32Value() uint32 { - if m != nil { - return m.Fixed32Value - } - return 0 -} - -func (m *ABitOfEverything) GetBoolValue() bool { - if m != nil { - return m.BoolValue - } - return false -} - -func (m *ABitOfEverything) GetStringValue() string { - if m != nil { - return m.StringValue - } - return "" -} - -func (m *ABitOfEverything) GetBytesValue() []byte { - if m != nil { - return m.BytesValue - } - return nil -} - -func (m *ABitOfEverything) GetUint32Value() uint32 { - if m != nil { - return m.Uint32Value - } - return 0 -} - -func (m *ABitOfEverything) GetEnumValue() NumericEnum { - if m != nil { - return m.EnumValue - } - return NumericEnum_ZERO -} - -func (m *ABitOfEverything) GetSfixed32Value() int32 { - if m != nil { - return m.Sfixed32Value - } - return 0 -} - -func (m *ABitOfEverything) GetSfixed64Value() int64 { - if m != nil { - return m.Sfixed64Value - } - return 0 -} - -func (m *ABitOfEverything) GetSint32Value() int32 { - if m != nil { - return m.Sint32Value - } - return 0 -} - -func (m *ABitOfEverything) GetSint64Value() int64 { - if m != nil { - return m.Sint64Value - } - return 0 -} - -func (m *ABitOfEverything) GetRepeatedStringValue() []string { - if m != nil { - return m.RepeatedStringValue - } - return nil -} - -func (m *ABitOfEverything) GetOneofEmpty() *empty.Empty { - if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofEmpty); ok { - return x.OneofEmpty - } - return nil -} - -func (m *ABitOfEverything) GetOneofString() string { - if x, ok := m.GetOneofValue().(*ABitOfEverything_OneofString); ok { - return x.OneofString - } - return "" -} - -func (m *ABitOfEverything) GetMapValue() map[string]NumericEnum { - if m != nil { - return m.MapValue - } - return nil -} - -func (m *ABitOfEverything) GetMappedStringValue() map[string]string { - if m != nil { - return m.MappedStringValue - } - return nil -} - -func (m *ABitOfEverything) GetMappedNestedValue() map[string]*ABitOfEverything_Nested { - if m != nil { - return m.MappedNestedValue - } - return nil -} - -func (m *ABitOfEverything) GetNonConventionalNameValue() string { - if m != nil { - return m.NonConventionalNameValue - } - return "" -} - -func (m *ABitOfEverything) GetTimestampValue() *timestamp.Timestamp { - if m != nil { - return m.TimestampValue - } - return nil -} - -func (m *ABitOfEverything) GetRepeatedEnumValue() []NumericEnum { - if m != nil { - return m.RepeatedEnumValue - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ABitOfEverything) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ABitOfEverything_OneofMarshaler, _ABitOfEverything_OneofUnmarshaler, _ABitOfEverything_OneofSizer, []interface{}{ - (*ABitOfEverything_OneofEmpty)(nil), - (*ABitOfEverything_OneofString)(nil), - } -} - -func _ABitOfEverything_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ABitOfEverything) - // oneof_value - switch x := m.OneofValue.(type) { - case *ABitOfEverything_OneofEmpty: - b.EncodeVarint(20<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.OneofEmpty); err != nil { - return err - } - case *ABitOfEverything_OneofString: - b.EncodeVarint(21<<3 | proto.WireBytes) - b.EncodeStringBytes(x.OneofString) - case nil: - default: - return fmt.Errorf("ABitOfEverything.OneofValue has unexpected type %T", x) - } - return nil -} - -func _ABitOfEverything_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ABitOfEverything) - switch tag { - case 20: // oneof_value.oneof_empty - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(empty.Empty) - err := b.DecodeMessage(msg) - m.OneofValue = &ABitOfEverything_OneofEmpty{msg} - return true, err - case 21: // oneof_value.oneof_string - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.OneofValue = &ABitOfEverything_OneofString{x} - return true, err - default: - return false, nil - } -} - -func _ABitOfEverything_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ABitOfEverything) - // oneof_value - switch x := m.OneofValue.(type) { - case *ABitOfEverything_OneofEmpty: - s := proto.Size(x.OneofEmpty) - n += 2 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ABitOfEverything_OneofString: - n += 2 // tag and wire - n += proto.SizeVarint(uint64(len(x.OneofString))) - n += len(x.OneofString) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Nested is nested type. -type ABitOfEverything_Nested struct { - // name is nested field. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Amount uint32 `protobuf:"varint,2,opt,name=amount" json:"amount,omitempty"` - Ok ABitOfEverything_Nested_DeepEnum `protobuf:"varint,3,opt,name=ok,enum=grpc.gateway.examples.examplepb.ABitOfEverything_Nested_DeepEnum" json:"ok,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ABitOfEverything_Nested) Reset() { *m = ABitOfEverything_Nested{} } -func (m *ABitOfEverything_Nested) String() string { return proto.CompactTextString(m) } -func (*ABitOfEverything_Nested) ProtoMessage() {} -func (*ABitOfEverything_Nested) Descriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{0, 0} -} -func (m *ABitOfEverything_Nested) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ABitOfEverything_Nested.Unmarshal(m, b) -} -func (m *ABitOfEverything_Nested) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ABitOfEverything_Nested.Marshal(b, m, deterministic) -} -func (dst *ABitOfEverything_Nested) XXX_Merge(src proto.Message) { - xxx_messageInfo_ABitOfEverything_Nested.Merge(dst, src) -} -func (m *ABitOfEverything_Nested) XXX_Size() int { - return xxx_messageInfo_ABitOfEverything_Nested.Size(m) -} -func (m *ABitOfEverything_Nested) XXX_DiscardUnknown() { - xxx_messageInfo_ABitOfEverything_Nested.DiscardUnknown(m) -} - -var xxx_messageInfo_ABitOfEverything_Nested proto.InternalMessageInfo - -func (m *ABitOfEverything_Nested) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *ABitOfEverything_Nested) GetAmount() uint32 { - if m != nil { - return m.Amount - } - return 0 -} - -func (m *ABitOfEverything_Nested) GetOk() ABitOfEverything_Nested_DeepEnum { - if m != nil { - return m.Ok - } - return ABitOfEverything_Nested_FALSE -} - -type Body struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Body) Reset() { *m = Body{} } -func (m *Body) String() string { return proto.CompactTextString(m) } -func (*Body) ProtoMessage() {} -func (*Body) Descriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{1} -} -func (m *Body) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Body.Unmarshal(m, b) -} -func (m *Body) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Body.Marshal(b, m, deterministic) -} -func (dst *Body) XXX_Merge(src proto.Message) { - xxx_messageInfo_Body.Merge(dst, src) -} -func (m *Body) XXX_Size() int { - return xxx_messageInfo_Body.Size(m) -} -func (m *Body) XXX_DiscardUnknown() { - xxx_messageInfo_Body.DiscardUnknown(m) -} - -var xxx_messageInfo_Body proto.InternalMessageInfo - -func (m *Body) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type MessageWithBody struct { - Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` - Data *Body `protobuf:"bytes,2,opt,name=data" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageWithBody) Reset() { *m = MessageWithBody{} } -func (m *MessageWithBody) String() string { return proto.CompactTextString(m) } -func (*MessageWithBody) ProtoMessage() {} -func (*MessageWithBody) Descriptor() ([]byte, []int) { - return fileDescriptor_a_bit_of_everything_f27080d9602a5f10, []int{2} -} -func (m *MessageWithBody) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageWithBody.Unmarshal(m, b) -} -func (m *MessageWithBody) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageWithBody.Marshal(b, m, deterministic) -} -func (dst *MessageWithBody) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageWithBody.Merge(dst, src) -} -func (m *MessageWithBody) XXX_Size() int { - return xxx_messageInfo_MessageWithBody.Size(m) -} -func (m *MessageWithBody) XXX_DiscardUnknown() { - xxx_messageInfo_MessageWithBody.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageWithBody proto.InternalMessageInfo - -func (m *MessageWithBody) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *MessageWithBody) GetData() *Body { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*ABitOfEverything)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything") - proto.RegisterMapType((map[string]NumericEnum)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MapValueEntry") - proto.RegisterMapType((map[string]*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MappedNestedValueEntry") - proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.MappedStringValueEntry") - proto.RegisterType((*ABitOfEverything_Nested)(nil), "grpc.gateway.examples.examplepb.ABitOfEverything.Nested") - proto.RegisterType((*Body)(nil), "grpc.gateway.examples.examplepb.Body") - proto.RegisterType((*MessageWithBody)(nil), "grpc.gateway.examples.examplepb.MessageWithBody") - proto.RegisterEnum("grpc.gateway.examples.examplepb.NumericEnum", NumericEnum_name, NumericEnum_value) - proto.RegisterEnum("grpc.gateway.examples.examplepb.ABitOfEverything_Nested_DeepEnum", ABitOfEverything_Nested_DeepEnum_name, ABitOfEverything_Nested_DeepEnum_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// ABitOfEverythingServiceClient is the client API for ABitOfEverythingService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ABitOfEverythingServiceClient interface { - Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) - CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) - Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error) - Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) - Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*empty.Empty, error) - GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) - // Echo allows posting a StringMessage value. - // - // It also exposes multiple bindings. - // - // This makes it useful when validating that the OpenAPI v2 API - // description exposes documentation correctly on all paths - // defined as additional_bindings in the proto. - Echo(ctx context.Context, in *sub.StringMessage, opts ...grpc.CallOption) (*sub.StringMessage, error) - DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) - NoBindings(ctx context.Context, in *duration.Duration, opts ...grpc.CallOption) (*empty.Empty, error) - Timeout(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) - ErrorWithDetails(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) - GetMessageWithBody(ctx context.Context, in *MessageWithBody, opts ...grpc.CallOption) (*empty.Empty, error) - PostWithEmptyBody(ctx context.Context, in *Body, opts ...grpc.CallOption) (*empty.Empty, error) -} - -type aBitOfEverythingServiceClient struct { - cc *grpc.ClientConn -} - -func NewABitOfEverythingServiceClient(cc *grpc.ClientConn) ABitOfEverythingServiceClient { - return &aBitOfEverythingServiceClient{cc} -} - -func (c *aBitOfEverythingServiceClient) Create(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { - out := new(ABitOfEverything) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) CreateBody(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { - out := new(ABitOfEverything) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/CreateBody", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) Lookup(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*ABitOfEverything, error) { - out := new(ABitOfEverything) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Lookup", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) Update(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Update", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) Delete(ctx context.Context, in *sub2.IdMessage, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Delete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) GetQuery(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetQuery", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) Echo(ctx context.Context, in *sub.StringMessage, opts ...grpc.CallOption) (*sub.StringMessage, error) { - out := new(sub.StringMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Echo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) DeepPathEcho(ctx context.Context, in *ABitOfEverything, opts ...grpc.CallOption) (*ABitOfEverything, error) { - out := new(ABitOfEverything) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/DeepPathEcho", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) NoBindings(ctx context.Context, in *duration.Duration, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/NoBindings", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) Timeout(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Timeout", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) ErrorWithDetails(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/ErrorWithDetails", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) GetMessageWithBody(ctx context.Context, in *MessageWithBody, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetMessageWithBody", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *aBitOfEverythingServiceClient) PostWithEmptyBody(ctx context.Context, in *Body, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.ABitOfEverythingService/PostWithEmptyBody", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ABitOfEverythingServiceServer is the server API for ABitOfEverythingService service. -type ABitOfEverythingServiceServer interface { - Create(context.Context, *ABitOfEverything) (*ABitOfEverything, error) - CreateBody(context.Context, *ABitOfEverything) (*ABitOfEverything, error) - Lookup(context.Context, *sub2.IdMessage) (*ABitOfEverything, error) - Update(context.Context, *ABitOfEverything) (*empty.Empty, error) - Delete(context.Context, *sub2.IdMessage) (*empty.Empty, error) - GetQuery(context.Context, *ABitOfEverything) (*empty.Empty, error) - // Echo allows posting a StringMessage value. - // - // It also exposes multiple bindings. - // - // This makes it useful when validating that the OpenAPI v2 API - // description exposes documentation correctly on all paths - // defined as additional_bindings in the proto. - Echo(context.Context, *sub.StringMessage) (*sub.StringMessage, error) - DeepPathEcho(context.Context, *ABitOfEverything) (*ABitOfEverything, error) - NoBindings(context.Context, *duration.Duration) (*empty.Empty, error) - Timeout(context.Context, *empty.Empty) (*empty.Empty, error) - ErrorWithDetails(context.Context, *empty.Empty) (*empty.Empty, error) - GetMessageWithBody(context.Context, *MessageWithBody) (*empty.Empty, error) - PostWithEmptyBody(context.Context, *Body) (*empty.Empty, error) -} - -func RegisterABitOfEverythingServiceServer(s *grpc.Server, srv ABitOfEverythingServiceServer) { - s.RegisterService(&_ABitOfEverythingService_serviceDesc, srv) -} - -func _ABitOfEverythingService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ABitOfEverything) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Create(ctx, req.(*ABitOfEverything)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_CreateBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ABitOfEverything) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/CreateBody", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).CreateBody(ctx, req.(*ABitOfEverything)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_Lookup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(sub2.IdMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Lookup(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Lookup", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Lookup(ctx, req.(*sub2.IdMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ABitOfEverything) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Update(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Update", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Update(ctx, req.(*ABitOfEverything)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(sub2.IdMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Delete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Delete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Delete(ctx, req.(*sub2.IdMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_GetQuery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ABitOfEverything) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetQuery", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).GetQuery(ctx, req.(*ABitOfEverything)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(sub.StringMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Echo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Echo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Echo(ctx, req.(*sub.StringMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_DeepPathEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ABitOfEverything) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/DeepPathEcho", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).DeepPathEcho(ctx, req.(*ABitOfEverything)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(duration.Duration) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/NoBindings", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).NoBindings(ctx, req.(*duration.Duration)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_Timeout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(empty.Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).Timeout(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/Timeout", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).Timeout(ctx, req.(*empty.Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_ErrorWithDetails_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(empty.Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).ErrorWithDetails(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/ErrorWithDetails", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).ErrorWithDetails(ctx, req.(*empty.Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_GetMessageWithBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MessageWithBody) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).GetMessageWithBody(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/GetMessageWithBody", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).GetMessageWithBody(ctx, req.(*MessageWithBody)) - } - return interceptor(ctx, in, info, handler) -} - -func _ABitOfEverythingService_PostWithEmptyBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Body) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ABitOfEverythingServiceServer).PostWithEmptyBody(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.ABitOfEverythingService/PostWithEmptyBody", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ABitOfEverythingServiceServer).PostWithEmptyBody(ctx, req.(*Body)) - } - return interceptor(ctx, in, info, handler) -} - -var _ABitOfEverythingService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.ABitOfEverythingService", - HandlerType: (*ABitOfEverythingServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _ABitOfEverythingService_Create_Handler, - }, - { - MethodName: "CreateBody", - Handler: _ABitOfEverythingService_CreateBody_Handler, - }, - { - MethodName: "Lookup", - Handler: _ABitOfEverythingService_Lookup_Handler, - }, - { - MethodName: "Update", - Handler: _ABitOfEverythingService_Update_Handler, - }, - { - MethodName: "Delete", - Handler: _ABitOfEverythingService_Delete_Handler, - }, - { - MethodName: "GetQuery", - Handler: _ABitOfEverythingService_GetQuery_Handler, - }, - { - MethodName: "Echo", - Handler: _ABitOfEverythingService_Echo_Handler, - }, - { - MethodName: "DeepPathEcho", - Handler: _ABitOfEverythingService_DeepPathEcho_Handler, - }, - { - MethodName: "NoBindings", - Handler: _ABitOfEverythingService_NoBindings_Handler, - }, - { - MethodName: "Timeout", - Handler: _ABitOfEverythingService_Timeout_Handler, - }, - { - MethodName: "ErrorWithDetails", - Handler: _ABitOfEverythingService_ErrorWithDetails_Handler, - }, - { - MethodName: "GetMessageWithBody", - Handler: _ABitOfEverythingService_GetMessageWithBody_Handler, - }, - { - MethodName: "PostWithEmptyBody", - Handler: _ABitOfEverythingService_PostWithEmptyBody_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/a_bit_of_everything.proto", -} - -// CamelCaseServiceNameClient is the client API for CamelCaseServiceName service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type CamelCaseServiceNameClient interface { - Empty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) -} - -type camelCaseServiceNameClient struct { - cc *grpc.ClientConn -} - -func NewCamelCaseServiceNameClient(cc *grpc.ClientConn) CamelCaseServiceNameClient { - return &camelCaseServiceNameClient{cc} -} - -func (c *camelCaseServiceNameClient) Empty(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.camelCaseServiceName/Empty", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// CamelCaseServiceNameServer is the server API for CamelCaseServiceName service. -type CamelCaseServiceNameServer interface { - Empty(context.Context, *empty.Empty) (*empty.Empty, error) -} - -func RegisterCamelCaseServiceNameServer(s *grpc.Server, srv CamelCaseServiceNameServer) { - s.RegisterService(&_CamelCaseServiceName_serviceDesc, srv) -} - -func _CamelCaseServiceName_Empty_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(empty.Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(CamelCaseServiceNameServer).Empty(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.camelCaseServiceName/Empty", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(CamelCaseServiceNameServer).Empty(ctx, req.(*empty.Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _CamelCaseServiceName_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.camelCaseServiceName", - HandlerType: (*CamelCaseServiceNameServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Empty", - Handler: _CamelCaseServiceName_Empty_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/a_bit_of_everything.proto", -} - -// AnotherServiceWithNoBindingsClient is the client API for AnotherServiceWithNoBindings service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type AnotherServiceWithNoBindingsClient interface { - NoBindings(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) -} - -type anotherServiceWithNoBindingsClient struct { - cc *grpc.ClientConn -} - -func NewAnotherServiceWithNoBindingsClient(cc *grpc.ClientConn) AnotherServiceWithNoBindingsClient { - return &anotherServiceWithNoBindingsClient{cc} -} - -func (c *anotherServiceWithNoBindingsClient) NoBindings(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { - out := new(empty.Empty) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings/NoBindings", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AnotherServiceWithNoBindingsServer is the server API for AnotherServiceWithNoBindings service. -type AnotherServiceWithNoBindingsServer interface { - NoBindings(context.Context, *empty.Empty) (*empty.Empty, error) -} - -func RegisterAnotherServiceWithNoBindingsServer(s *grpc.Server, srv AnotherServiceWithNoBindingsServer) { - s.RegisterService(&_AnotherServiceWithNoBindings_serviceDesc, srv) -} - -func _AnotherServiceWithNoBindings_NoBindings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(empty.Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings/NoBindings", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AnotherServiceWithNoBindingsServer).NoBindings(ctx, req.(*empty.Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _AnotherServiceWithNoBindings_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.AnotherServiceWithNoBindings", - HandlerType: (*AnotherServiceWithNoBindingsServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "NoBindings", - Handler: _AnotherServiceWithNoBindings_NoBindings_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/a_bit_of_everything.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/a_bit_of_everything.proto", fileDescriptor_a_bit_of_everything_f27080d9602a5f10) -} - -var fileDescriptor_a_bit_of_everything_f27080d9602a5f10 = []byte{ - // 2019 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xcd, 0x6f, 0xdb, 0xc8, - 0x15, 0xf7, 0x48, 0xb2, 0x22, 0x3d, 0xf9, 0x43, 0x1e, 0xe7, 0xc3, 0x51, 0x9c, 0xf5, 0x44, 0xc9, - 0xb6, 0x8c, 0x37, 0x22, 0x37, 0xca, 0xa2, 0xd8, 0x08, 0x68, 0xb7, 0xb2, 0xad, 0x4d, 0x82, 0x6c, - 0x9c, 0x84, 0xd9, 0x4d, 0x83, 0x34, 0x5b, 0x83, 0x22, 0x47, 0x12, 0x13, 0x91, 0xc3, 0x92, 0x43, - 0x27, 0xaa, 0xeb, 0x16, 0xed, 0x02, 0x2d, 0xf6, 0x54, 0xc0, 0xbd, 0xef, 0xa5, 0x40, 0xd1, 0x4b, - 0x0f, 0x3d, 0xf4, 0x54, 0xa0, 0x3d, 0xf6, 0xd0, 0x63, 0x81, 0xde, 0x0b, 0xf4, 0xd4, 0x63, 0xff, - 0x82, 0x62, 0x86, 0xa4, 0x42, 0xc9, 0x16, 0x1c, 0x39, 0x8b, 0xbd, 0x24, 0x9c, 0x99, 0xdf, 0x7b, - 0xef, 0xf7, 0xde, 0xbc, 0xf7, 0xe6, 0xc9, 0x50, 0xa7, 0xaf, 0x0c, 0xc7, 0xeb, 0xd3, 0x40, 0xf3, - 0x7c, 0xc6, 0x99, 0x16, 0x2f, 0xbd, 0xb6, 0x66, 0xec, 0xb4, 0x6d, 0xbe, 0xc3, 0x3a, 0x3b, 0x74, - 0x97, 0xfa, 0x03, 0xde, 0xb3, 0xdd, 0xae, 0x2a, 0x31, 0x78, 0xad, 0xeb, 0x7b, 0xa6, 0xda, 0x35, - 0x38, 0x7d, 0x69, 0x0c, 0xd4, 0x44, 0x81, 0x3a, 0x14, 0xad, 0xac, 0x76, 0x19, 0xeb, 0xf6, 0xa9, - 0x66, 0x78, 0xb6, 0x66, 0xb8, 0x2e, 0xe3, 0x06, 0xb7, 0x99, 0x1b, 0x44, 0xe2, 0x95, 0x0b, 0xf1, - 0xa9, 0x5c, 0xb5, 0xc3, 0x8e, 0x46, 0x1d, 0x8f, 0x0f, 0xe2, 0xc3, 0x77, 0xc6, 0x0f, 0xad, 0xd0, - 0x97, 0xd2, 0xf1, 0x39, 0x19, 0xe3, 0x1b, 0x84, 0x6d, 0xcd, 0xa1, 0x41, 0x60, 0x74, 0x69, 0x8c, - 0xb8, 0x74, 0x18, 0x51, 0x1f, 0x83, 0xac, 0x8d, 0x1b, 0xe1, 0xb6, 0x43, 0x03, 0x6e, 0x38, 0x5e, - 0x0c, 0xb8, 0x26, 0xff, 0x33, 0x6b, 0x5d, 0xea, 0xd6, 0x82, 0x97, 0x46, 0xb7, 0x4b, 0x7d, 0x8d, - 0x79, 0xd2, 0x89, 0xc3, 0x0e, 0x55, 0xff, 0x5a, 0x86, 0x72, 0x73, 0xc3, 0xe6, 0xf7, 0x3b, 0xad, - 0x61, 0xa8, 0xf0, 0xe7, 0x30, 0x1f, 0xd8, 0x6e, 0xb7, 0x4f, 0x77, 0x5c, 0x1a, 0x70, 0x6a, 0xad, - 0x9c, 0x27, 0x48, 0x29, 0xd5, 0x3f, 0x54, 0x8f, 0x09, 0x9e, 0x3a, 0xae, 0x49, 0xdd, 0x96, 0xf2, - 0xfa, 0x5c, 0xa4, 0x2e, 0x5a, 0x61, 0x0c, 0xb9, 0x30, 0xb4, 0xad, 0x15, 0x44, 0x90, 0x52, 0xd4, - 0xe5, 0x37, 0x7e, 0x00, 0xf9, 0xd8, 0x56, 0x86, 0x64, 0xdf, 0xca, 0x56, 0xac, 0x07, 0xaf, 0x41, - 0xa9, 0xd3, 0x67, 0x06, 0xdf, 0xd9, 0x35, 0xfa, 0x21, 0x5d, 0xc9, 0x12, 0xa4, 0x64, 0x74, 0x90, - 0x5b, 0x8f, 0xc5, 0x0e, 0xbe, 0x04, 0x73, 0x16, 0x0b, 0xdb, 0x7d, 0x1a, 0x23, 0x72, 0x04, 0x29, - 0x48, 0x2f, 0x45, 0x7b, 0x11, 0x64, 0x0d, 0x4a, 0xb6, 0xcb, 0xbf, 0xf3, 0x41, 0x8c, 0x98, 0x25, - 0x48, 0xc9, 0xea, 0x20, 0xb7, 0x86, 0x3a, 0xc2, 0x34, 0x22, 0x4f, 0x90, 0x92, 0xd3, 0x4b, 0x61, - 0x0a, 0x12, 0xe9, 0xb8, 0x51, 0x8f, 0x11, 0xa7, 0x08, 0x52, 0x66, 0xa5, 0x8e, 0x1b, 0xf5, 0x08, - 0x70, 0x19, 0xe6, 0x3b, 0xf6, 0x2b, 0x6a, 0x0d, 0x95, 0x14, 0x08, 0x52, 0xf2, 0xfa, 0x5c, 0xbc, - 0x39, 0x0a, 0x1a, 0xea, 0x29, 0x12, 0xa4, 0x9c, 0x8a, 0x41, 0x89, 0xa6, 0x8b, 0x00, 0x6d, 0xc6, - 0xfa, 0x31, 0x02, 0x08, 0x52, 0x0a, 0x7a, 0x51, 0xec, 0x0c, 0xc9, 0x06, 0xdc, 0xb7, 0xdd, 0x6e, - 0x0c, 0x28, 0xc9, 0xf8, 0x97, 0xa2, 0xbd, 0x21, 0xd9, 0xf6, 0x80, 0xd3, 0x20, 0x46, 0x5c, 0x24, - 0x48, 0x99, 0xd3, 0x41, 0x6e, 0x8d, 0x38, 0x3c, 0xa4, 0x31, 0x4f, 0x90, 0x32, 0x1f, 0x39, 0x9c, - 0xb0, 0xb8, 0x0b, 0x40, 0xdd, 0xd0, 0x89, 0x01, 0x0b, 0x04, 0x29, 0x0b, 0xf5, 0x6b, 0xc7, 0x5e, - 0xe7, 0x76, 0xe8, 0x50, 0xdf, 0x36, 0x5b, 0x6e, 0xe8, 0xe8, 0x45, 0x21, 0x1f, 0x29, 0x7b, 0x17, - 0x16, 0x82, 0x51, 0xc7, 0x17, 0x09, 0x52, 0x16, 0xf5, 0xf9, 0x60, 0xc4, 0xf3, 0x21, 0x6c, 0x18, - 0xc4, 0x32, 0x41, 0x4a, 0x39, 0x81, 0xa5, 0xae, 0x2b, 0x48, 0xb3, 0x5f, 0x22, 0x48, 0x59, 0xd2, - 0x4b, 0x41, 0x8a, 0x7d, 0x0c, 0x19, 0xea, 0xc1, 0x04, 0x29, 0x38, 0x82, 0x24, 0x5a, 0xea, 0x70, - 0xc6, 0xa7, 0x1e, 0x35, 0x38, 0xb5, 0x76, 0x46, 0x02, 0xba, 0x4c, 0xb2, 0x4a, 0x51, 0x5f, 0x4e, - 0x0e, 0x1f, 0xa5, 0x02, 0x7b, 0x13, 0x4a, 0xcc, 0xa5, 0xa2, 0x23, 0x89, 0x86, 0xb1, 0x72, 0x5a, - 0x16, 0xd4, 0x59, 0x35, 0x2a, 0x66, 0x35, 0x29, 0x66, 0xb5, 0x25, 0x4e, 0x6f, 0xcf, 0xe8, 0x20, - 0xc1, 0x72, 0x85, 0x2f, 0xc3, 0x5c, 0x24, 0x1a, 0xd9, 0x5a, 0x39, 0x23, 0xae, 0xed, 0xf6, 0x8c, - 0x1e, 0x29, 0x8c, 0x8c, 0xe0, 0x67, 0x50, 0x74, 0x0c, 0x2f, 0xe6, 0x71, 0x56, 0x96, 0xd0, 0x47, - 0xd3, 0x97, 0xd0, 0x3d, 0xc3, 0x93, 0x74, 0x5b, 0x2e, 0xf7, 0x07, 0x7a, 0xc1, 0x89, 0x97, 0xf8, - 0x15, 0x2c, 0x3b, 0x86, 0xe7, 0x8d, 0xfb, 0x7b, 0x4e, 0xda, 0xb9, 0x7d, 0x22, 0x3b, 0xde, 0x48, - 0x7c, 0x22, 0x83, 0x4b, 0xce, 0xf8, 0x7e, 0xca, 0x72, 0x54, 0xd6, 0xb1, 0xe5, 0x95, 0xb7, 0xb3, - 0x1c, 0xb5, 0x8a, 0xc3, 0x96, 0x53, 0xfb, 0xb8, 0x01, 0x2b, 0x2e, 0x73, 0x37, 0x99, 0xbb, 0x4b, - 0x5d, 0xd1, 0x31, 0x8d, 0xfe, 0xb6, 0xe1, 0x44, 0x7d, 0x61, 0xa5, 0x22, 0x2b, 0x67, 0xe2, 0x39, - 0xde, 0x84, 0xc5, 0x61, 0x5b, 0x8e, 0x19, 0x5f, 0x90, 0x37, 0x5e, 0x39, 0x74, 0xe3, 0x9f, 0x26, - 0x38, 0x7d, 0x61, 0x28, 0x12, 0x29, 0x79, 0x06, 0xc3, 0x4c, 0xda, 0x49, 0x15, 0xd4, 0x2a, 0xc9, - 0x4e, 0x5d, 0x50, 0x4b, 0x89, 0xa2, 0x56, 0x52, 0x58, 0x95, 0x3f, 0x20, 0xc8, 0xbf, 0xee, 0xc7, - 0xae, 0xe1, 0xd0, 0xa4, 0x1f, 0x8b, 0x6f, 0x7c, 0x16, 0xf2, 0x86, 0xc3, 0x42, 0x97, 0xaf, 0x64, - 0x64, 0x85, 0xc7, 0x2b, 0xfc, 0x10, 0x32, 0xec, 0x85, 0x6c, 0xa6, 0x0b, 0xf5, 0xe6, 0x49, 0x7b, - 0xb4, 0xba, 0x45, 0xa9, 0x27, 0x89, 0x65, 0xd8, 0x8b, 0xea, 0x1a, 0x14, 0x92, 0x35, 0x2e, 0xc2, - 0xec, 0xc7, 0xcd, 0x4f, 0x1e, 0xb5, 0xca, 0x33, 0xb8, 0x00, 0xb9, 0x4f, 0xf5, 0xcf, 0x5a, 0x65, - 0x54, 0xb1, 0x61, 0x7e, 0x24, 0x31, 0x71, 0x19, 0xb2, 0x2f, 0xe8, 0x20, 0xe6, 0x2b, 0x3e, 0xf1, - 0x06, 0xcc, 0x46, 0xd1, 0xc9, 0x9c, 0xa0, 0xdd, 0x44, 0xa2, 0x8d, 0xcc, 0x87, 0xa8, 0xb2, 0x05, - 0x67, 0x8f, 0xce, 0xcd, 0x23, 0x6c, 0x9e, 0x4e, 0xdb, 0x2c, 0xa6, 0xb5, 0xfc, 0x2c, 0xd1, 0x32, - 0x9e, 0x67, 0x47, 0x68, 0xd9, 0x4e, 0x6b, 0x79, 0x9b, 0x77, 0xef, 0xb5, 0xfd, 0xc6, 0x0f, 0x0f, - 0x9a, 0x4f, 0xd6, 0x1f, 0xc3, 0x95, 0x8f, 0x6d, 0xd7, 0x22, 0x2c, 0xe4, 0xc4, 0x61, 0x3e, 0x25, - 0x46, 0x5b, 0x7c, 0x1e, 0x7a, 0xec, 0xd5, 0x1e, 0xe7, 0x5e, 0xd0, 0xd0, 0xb4, 0xae, 0xcd, 0x7b, - 0x61, 0x5b, 0x35, 0x99, 0xa3, 0x09, 0x0e, 0x35, 0x6a, 0xb2, 0x60, 0x10, 0x70, 0x1a, 0x2f, 0x63, - 0x4a, 0x1b, 0xf3, 0x49, 0x27, 0x93, 0xf6, 0xaa, 0x15, 0xc8, 0x6d, 0x30, 0x6b, 0x70, 0x54, 0x12, - 0x55, 0x9f, 0xc1, 0xe2, 0xbd, 0x68, 0x78, 0xf9, 0x81, 0xcd, 0x7b, 0x12, 0xb6, 0x00, 0x99, 0xe1, - 0xcb, 0x9f, 0xb1, 0x2d, 0x7c, 0x13, 0x72, 0x96, 0xc1, 0x8d, 0xd8, 0xfb, 0x77, 0x8f, 0xf5, 0x5e, - 0x28, 0xd1, 0xa5, 0xc8, 0x3a, 0x81, 0x52, 0xea, 0x16, 0x45, 0xbe, 0x3c, 0x6d, 0xe9, 0xf7, 0xcb, - 0x33, 0xf8, 0x14, 0x64, 0xef, 0x6f, 0xb7, 0xca, 0xa8, 0xfe, 0xa7, 0x65, 0x38, 0x37, 0xee, 0xef, - 0x23, 0xea, 0xef, 0xda, 0x26, 0xc5, 0x5f, 0x65, 0x21, 0xbf, 0xe9, 0x8b, 0xa2, 0xc0, 0xd7, 0xa7, - 0x8e, 0x79, 0x65, 0x7a, 0x91, 0xea, 0x1f, 0x33, 0xbf, 0xfc, 0xe7, 0x7f, 0x7e, 0x9b, 0xf9, 0x7d, - 0xa6, 0xfa, 0xbb, 0x8c, 0xb6, 0x7b, 0x3d, 0x99, 0x56, 0x8f, 0x9a, 0x55, 0xb5, 0xbd, 0xd4, 0xe4, - 0xb2, 0xaf, 0xed, 0xa5, 0xc7, 0x94, 0x7d, 0x6d, 0x2f, 0xf5, 0x3c, 0xed, 0x6b, 0x01, 0xf5, 0x0c, - 0xdf, 0xe0, 0xcc, 0xd7, 0xf6, 0xc2, 0x91, 0x83, 0xbd, 0xd4, 0x43, 0xb7, 0xaf, 0xed, 0x8d, 0xbc, - 0x8e, 0xc9, 0x3a, 0x75, 0xfe, 0x7a, 0x70, 0xd8, 0xd7, 0xf6, 0xd2, 0x5d, 0xfe, 0xbb, 0x01, 0xf7, - 0x3d, 0x9f, 0x76, 0xec, 0x57, 0xda, 0xfa, 0x7e, 0x64, 0x24, 0x25, 0x16, 0x8c, 0xeb, 0x09, 0xc6, - 0x0d, 0x05, 0x63, 0x02, 0xa3, 0x24, 0x27, 0xb5, 0xd0, 0x7d, 0xfc, 0x15, 0x02, 0x88, 0x2e, 0x48, - 0x26, 0xce, 0x37, 0x73, 0x49, 0xeb, 0xf2, 0x8e, 0xae, 0x54, 0xd7, 0x8e, 0xb9, 0xa1, 0x06, 0x5a, - 0xc7, 0x3f, 0x85, 0xfc, 0x27, 0x8c, 0xbd, 0x08, 0x3d, 0xbc, 0xa8, 0x8a, 0x41, 0x5d, 0xbd, 0x63, - 0xc5, 0xd9, 0x7e, 0x12, 0xcb, 0xaa, 0xb4, 0xac, 0xe0, 0x6f, 0x1d, 0x9b, 0x1b, 0x62, 0x5e, 0xde, - 0xc7, 0xbf, 0x42, 0x90, 0xff, 0xcc, 0xb3, 0x4e, 0x98, 0xbf, 0x13, 0x26, 0x8f, 0xea, 0x75, 0xc9, - 0xe2, 0xbd, 0xca, 0x1b, 0xb2, 0x10, 0x61, 0xf8, 0x0d, 0x82, 0xfc, 0x16, 0xed, 0x53, 0x4e, 0x0f, - 0xc7, 0x61, 0x92, 0x99, 0x67, 0x07, 0xcd, 0xf7, 0xda, 0x57, 0x61, 0x01, 0xa0, 0xe9, 0xd9, 0x77, - 0xe9, 0xa0, 0x19, 0xf2, 0x1e, 0x9e, 0x81, 0x73, 0x90, 0xbf, 0x2f, 0x3e, 0xeb, 0x78, 0x1e, 0x72, - 0x3e, 0x35, 0x2c, 0x98, 0x7d, 0xe9, 0xdb, 0x9c, 0x46, 0xa1, 0x59, 0x7f, 0xd3, 0xd0, 0xfc, 0x1b, - 0x41, 0xe1, 0x16, 0xe5, 0x0f, 0x43, 0xea, 0x0f, 0xbe, 0xce, 0xe0, 0x7c, 0x89, 0x0e, 0x9a, 0x7a, - 0x75, 0x1b, 0x56, 0x8f, 0xea, 0xab, 0x43, 0x83, 0x53, 0xf6, 0xd3, 0x27, 0x48, 0x7a, 0xa7, 0xe2, - 0x6b, 0xc7, 0x79, 0xf7, 0x63, 0xa1, 0x3e, 0xf1, 0xf1, 0xef, 0x19, 0xc8, 0xb5, 0xcc, 0x1e, 0xc3, - 0xca, 0x04, 0xff, 0x82, 0xb0, 0xad, 0x46, 0x8f, 0x58, 0x72, 0x19, 0x6f, 0x8c, 0xac, 0xfe, 0x17, - 0x1d, 0x34, 0xbf, 0x40, 0x30, 0x47, 0xcd, 0x1e, 0x23, 0x41, 0xd4, 0x30, 0xa1, 0x20, 0x57, 0xbe, - 0x67, 0xe2, 0xa5, 0x47, 0xa1, 0xe3, 0x18, 0xfe, 0xa0, 0x41, 0x5a, 0xf1, 0x56, 0xa5, 0xbc, 0x45, - 0x03, 0xd3, 0xb7, 0xe5, 0xcf, 0x4c, 0xb9, 0x5b, 0xdd, 0x02, 0x3c, 0x1a, 0x26, 0xc9, 0x76, 0xca, - 0xe0, 0xc8, 0xd0, 0x7c, 0x7e, 0x7c, 0x68, 0x04, 0x35, 0x6d, 0x2f, 0xea, 0x29, 0x4f, 0xcf, 0x57, - 0xcb, 0xda, 0x6e, 0x7d, 0x88, 0x17, 0x67, 0x8d, 0xe8, 0x71, 0x7c, 0x8a, 0xf1, 0xa1, 0x23, 0xfc, - 0x67, 0x04, 0x73, 0x62, 0xfe, 0x78, 0x60, 0xf0, 0x9e, 0xe4, 0xf8, 0xcd, 0x74, 0x9a, 0x8f, 0xa4, - 0x6f, 0x37, 0xab, 0x1f, 0x1c, 0x9b, 0xd4, 0x23, 0x3f, 0xc5, 0x55, 0xf1, 0xb0, 0xca, 0xba, 0x6b, - 0x02, 0x6c, 0xb3, 0x0d, 0xdb, 0xb5, 0x6c, 0xb7, 0x1b, 0xe0, 0xf3, 0x87, 0x72, 0x76, 0x2b, 0xfe, - 0xe3, 0xc3, 0xc4, 0x74, 0x9e, 0xc1, 0x8f, 0xe1, 0x94, 0x18, 0x3f, 0x59, 0xc8, 0xf1, 0x04, 0xd0, - 0x44, 0xe1, 0x0b, 0x92, 0xfe, 0x19, 0xbc, 0x9c, 0x8e, 0x27, 0x8f, 0x95, 0xf5, 0xa0, 0xdc, 0xf2, - 0x7d, 0xe6, 0x8b, 0x57, 0x7f, 0x8b, 0x72, 0xc3, 0xee, 0x07, 0x53, 0x1b, 0xb8, 0x22, 0x0d, 0xbc, - 0x83, 0x57, 0x47, 0x2e, 0x4c, 0x68, 0x7d, 0x69, 0xf3, 0x9e, 0x15, 0x6b, 0xfd, 0x35, 0x02, 0x7c, - 0x8b, 0xf2, 0xf1, 0x29, 0xe3, 0xfd, 0x63, 0xef, 0x63, 0x4c, 0x62, 0x22, 0x8d, 0x6f, 0x4b, 0x1a, - 0x97, 0xaa, 0xe7, 0xd3, 0x34, 0x04, 0x83, 0x36, 0xb3, 0x06, 0xda, 0x9e, 0xe8, 0x81, 0x72, 0x1a, - 0xc1, 0x5f, 0x20, 0x58, 0x7a, 0xc0, 0x02, 0x2e, 0x34, 0x4a, 0x51, 0x49, 0xe4, 0xcd, 0x06, 0x9a, - 0x89, 0xd6, 0x35, 0x69, 0xfd, 0x6a, 0xf5, 0x4a, 0xda, 0xba, 0xc7, 0x02, 0x2e, 0x18, 0xc8, 0x5f, - 0x92, 0x11, 0x8d, 0x24, 0x29, 0x2a, 0x7f, 0x43, 0x07, 0xcd, 0xbf, 0x20, 0xdc, 0x99, 0x30, 0xf5, - 0x10, 0x2b, 0x55, 0xa6, 0xb5, 0x1a, 0x79, 0xd9, 0xb3, 0xcd, 0x1e, 0x09, 0x7a, 0x2c, 0xec, 0x5b, - 0xc4, 0x65, 0x9c, 0xb4, 0x29, 0x09, 0x03, 0x6a, 0x11, 0xdb, 0x25, 0x5e, 0xdf, 0x30, 0x29, 0x61, - 0x1d, 0xc2, 0x7b, 0x94, 0x58, 0xcc, 0x0c, 0x1d, 0xea, 0x46, 0x7f, 0x3b, 0x22, 0x26, 0x73, 0xc4, - 0xe2, 0x52, 0xe5, 0x21, 0xac, 0x1d, 0xd5, 0x0b, 0x45, 0x19, 0x25, 0x73, 0xd6, 0x94, 0x15, 0x5f, - 0x7f, 0x0e, 0xa7, 0x4d, 0xc3, 0xa1, 0xfd, 0x4d, 0x23, 0xa0, 0xb1, 0x0e, 0x31, 0x14, 0x60, 0x1d, - 0x66, 0xa3, 0x9f, 0xc3, 0xd3, 0x26, 0xd2, 0x79, 0x19, 0xc3, 0x65, 0xbc, 0x34, 0x92, 0x48, 0xe2, - 0xa8, 0xfe, 0x23, 0x58, 0x6d, 0xba, 0x8c, 0xf7, 0xa8, 0x1f, 0x5b, 0x12, 0x97, 0x97, 0x2a, 0xaa, - 0xef, 0x8d, 0x94, 0xd8, 0xb4, 0x86, 0x67, 0x36, 0x7e, 0x31, 0x7b, 0xd0, 0xfc, 0x5f, 0x0e, 0x73, - 0x58, 0x6e, 0x92, 0x0d, 0x9b, 0x8b, 0x60, 0xa6, 0x3a, 0xc0, 0x13, 0x38, 0xdd, 0xd5, 0x1f, 0x6c, - 0xd6, 0x6e, 0x45, 0x9e, 0x13, 0xcf, 0x67, 0xcf, 0xa9, 0xc9, 0xa7, 0x8d, 0x58, 0xa5, 0xec, 0x32, - 0x97, 0x7e, 0x3f, 0xf6, 0x4c, 0xa0, 0xeb, 0xd9, 0xeb, 0xea, 0xfb, 0xeb, 0x59, 0x94, 0xc9, 0xd5, - 0xcb, 0x86, 0xe7, 0xf5, 0x6d, 0x53, 0x5e, 0x9b, 0xf6, 0x3c, 0x60, 0x6e, 0xfd, 0x6c, 0x7a, 0xe7, - 0x55, 0xad, 0xc3, 0x58, 0xcd, 0xb1, 0x1d, 0xda, 0x38, 0x84, 0x6c, 0x4c, 0x40, 0x3e, 0xfd, 0x32, - 0x03, 0x8b, 0x50, 0xdc, 0x30, 0x02, 0xdb, 0x94, 0xef, 0x76, 0xa6, 0x80, 0xe0, 0xe2, 0xc8, 0x4b, - 0xbe, 0x58, 0xc8, 0x54, 0x8a, 0x4f, 0x6a, 0xcd, 0x07, 0x77, 0x6a, 0x77, 0xe9, 0x80, 0x64, 0xe0, - 0x5f, 0x68, 0xf8, 0xb2, 0xff, 0x03, 0x15, 0xb2, 0x4a, 0xae, 0x7e, 0x39, 0x71, 0x32, 0xc5, 0x5b, - 0x63, 0x46, 0xc8, 0x7b, 0x9a, 0xf8, 0x87, 0xf9, 0xf6, 0x4f, 0x68, 0x63, 0x6d, 0x32, 0x88, 0xb3, - 0x17, 0xd4, 0xdd, 0xf8, 0x39, 0x54, 0xa2, 0x41, 0x01, 0xe3, 0x5b, 0xbe, 0xe1, 0xf2, 0x80, 0x88, - 0x05, 0x31, 0x4c, 0x93, 0x06, 0x01, 0xac, 0xc6, 0xe3, 0x03, 0x5e, 0x8e, 0x0f, 0xe5, 0x2a, 0x39, - 0xdd, 0x84, 0x59, 0xc3, 0x72, 0x6c, 0x17, 0x37, 0x46, 0x44, 0x5d, 0x6b, 0x04, 0x46, 0x38, 0x23, - 0x12, 0x66, 0x07, 0x5c, 0xf4, 0xd3, 0x5d, 0x4a, 0x6c, 0xb7, 0xc3, 0x7c, 0x47, 0x86, 0xa5, 0xbd, - 0x06, 0xf3, 0xe9, 0x50, 0xcc, 0x8c, 0x8f, 0x34, 0xed, 0xab, 0x13, 0x87, 0x9a, 0x71, 0xa8, 0x7f, - 0x07, 0xce, 0xdd, 0x7b, 0x5d, 0x43, 0xe9, 0xd4, 0x98, 0x36, 0x25, 0x9e, 0x16, 0x87, 0xfd, 0xa5, - 0x9d, 0x97, 0x59, 0x79, 0xe3, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, 0x60, 0xd8, 0x68, 0xe8, 0x2d, - 0x17, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.gw.go deleted file mode 100755 index f863b09..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.pb.gw.go +++ /dev/null @@ -1,1116 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/a_bit_of_everything.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -var ( - filter_ABitOfEverythingService_Create_0 = &utilities.DoubleArray{Encoding: map[string]int{"float_value": 0, "double_value": 1, "int64_value": 2, "uint64_value": 3, "int32_value": 4, "fixed64_value": 5, "fixed32_value": 6, "bool_value": 7, "string_value": 8, "uint32_value": 9, "sfixed32_value": 10, "sfixed64_value": 11, "sint32_value": 12, "sint64_value": 13, "nonConventionalNameValue": 14}, Base: []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Check: []int{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}} -) - -func request_ABitOfEverythingService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ABitOfEverything - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["float_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "float_value") - } - - protoReq.FloatValue, err = runtime.Float32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "float_value", err) - } - - val, ok = pathParams["double_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "double_value") - } - - protoReq.DoubleValue, err = runtime.Float64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "double_value", err) - } - - val, ok = pathParams["int64_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int64_value") - } - - protoReq.Int64Value, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int64_value", err) - } - - val, ok = pathParams["uint64_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint64_value") - } - - protoReq.Uint64Value, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint64_value", err) - } - - val, ok = pathParams["int32_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "int32_value") - } - - protoReq.Int32Value, err = runtime.Int32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "int32_value", err) - } - - val, ok = pathParams["fixed64_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed64_value") - } - - protoReq.Fixed64Value, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed64_value", err) - } - - val, ok = pathParams["fixed32_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "fixed32_value") - } - - protoReq.Fixed32Value, err = runtime.Uint32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "fixed32_value", err) - } - - val, ok = pathParams["bool_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "bool_value") - } - - protoReq.BoolValue, err = runtime.Bool(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "bool_value", err) - } - - val, ok = pathParams["string_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "string_value") - } - - protoReq.StringValue, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "string_value", err) - } - - val, ok = pathParams["uint32_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uint32_value") - } - - protoReq.Uint32Value, err = runtime.Uint32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uint32_value", err) - } - - val, ok = pathParams["sfixed32_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed32_value") - } - - protoReq.Sfixed32Value, err = runtime.Int32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed32_value", err) - } - - val, ok = pathParams["sfixed64_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sfixed64_value") - } - - protoReq.Sfixed64Value, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sfixed64_value", err) - } - - val, ok = pathParams["sint32_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint32_value") - } - - protoReq.Sint32Value, err = runtime.Int32(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint32_value", err) - } - - val, ok = pathParams["sint64_value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "sint64_value") - } - - protoReq.Sint64Value, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "sint64_value", err) - } - - val, ok = pathParams["nonConventionalNameValue"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "nonConventionalNameValue") - } - - protoReq.NonConventionalNameValue, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "nonConventionalNameValue", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_Create_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_CreateBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ABitOfEverything - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.CreateBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Lookup_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq sub2.IdMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["uuid"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") - } - - protoReq.Uuid, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) - } - - msg, err := client.Lookup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Update_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ABitOfEverything - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["uuid"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") - } - - protoReq.Uuid, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) - } - - msg, err := client.Update(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Delete_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq sub2.IdMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["uuid"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") - } - - protoReq.Uuid, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) - } - - msg, err := client.Delete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_ABitOfEverythingService_GetQuery_0 = &utilities.DoubleArray{Encoding: map[string]int{"uuid": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_ABitOfEverythingService_GetQuery_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ABitOfEverything - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["uuid"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "uuid") - } - - protoReq.Uuid, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "uuid", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_GetQuery_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.GetQuery(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq sub.StringMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["value"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "value") - } - - protoReq.Value, err = runtime.StringP(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "value", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq sub.StringMessage - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.Value); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_ABitOfEverythingService_Echo_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_ABitOfEverythingService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq sub.StringMessage - var metadata runtime.ServerMetadata - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_ABitOfEverythingService_Echo_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_DeepPathEcho_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ABitOfEverything - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["single_nested.name"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "single_nested.name") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "single_nested.name", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "single_nested.name", err) - } - - msg, err := client.DeepPathEcho(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_Timeout_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq empty.Empty - var metadata runtime.ServerMetadata - - msg, err := client.Timeout(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_ErrorWithDetails_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq empty.Empty - var metadata runtime.ServerMetadata - - msg, err := client.ErrorWithDetails(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_GetMessageWithBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MessageWithBody - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.Data); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - msg, err := client.GetMessageWithBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_ABitOfEverythingService_PostWithEmptyBody_0(ctx context.Context, marshaler runtime.Marshaler, client ABitOfEverythingServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq Body - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["name"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "name") - } - - protoReq.Name, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) - } - - msg, err := client.PostWithEmptyBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_CamelCaseServiceName_Empty_0(ctx context.Context, marshaler runtime.Marshaler, client CamelCaseServiceNameClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq empty.Empty - var metadata runtime.ServerMetadata - - msg, err := client.Empty(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterABitOfEverythingServiceHandlerFromEndpoint is same as RegisterABitOfEverythingServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterABitOfEverythingServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterABitOfEverythingServiceHandler(ctx, mux, conn) -} - -// RegisterABitOfEverythingServiceHandler registers the http handlers for service ABitOfEverythingService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterABitOfEverythingServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterABitOfEverythingServiceHandlerClient(ctx, mux, NewABitOfEverythingServiceClient(conn)) -} - -// RegisterABitOfEverythingServiceHandler registers the http handlers for service ABitOfEverythingService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "ABitOfEverythingServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "ABitOfEverythingServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "ABitOfEverythingServiceClient" to call the correct interceptors. -func RegisterABitOfEverythingServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client ABitOfEverythingServiceClient) error { - - mux.Handle("POST", pattern_ABitOfEverythingService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Create_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_ABitOfEverythingService_CreateBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_CreateBody_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_CreateBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_Lookup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Lookup_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Lookup_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("PUT", pattern_ABitOfEverythingService_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Update_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("DELETE", pattern_ABitOfEverythingService_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Delete_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_GetQuery_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_GetQuery_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_GetQuery_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_ABitOfEverythingService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Echo_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_ABitOfEverythingService_DeepPathEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_DeepPathEcho_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_DeepPathEcho_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_Timeout_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_Timeout_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_Timeout_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_ABitOfEverythingService_ErrorWithDetails_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_ErrorWithDetails_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_ErrorWithDetails_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_ABitOfEverythingService_GetMessageWithBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_GetMessageWithBody_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_GetMessageWithBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_ABitOfEverythingService_PostWithEmptyBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_ABitOfEverythingService_PostWithEmptyBody_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_ABitOfEverythingService_PostWithEmptyBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_ABitOfEverythingService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5, 2, 6, 1, 0, 4, 1, 5, 7, 1, 0, 4, 1, 5, 8, 1, 0, 4, 1, 5, 9, 1, 0, 4, 1, 5, 10, 1, 0, 4, 1, 5, 11, 2, 12, 1, 0, 4, 2, 5, 13, 1, 0, 4, 1, 5, 14, 1, 0, 4, 1, 5, 15, 1, 0, 4, 1, 5, 16, 1, 0, 4, 1, 5, 17, 1, 0, 4, 1, 5, 18, 1, 0, 4, 1, 5, 19}, []string{"v1", "example", "a_bit_of_everything", "float_value", "double_value", "int64_value", "separator", "uint64_value", "int32_value", "fixed64_value", "fixed32_value", "bool_value", "strprefix", "string_value", "uint32_value", "sfixed32_value", "sfixed64_value", "sint32_value", "sint64_value", "nonConventionalNameValue"}, "")) - - pattern_ABitOfEverythingService_CreateBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, "")) - - pattern_ABitOfEverythingService_Lookup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "")) - - pattern_ABitOfEverythingService_Update_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "")) - - pattern_ABitOfEverythingService_Delete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "uuid"}, "")) - - pattern_ABitOfEverythingService_GetQuery_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "query", "uuid"}, "")) - - pattern_ABitOfEverythingService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "a_bit_of_everything", "echo", "value"}, "")) - - pattern_ABitOfEverythingService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, "")) - - pattern_ABitOfEverythingService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "echo"}, "")) - - pattern_ABitOfEverythingService_DeepPathEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "a_bit_of_everything", "single_nested.name"}, "")) - - pattern_ABitOfEverythingService_Timeout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "timeout"}, "")) - - pattern_ABitOfEverythingService_ErrorWithDetails_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "errorwithdetails"}, "")) - - pattern_ABitOfEverythingService_GetMessageWithBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "withbody", "id"}, "")) - - pattern_ABitOfEverythingService_PostWithEmptyBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v2", "example", "postwithemptybody", "name"}, "")) -) - -var ( - forward_ABitOfEverythingService_Create_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_CreateBody_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Lookup_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Update_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Delete_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_GetQuery_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Echo_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Echo_1 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Echo_2 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_DeepPathEcho_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_Timeout_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_ErrorWithDetails_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_GetMessageWithBody_0 = runtime.ForwardResponseMessage - - forward_ABitOfEverythingService_PostWithEmptyBody_0 = runtime.ForwardResponseMessage -) - -// RegisterCamelCaseServiceNameHandlerFromEndpoint is same as RegisterCamelCaseServiceNameHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterCamelCaseServiceNameHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterCamelCaseServiceNameHandler(ctx, mux, conn) -} - -// RegisterCamelCaseServiceNameHandler registers the http handlers for service CamelCaseServiceName to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterCamelCaseServiceNameHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterCamelCaseServiceNameHandlerClient(ctx, mux, NewCamelCaseServiceNameClient(conn)) -} - -// RegisterCamelCaseServiceNameHandler registers the http handlers for service CamelCaseServiceName to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "CamelCaseServiceNameClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "CamelCaseServiceNameClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "CamelCaseServiceNameClient" to call the correct interceptors. -func RegisterCamelCaseServiceNameHandlerClient(ctx context.Context, mux *runtime.ServeMux, client CamelCaseServiceNameClient) error { - - mux.Handle("GET", pattern_CamelCaseServiceName_Empty_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_CamelCaseServiceName_Empty_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_CamelCaseServiceName_Empty_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_CamelCaseServiceName_Empty_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v2", "example", "empty"}, "")) -) - -var ( - forward_CamelCaseServiceName_Empty_0 = runtime.ForwardResponseMessage -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.proto deleted file mode 100755 index 6eaa7d8..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.proto +++ /dev/null @@ -1,316 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; -package grpc.gateway.examples.examplepb; - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/duration.proto"; -import "examples/proto/sub/message.proto"; -import "examples/proto/sub2/message.proto"; -import "google/protobuf/timestamp.proto"; -import "protoc-gen-swagger/options/annotations.proto"; - -option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = { - info: { - title: "A Bit of Everything"; - version: "1.0"; - contact: { - name: "gRPC-Gateway project"; - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - email: "none@example.com"; - }; - }; - // Overwriting host entry breaks tests, so this is not done here. - external_docs: { - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - description: "More about gRPC-Gateway"; - } - schemes: HTTP; - schemes: HTTPS; - schemes: WSS; - consumes: "application/json"; - consumes: "application/x-foo-mime"; - produces: "application/json"; - produces: "application/x-foo-mime"; - security_definitions: { - security: { - key: "BasicAuth"; - value: { - type: TYPE_BASIC; - } - } - security: { - key: "ApiKeyAuth"; - value: { - type: TYPE_API_KEY; - in: IN_HEADER; - name: "X-API-Key"; - } - } - security: { - key: "OAuth2"; - value: { - type: TYPE_OAUTH2; - flow: FLOW_ACCESS_CODE; - authorization_url: "https://example.com/oauth/authorize"; - token_url: "https://example.com/oauth/token"; - scopes: { - scope: { - key: "read"; - value: "Grants read access"; - } - scope: { - key: "write"; - value: "Grants write access"; - } - scope: { - key: "admin"; - value: "Grants read and write access to administrative information"; - } - } - } - } - } - security: { - security_requirement: { - key: "BasicAuth"; - value: {}; - } - security_requirement: { - key: "ApiKeyAuth"; - value: {}; - } - } - security: { - security_requirement: { - key: "OAuth2"; - value: { - scope: "read"; - scope: "write"; - } - } - security_requirement: { - key: "ApiKeyAuth"; - value: {}; - } - } -}; - - -// Intentionaly complicated message type to cover much features of Protobuf. -// NEXT ID: 30 -message ABitOfEverything { - option (grpc.gateway.protoc_gen_swagger.options.openapiv2_schema) = { - external_docs: { - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - description: "Find out more about ABitOfEverything"; - } - }; - - // Nested is nested type. - message Nested { - // name is nested field. - string name = 1; - uint32 amount = 2; - // DeepEnum is one or zero. - enum DeepEnum { - // FALSE is false. - FALSE = 0; - // TRUE is true. - TRUE = 1; - } - DeepEnum ok = 3; - } - Nested single_nested = 25; - - string uuid = 1; - repeated Nested nested = 2; - float float_value = 3; - double double_value = 4; - int64 int64_value = 5; - uint64 uint64_value = 6; - int32 int32_value = 7; - fixed64 fixed64_value = 8; - fixed32 fixed32_value = 9; - bool bool_value = 10; - string string_value = 11; - bytes bytes_value = 29; - uint32 uint32_value = 13; - NumericEnum enum_value = 14; - sfixed32 sfixed32_value = 15; - sfixed64 sfixed64_value = 16; - sint32 sint32_value = 17; - sint64 sint64_value = 18; - repeated string repeated_string_value = 19; - oneof oneof_value { - google.protobuf.Empty oneof_empty = 20; - string oneof_string = 21; - } - - map map_value = 22; - map mapped_string_value = 23; - map mapped_nested_value = 24; - - string nonConventionalNameValue = 26; - - google.protobuf.Timestamp timestamp_value = 27; - - // repeated enum value. it is comma-separated in query - repeated NumericEnum repeated_enum_value = 28; -} - -message Body { - string name = 1; -} - -message MessageWithBody { - string id = 1; - Body data = 2; -} - - -// NumericEnum is one or zero. -enum NumericEnum { - // ZERO means 0 - ZERO = 0; - // ONE means 1 - ONE = 1; -} - -// ABitOfEverything service is used to validate that APIs with complicated -// proto messages and URL templates are still processed correctly. -service ABitOfEverythingService { - - option (grpc.gateway.protoc_gen_swagger.options.openapiv2_tag) = { - description: "ABitOfEverythingService description -- which should not be used in place of the documentation comment!" - external_docs: { - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - description: "Find out more about EchoService"; - } - }; - - rpc Create(ABitOfEverything) returns (ABitOfEverything) { - // TODO add enum_value - option (google.api.http) = { - post: "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value=strprefix/*}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}" - }; - } - rpc CreateBody(ABitOfEverything) returns (ABitOfEverything) { - option (google.api.http) = { - post: "/v1/example/a_bit_of_everything" - body: "*" - }; - } - rpc Lookup(sub2.IdMessage) returns (ABitOfEverything) { - option (google.api.http) = { - get: "/v1/example/a_bit_of_everything/{uuid}" - }; - } - rpc Update(ABitOfEverything) returns (google.protobuf.Empty) { - option (google.api.http) = { - put: "/v1/example/a_bit_of_everything/{uuid}" - body: "*" - }; - } - rpc Delete(sub2.IdMessage) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1/example/a_bit_of_everything/{uuid}" - }; - option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { - security: { - security_requirement: { - key: "ApiKeyAuth"; - value: {} - } - security_requirement: { - key: "OAuth2"; - value: { - scope: "read"; - scope: "write"; - } - } - } - }; - } - rpc GetQuery(ABitOfEverything) returns (google.protobuf.Empty) { - option (google.api.http) = { - get: "/v1/example/a_bit_of_everything/query/{uuid}" - }; - option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { - deprecated: true // For testing purposes. - external_docs: { - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - description: "Find out more about GetQuery"; - } - }; - } - // Echo allows posting a StringMessage value. - // - // It also exposes multiple bindings. - // - // This makes it useful when validating that the OpenAPI v2 API - // description exposes documentation correctly on all paths - // defined as additional_bindings in the proto. - rpc Echo(grpc.gateway.examples.sub.StringMessage) returns (grpc.gateway.examples.sub.StringMessage) { - option (google.api.http) = { - get: "/v1/example/a_bit_of_everything/echo/{value}" - additional_bindings { - post: "/v2/example/echo" - body: "value" - } - additional_bindings { - get: "/v2/example/echo" - } - }; - option (grpc.gateway.protoc_gen_swagger.options.openapiv2_operation) = { - description: "Description Echo"; - summary: "Summary: Echo rpc"; - tags: "echo service"; - tags: "echo rpc"; - external_docs: { - url: "https://github.com/grpc-ecosystem/grpc-gateway"; - description: "Find out more Echo"; - } - }; - } - rpc DeepPathEcho(ABitOfEverything) returns (ABitOfEverything) { - option (google.api.http) = { - post: "/v1/example/a_bit_of_everything/{single_nested.name}" - body: "*" - }; - } - rpc NoBindings(google.protobuf.Duration) returns (google.protobuf.Empty) {} - rpc Timeout(google.protobuf.Empty) returns (google.protobuf.Empty) { - option (google.api.http) = { - get: "/v2/example/timeout", - }; - } - rpc ErrorWithDetails(google.protobuf.Empty) returns (google.protobuf.Empty) { - option (google.api.http) = { - get: "/v2/example/errorwithdetails", - }; - } - rpc GetMessageWithBody(MessageWithBody) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v2/example/withbody/{id}", - body: "data" - }; - } - rpc PostWithEmptyBody(Body) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v2/example/postwithemptybody/{name}", - body: "*" - }; - } -} -// camelCase and lowercase service names are valid but not recommended (use TitleCase instead) -service camelCaseServiceName { - rpc Empty(google.protobuf.Empty) returns (google.protobuf.Empty) { - option (google.api.http) = { - get: "/v2/example/empty", - }; - } -} -service AnotherServiceWithNoBindings { - rpc NoBindings(google.protobuf.Empty) returns (google.protobuf.Empty) {} -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.swagger.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.swagger.json deleted file mode 100755 index aa7f247..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/a_bit_of_everything.swagger.json +++ /dev/null @@ -1,933 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "A Bit of Everything", - "version": "1.0", - "contact": { - "name": "gRPC-Gateway project", - "url": "https://github.com/grpc-ecosystem/grpc-gateway", - "email": "none@example.com" - } - }, - "schemes": [ - "http", - "https", - "wss" - ], - "consumes": [ - "application/json", - "application/x-foo-mime" - ], - "produces": [ - "application/json", - "application/x-foo-mime" - ], - "paths": { - "/v1/example/a_bit_of_everything": { - "post": { - "operationId": "CreateBody", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v1/example/a_bit_of_everything/echo/{value}": { - "get": { - "summary": "Summary: Echo rpc", - "description": "Description Echo", - "operationId": "Echo", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/subStringMessage" - } - } - }, - "parameters": [ - { - "name": "value", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "echo service", - "echo rpc" - ], - "externalDocs": { - "description": "Find out more Echo", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } - } - }, - "/v1/example/a_bit_of_everything/query/{uuid}": { - "get": { - "operationId": "GetQuery", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "uuid", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "single_nested.name", - "description": "name is nested field.", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "single_nested.amount", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "single_nested.ok", - "description": " - FALSE: FALSE is false.\n - TRUE: TRUE is true.", - "in": "query", - "required": false, - "type": "string", - "enum": [ - "FALSE", - "TRUE" - ], - "default": "FALSE" - }, - { - "name": "float_value", - "in": "query", - "required": false, - "type": "number", - "format": "float" - }, - { - "name": "double_value", - "in": "query", - "required": false, - "type": "number", - "format": "double" - }, - { - "name": "int64_value", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "uint64_value", - "in": "query", - "required": false, - "type": "string", - "format": "uint64" - }, - { - "name": "int32_value", - "in": "query", - "required": false, - "type": "integer", - "format": "int32" - }, - { - "name": "fixed64_value", - "in": "query", - "required": false, - "type": "string", - "format": "uint64" - }, - { - "name": "fixed32_value", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "bool_value", - "in": "query", - "required": false, - "type": "boolean", - "format": "boolean" - }, - { - "name": "string_value", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "bytes_value", - "in": "query", - "required": false, - "type": "string", - "format": "byte" - }, - { - "name": "uint32_value", - "in": "query", - "required": false, - "type": "integer", - "format": "int64" - }, - { - "name": "enum_value", - "description": " - ZERO: ZERO means 0\n - ONE: ONE means 1", - "in": "query", - "required": false, - "type": "string", - "enum": [ - "ZERO", - "ONE" - ], - "default": "ZERO" - }, - { - "name": "sfixed32_value", - "in": "query", - "required": false, - "type": "integer", - "format": "int32" - }, - { - "name": "sfixed64_value", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "sint32_value", - "in": "query", - "required": false, - "type": "integer", - "format": "int32" - }, - { - "name": "sint64_value", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "repeated_string_value", - "in": "query", - "required": false, - "type": "array", - "items": { - "type": "string" - } - }, - { - "name": "oneof_string", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "nonConventionalNameValue", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "timestamp_value", - "in": "query", - "required": false, - "type": "string", - "format": "date-time" - }, - { - "name": "repeated_enum_value", - "description": "repeated enum value. it is comma-separated in query.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1", - "in": "query", - "required": false, - "type": "array", - "items": { - "type": "string", - "enum": [ - "ZERO", - "ONE" - ] - } - } - ], - "tags": [ - "ABitOfEverythingService" - ], - "deprecated": true, - "externalDocs": { - "description": "Find out more about GetQuery", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } - } - }, - "/v1/example/a_bit_of_everything/{float_value}/{double_value}/{int64_value}/separator/{uint64_value}/{int32_value}/{fixed64_value}/{fixed32_value}/{bool_value}/{string_value}/{uint32_value}/{sfixed32_value}/{sfixed64_value}/{sint32_value}/{sint64_value}/{nonConventionalNameValue}": { - "post": { - "operationId": "Create", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - }, - "parameters": [ - { - "name": "float_value", - "in": "path", - "required": true, - "type": "number", - "format": "float" - }, - { - "name": "double_value", - "in": "path", - "required": true, - "type": "number", - "format": "double" - }, - { - "name": "int64_value", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "uint64_value", - "in": "path", - "required": true, - "type": "string", - "format": "uint64" - }, - { - "name": "int32_value", - "in": "path", - "required": true, - "type": "integer", - "format": "int32" - }, - { - "name": "fixed64_value", - "in": "path", - "required": true, - "type": "string", - "format": "uint64" - }, - { - "name": "fixed32_value", - "in": "path", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "bool_value", - "in": "path", - "required": true, - "type": "boolean", - "format": "boolean" - }, - { - "name": "string_value", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "uint32_value", - "in": "path", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "sfixed32_value", - "in": "path", - "required": true, - "type": "integer", - "format": "int32" - }, - { - "name": "sfixed64_value", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "sint32_value", - "in": "path", - "required": true, - "type": "integer", - "format": "int32" - }, - { - "name": "sint64_value", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "nonConventionalNameValue", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v1/example/a_bit_of_everything/{single_nested.name}": { - "post": { - "operationId": "DeepPathEcho", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - }, - "parameters": [ - { - "name": "single_nested.name", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v1/example/a_bit_of_everything/{uuid}": { - "get": { - "operationId": "Lookup", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - }, - "parameters": [ - { - "name": "uuid", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "ABitOfEverythingService" - ] - }, - "delete": { - "operationId": "Delete", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "uuid", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "ABitOfEverythingService" - ], - "security": [ - { - "ApiKeyAuth": [], - "OAuth2": [ - "read", - "write" - ] - } - ] - }, - "put": { - "operationId": "Update", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "uuid", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbABitOfEverything" - } - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v2/example/echo": { - "get": { - "summary": "Summary: Echo rpc", - "description": "Description Echo", - "operationId": "Echo3", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/subStringMessage" - } - } - }, - "parameters": [ - { - "name": "value", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "echo service", - "echo rpc" - ], - "externalDocs": { - "description": "Find out more Echo", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } - }, - "post": { - "summary": "Summary: Echo rpc", - "description": "Description Echo", - "operationId": "Echo2", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/subStringMessage" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "type": "string" - } - } - ], - "tags": [ - "echo service", - "echo rpc" - ], - "externalDocs": { - "description": "Find out more Echo", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } - } - }, - "/v2/example/empty": { - "get": { - "operationId": "Empty", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "tags": [ - "camelCaseServiceName" - ] - } - }, - "/v2/example/errorwithdetails": { - "get": { - "operationId": "ErrorWithDetails", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v2/example/postwithemptybody/{name}": { - "post": { - "operationId": "PostWithEmptyBody", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "name", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbBody" - } - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v2/example/timeout": { - "get": { - "operationId": "Timeout", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "tags": [ - "ABitOfEverythingService" - ] - } - }, - "/v2/example/withbody/{id}": { - "post": { - "operationId": "GetMessageWithBody", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/protobufEmpty" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbBody" - } - } - ], - "tags": [ - "ABitOfEverythingService" - ] - } - } - }, - "definitions": { - "ABitOfEverythingNested": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "name is nested field." - }, - "amount": { - "type": "integer", - "format": "int64" - }, - "ok": { - "$ref": "#/definitions/NestedDeepEnum" - } - }, - "description": "Nested is nested type." - }, - "NestedDeepEnum": { - "type": "string", - "enum": [ - "FALSE", - "TRUE" - ], - "default": "FALSE", - "description": "DeepEnum is one or zero.\n\n - FALSE: FALSE is false.\n - TRUE: TRUE is true." - }, - "examplepbABitOfEverything": { - "type": "object", - "properties": { - "single_nested": { - "$ref": "#/definitions/ABitOfEverythingNested" - }, - "uuid": { - "type": "string" - }, - "nested": { - "type": "array", - "items": { - "$ref": "#/definitions/ABitOfEverythingNested" - } - }, - "float_value": { - "type": "number", - "format": "float" - }, - "double_value": { - "type": "number", - "format": "double" - }, - "int64_value": { - "type": "string", - "format": "int64" - }, - "uint64_value": { - "type": "string", - "format": "uint64" - }, - "int32_value": { - "type": "integer", - "format": "int32" - }, - "fixed64_value": { - "type": "string", - "format": "uint64" - }, - "fixed32_value": { - "type": "integer", - "format": "int64" - }, - "bool_value": { - "type": "boolean", - "format": "boolean" - }, - "string_value": { - "type": "string" - }, - "bytes_value": { - "type": "string", - "format": "byte" - }, - "uint32_value": { - "type": "integer", - "format": "int64" - }, - "enum_value": { - "$ref": "#/definitions/examplepbNumericEnum" - }, - "sfixed32_value": { - "type": "integer", - "format": "int32" - }, - "sfixed64_value": { - "type": "string", - "format": "int64" - }, - "sint32_value": { - "type": "integer", - "format": "int32" - }, - "sint64_value": { - "type": "string", - "format": "int64" - }, - "repeated_string_value": { - "type": "array", - "items": { - "type": "string" - } - }, - "oneof_empty": { - "$ref": "#/definitions/protobufEmpty" - }, - "oneof_string": { - "type": "string" - }, - "map_value": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/examplepbNumericEnum" - } - }, - "mapped_string_value": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "mapped_nested_value": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/ABitOfEverythingNested" - } - }, - "nonConventionalNameValue": { - "type": "string" - }, - "timestamp_value": { - "type": "string", - "format": "date-time" - }, - "repeated_enum_value": { - "type": "array", - "items": { - "$ref": "#/definitions/examplepbNumericEnum" - }, - "title": "repeated enum value. it is comma-separated in query" - } - }, - "title": "Intentionaly complicated message type to cover much features of Protobuf.\nNEXT ID: 30", - "externalDocs": { - "description": "Find out more about ABitOfEverything", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } - }, - "examplepbBody": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "examplepbNumericEnum": { - "type": "string", - "enum": [ - "ZERO", - "ONE" - ], - "default": "ZERO", - "description": "NumericEnum is one or zero.\n\n - ZERO: ZERO means 0\n - ONE: ONE means 1" - }, - "protobufEmpty": { - "type": "object", - "description": "service Foo {\n rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);\n }\n\nThe JSON representation for `Empty` is empty JSON object `{}`.", - "title": "A generic empty message that you can re-use to avoid defining duplicated\nempty messages in your APIs. A typical example is to use it as the request\nor the response type of an API method. For instance:" - }, - "subStringMessage": { - "type": "object", - "properties": { - "value": { - "type": "string" - } - } - } - }, - "securityDefinitions": { - "ApiKeyAuth": { - "type": "apiKey", - "name": "X-API-Key", - "in": "header" - }, - "BasicAuth": { - "type": "basic" - }, - "OAuth2": { - "type": "oauth2", - "flow": "accessCode", - "authorizationUrl": "https://example.com/oauth/authorize", - "tokenUrl": "https://example.com/oauth/token", - "scopes": { - "admin": "Grants read and write access to administrative information", - "read": "Grants read access", - "write": "Grants write access" - } - } - }, - "security": [ - { - "ApiKeyAuth": [], - "BasicAuth": [] - }, - { - "ApiKeyAuth": [], - "OAuth2": [ - "read", - "write" - ] - } - ], - "externalDocs": { - "description": "More about gRPC-Gateway", - "url": "https://github.com/grpc-ecosystem/grpc-gateway" - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.go deleted file mode 100755 index 42a70d1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.go +++ /dev/null @@ -1,600 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/echo_service.proto - -package examplepb - -/* -Echo Service - -Echo Service API consists of a single service which returns -a message. -*/ - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Embedded represents a message embedded in SimpleMessage. -type Embedded struct { - // Types that are valid to be assigned to Mark: - // *Embedded_Progress - // *Embedded_Note - Mark isEmbedded_Mark `protobuf_oneof:"mark"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Embedded) Reset() { *m = Embedded{} } -func (m *Embedded) String() string { return proto.CompactTextString(m) } -func (*Embedded) ProtoMessage() {} -func (*Embedded) Descriptor() ([]byte, []int) { - return fileDescriptor_echo_service_c13a64d5f1f0c068, []int{0} -} -func (m *Embedded) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Embedded.Unmarshal(m, b) -} -func (m *Embedded) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Embedded.Marshal(b, m, deterministic) -} -func (dst *Embedded) XXX_Merge(src proto.Message) { - xxx_messageInfo_Embedded.Merge(dst, src) -} -func (m *Embedded) XXX_Size() int { - return xxx_messageInfo_Embedded.Size(m) -} -func (m *Embedded) XXX_DiscardUnknown() { - xxx_messageInfo_Embedded.DiscardUnknown(m) -} - -var xxx_messageInfo_Embedded proto.InternalMessageInfo - -type isEmbedded_Mark interface { - isEmbedded_Mark() -} - -type Embedded_Progress struct { - Progress int64 `protobuf:"varint,1,opt,name=progress,oneof"` -} -type Embedded_Note struct { - Note string `protobuf:"bytes,2,opt,name=note,oneof"` -} - -func (*Embedded_Progress) isEmbedded_Mark() {} -func (*Embedded_Note) isEmbedded_Mark() {} - -func (m *Embedded) GetMark() isEmbedded_Mark { - if m != nil { - return m.Mark - } - return nil -} - -func (m *Embedded) GetProgress() int64 { - if x, ok := m.GetMark().(*Embedded_Progress); ok { - return x.Progress - } - return 0 -} - -func (m *Embedded) GetNote() string { - if x, ok := m.GetMark().(*Embedded_Note); ok { - return x.Note - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Embedded) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Embedded_OneofMarshaler, _Embedded_OneofUnmarshaler, _Embedded_OneofSizer, []interface{}{ - (*Embedded_Progress)(nil), - (*Embedded_Note)(nil), - } -} - -func _Embedded_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Embedded) - // mark - switch x := m.Mark.(type) { - case *Embedded_Progress: - b.EncodeVarint(1<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Progress)) - case *Embedded_Note: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Note) - case nil: - default: - return fmt.Errorf("Embedded.Mark has unexpected type %T", x) - } - return nil -} - -func _Embedded_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Embedded) - switch tag { - case 1: // mark.progress - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Mark = &Embedded_Progress{int64(x)} - return true, err - case 2: // mark.note - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Mark = &Embedded_Note{x} - return true, err - default: - return false, nil - } -} - -func _Embedded_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Embedded) - // mark - switch x := m.Mark.(type) { - case *Embedded_Progress: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.Progress)) - case *Embedded_Note: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Note))) - n += len(x.Note) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// SimpleMessage represents a simple message sent to the Echo service. -type SimpleMessage struct { - // Id represents the message identifier. - Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` - Num int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - // Types that are valid to be assigned to Code: - // *SimpleMessage_LineNum - // *SimpleMessage_Lang - Code isSimpleMessage_Code `protobuf_oneof:"code"` - Status *Embedded `protobuf:"bytes,5,opt,name=status" json:"status,omitempty"` - // Types that are valid to be assigned to Ext: - // *SimpleMessage_En - // *SimpleMessage_No - Ext isSimpleMessage_Ext `protobuf_oneof:"ext"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleMessage) Reset() { *m = SimpleMessage{} } -func (m *SimpleMessage) String() string { return proto.CompactTextString(m) } -func (*SimpleMessage) ProtoMessage() {} -func (*SimpleMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_echo_service_c13a64d5f1f0c068, []int{1} -} -func (m *SimpleMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleMessage.Unmarshal(m, b) -} -func (m *SimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleMessage.Marshal(b, m, deterministic) -} -func (dst *SimpleMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleMessage.Merge(dst, src) -} -func (m *SimpleMessage) XXX_Size() int { - return xxx_messageInfo_SimpleMessage.Size(m) -} -func (m *SimpleMessage) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleMessage proto.InternalMessageInfo - -type isSimpleMessage_Code interface { - isSimpleMessage_Code() -} -type isSimpleMessage_Ext interface { - isSimpleMessage_Ext() -} - -type SimpleMessage_LineNum struct { - LineNum int64 `protobuf:"varint,3,opt,name=line_num,json=lineNum,oneof"` -} -type SimpleMessage_Lang struct { - Lang string `protobuf:"bytes,4,opt,name=lang,oneof"` -} -type SimpleMessage_En struct { - En int64 `protobuf:"varint,6,opt,name=en,oneof"` -} -type SimpleMessage_No struct { - No *Embedded `protobuf:"bytes,7,opt,name=no,oneof"` -} - -func (*SimpleMessage_LineNum) isSimpleMessage_Code() {} -func (*SimpleMessage_Lang) isSimpleMessage_Code() {} -func (*SimpleMessage_En) isSimpleMessage_Ext() {} -func (*SimpleMessage_No) isSimpleMessage_Ext() {} - -func (m *SimpleMessage) GetCode() isSimpleMessage_Code { - if m != nil { - return m.Code - } - return nil -} -func (m *SimpleMessage) GetExt() isSimpleMessage_Ext { - if m != nil { - return m.Ext - } - return nil -} - -func (m *SimpleMessage) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *SimpleMessage) GetNum() int64 { - if m != nil { - return m.Num - } - return 0 -} - -func (m *SimpleMessage) GetLineNum() int64 { - if x, ok := m.GetCode().(*SimpleMessage_LineNum); ok { - return x.LineNum - } - return 0 -} - -func (m *SimpleMessage) GetLang() string { - if x, ok := m.GetCode().(*SimpleMessage_Lang); ok { - return x.Lang - } - return "" -} - -func (m *SimpleMessage) GetStatus() *Embedded { - if m != nil { - return m.Status - } - return nil -} - -func (m *SimpleMessage) GetEn() int64 { - if x, ok := m.GetExt().(*SimpleMessage_En); ok { - return x.En - } - return 0 -} - -func (m *SimpleMessage) GetNo() *Embedded { - if x, ok := m.GetExt().(*SimpleMessage_No); ok { - return x.No - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*SimpleMessage) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _SimpleMessage_OneofMarshaler, _SimpleMessage_OneofUnmarshaler, _SimpleMessage_OneofSizer, []interface{}{ - (*SimpleMessage_LineNum)(nil), - (*SimpleMessage_Lang)(nil), - (*SimpleMessage_En)(nil), - (*SimpleMessage_No)(nil), - } -} - -func _SimpleMessage_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*SimpleMessage) - // code - switch x := m.Code.(type) { - case *SimpleMessage_LineNum: - b.EncodeVarint(3<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.LineNum)) - case *SimpleMessage_Lang: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Lang) - case nil: - default: - return fmt.Errorf("SimpleMessage.Code has unexpected type %T", x) - } - // ext - switch x := m.Ext.(type) { - case *SimpleMessage_En: - b.EncodeVarint(6<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.En)) - case *SimpleMessage_No: - b.EncodeVarint(7<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.No); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("SimpleMessage.Ext has unexpected type %T", x) - } - return nil -} - -func _SimpleMessage_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*SimpleMessage) - switch tag { - case 3: // code.line_num - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Code = &SimpleMessage_LineNum{int64(x)} - return true, err - case 4: // code.lang - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Code = &SimpleMessage_Lang{x} - return true, err - case 6: // ext.en - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Ext = &SimpleMessage_En{int64(x)} - return true, err - case 7: // ext.no - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Embedded) - err := b.DecodeMessage(msg) - m.Ext = &SimpleMessage_No{msg} - return true, err - default: - return false, nil - } -} - -func _SimpleMessage_OneofSizer(msg proto.Message) (n int) { - m := msg.(*SimpleMessage) - // code - switch x := m.Code.(type) { - case *SimpleMessage_LineNum: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.LineNum)) - case *SimpleMessage_Lang: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Lang))) - n += len(x.Lang) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - // ext - switch x := m.Ext.(type) { - case *SimpleMessage_En: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.En)) - case *SimpleMessage_No: - s := proto.Size(x.No) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -func init() { - proto.RegisterType((*Embedded)(nil), "grpc.gateway.examples.examplepb.Embedded") - proto.RegisterType((*SimpleMessage)(nil), "grpc.gateway.examples.examplepb.SimpleMessage") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// EchoServiceClient is the client API for EchoService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type EchoServiceClient interface { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) - // EchoBody method receives a simple message and returns it. - EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) - // EchoDelete method receives a simple message and returns it. - EchoDelete(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) -} - -type echoServiceClient struct { - cc *grpc.ClientConn -} - -func NewEchoServiceClient(cc *grpc.ClientConn) EchoServiceClient { - return &echoServiceClient{cc} -} - -func (c *echoServiceClient) Echo(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { - out := new(SimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.EchoService/Echo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *echoServiceClient) EchoBody(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { - out := new(SimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.EchoService/EchoBody", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *echoServiceClient) EchoDelete(ctx context.Context, in *SimpleMessage, opts ...grpc.CallOption) (*SimpleMessage, error) { - out := new(SimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.EchoService/EchoDelete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// EchoServiceServer is the server API for EchoService service. -type EchoServiceServer interface { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - Echo(context.Context, *SimpleMessage) (*SimpleMessage, error) - // EchoBody method receives a simple message and returns it. - EchoBody(context.Context, *SimpleMessage) (*SimpleMessage, error) - // EchoDelete method receives a simple message and returns it. - EchoDelete(context.Context, *SimpleMessage) (*SimpleMessage, error) -} - -func RegisterEchoServiceServer(s *grpc.Server, srv EchoServiceServer) { - s.RegisterService(&_EchoService_serviceDesc, srv) -} - -func _EchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EchoServiceServer).Echo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.EchoService/Echo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EchoServiceServer).Echo(ctx, req.(*SimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _EchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EchoServiceServer).EchoBody(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.EchoService/EchoBody", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EchoServiceServer).EchoBody(ctx, req.(*SimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _EchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(EchoServiceServer).EchoDelete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.EchoService/EchoDelete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(EchoServiceServer).EchoDelete(ctx, req.(*SimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -var _EchoService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.EchoService", - HandlerType: (*EchoServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Echo", - Handler: _EchoService_Echo_Handler, - }, - { - MethodName: "EchoBody", - Handler: _EchoService_EchoBody_Handler, - }, - { - MethodName: "EchoDelete", - Handler: _EchoService_EchoDelete_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/echo_service.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/echo_service.proto", fileDescriptor_echo_service_c13a64d5f1f0c068) -} - -var fileDescriptor_echo_service_c13a64d5f1f0c068 = []byte{ - // 470 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x53, 0x3f, 0x6f, 0xd3, 0x40, - 0x14, 0xef, 0xd9, 0x6e, 0x9a, 0xbc, 0x08, 0x54, 0x9d, 0x40, 0x98, 0xb4, 0xa8, 0x91, 0xc5, 0x10, - 0x8a, 0xe4, 0x53, 0xc2, 0x06, 0x13, 0x11, 0x45, 0x5d, 0x60, 0x70, 0xb7, 0x2c, 0xd1, 0xc5, 0xf7, - 0xe4, 0x5a, 0xd8, 0x77, 0x96, 0x7d, 0x29, 0x8d, 0xac, 0x2c, 0x48, 0x6c, 0x30, 0xb1, 0xf3, 0x11, - 0xd8, 0xf8, 0x18, 0x4c, 0x7c, 0x05, 0x3e, 0x08, 0xba, 0x4b, 0x1c, 0x09, 0x5a, 0xb5, 0xea, 0x90, - 0xcd, 0xef, 0xcf, 0xef, 0xfd, 0x7e, 0xf7, 0x7b, 0xcf, 0xf0, 0x1c, 0x2f, 0x79, 0x5e, 0x64, 0x58, - 0xb1, 0xa2, 0x54, 0x5a, 0xb1, 0x75, 0x58, 0xcc, 0x18, 0xc6, 0xe7, 0x6a, 0x5a, 0x61, 0x79, 0x91, - 0xc6, 0x18, 0xda, 0x22, 0x3d, 0x4a, 0xca, 0x22, 0x0e, 0x13, 0xae, 0xf1, 0x23, 0x5f, 0x84, 0x0d, - 0x32, 0xdc, 0x60, 0x7a, 0x87, 0x89, 0x52, 0x49, 0x86, 0x8c, 0x17, 0x29, 0xe3, 0x52, 0x2a, 0xcd, - 0x75, 0xaa, 0x64, 0xb5, 0x82, 0x07, 0x6f, 0xa1, 0x7d, 0x92, 0xcf, 0x50, 0x08, 0x14, 0xf4, 0x10, - 0xda, 0x45, 0xa9, 0x92, 0x12, 0xab, 0xca, 0x27, 0x7d, 0x32, 0x70, 0x4f, 0x77, 0xa2, 0x4d, 0x86, - 0x3e, 0x00, 0x4f, 0x2a, 0x8d, 0xbe, 0xd3, 0x27, 0x83, 0xce, 0xe9, 0x4e, 0x64, 0xa3, 0x71, 0x0b, - 0xbc, 0x9c, 0x97, 0x1f, 0x82, 0xcf, 0x0e, 0xdc, 0x3b, 0x4b, 0x0d, 0xe5, 0x3b, 0xac, 0x2a, 0x9e, - 0x20, 0xbd, 0x0f, 0x4e, 0x2a, 0xec, 0x9c, 0x4e, 0xe4, 0xa4, 0x82, 0xee, 0x83, 0x2b, 0xe7, 0xb9, - 0x85, 0xbb, 0x91, 0xf9, 0xa4, 0x07, 0xd0, 0xce, 0x52, 0x89, 0x53, 0x93, 0x76, 0xd7, 0x7c, 0x7b, - 0x26, 0xf3, 0x7e, 0x9e, 0x1b, 0xba, 0x8c, 0xcb, 0xc4, 0xf7, 0x1a, 0x3a, 0x13, 0xd1, 0xd7, 0xd0, - 0xaa, 0x34, 0xd7, 0xf3, 0xca, 0xdf, 0xed, 0x93, 0x41, 0x77, 0xf4, 0x2c, 0xbc, 0xe5, 0xf9, 0x61, - 0xf3, 0xba, 0x68, 0x0d, 0xa4, 0xfb, 0xe0, 0xa0, 0xf4, 0x5b, 0x96, 0x8f, 0x44, 0x0e, 0x4a, 0xfa, - 0x0a, 0x1c, 0xa9, 0xfc, 0xbd, 0x3b, 0x0e, 0x34, 0x60, 0xa9, 0x8c, 0x01, 0xb1, 0x12, 0x38, 0xde, - 0x05, 0x17, 0x2f, 0xf5, 0xe8, 0x97, 0x07, 0xdd, 0x93, 0xf8, 0x5c, 0x9d, 0xad, 0x96, 0x44, 0xbf, - 0x3b, 0xe0, 0x99, 0x98, 0x86, 0xb7, 0x0e, 0xfe, 0xc7, 0xbe, 0xde, 0x1d, 0xfb, 0x83, 0x9f, 0xe4, - 0xd3, 0xef, 0x3f, 0xdf, 0x9c, 0x1f, 0x24, 0x78, 0xc8, 0x2e, 0x86, 0xcd, 0xcd, 0xd8, 0x8b, 0x61, - 0x75, 0x2a, 0x96, 0x93, 0x27, 0xf4, 0xe0, 0xda, 0x02, 0xab, 0xe5, 0x3c, 0x5f, 0x4e, 0x9e, 0xd2, - 0xe0, 0x86, 0x32, 0xab, 0x8d, 0xfd, 0xcb, 0xc9, 0x90, 0xb2, 0xff, 0xbb, 0x86, 0xeb, 0xb6, 0x66, - 0x95, 0x4b, 0x56, 0xaf, 0x9c, 0x0e, 0xcd, 0x81, 0x5c, 0xcb, 0x3b, 0x62, 0xb5, 0x54, 0xab, 0x32, - 0xfd, 0x42, 0xa0, 0x6d, 0x0c, 0x1a, 0x2b, 0xb1, 0xd8, 0xba, 0x49, 0x7d, 0xeb, 0x51, 0xef, 0xaa, - 0x45, 0xd3, 0x99, 0x12, 0x8b, 0x97, 0xe4, 0x98, 0x7e, 0x25, 0x00, 0x46, 0xce, 0x1b, 0xcc, 0x50, - 0xe3, 0xd6, 0x05, 0x1d, 0x59, 0x41, 0x8f, 0x8f, 0x1f, 0x5d, 0x11, 0x24, 0xac, 0x80, 0x71, 0x77, - 0xd2, 0xd9, 0x60, 0x67, 0x2d, 0xfb, 0xcf, 0xbe, 0xf8, 0x1b, 0x00, 0x00, 0xff, 0xff, 0xe9, 0xdb, - 0x6f, 0x39, 0x21, 0x04, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.gw.go deleted file mode 100755 index 844ef14..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.pb.gw.go +++ /dev/null @@ -1,575 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/echo_service.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -var ( - filter_EchoService_Echo_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_EchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_EchoService_Echo_1 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} -) - -func request_EchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - val, ok = pathParams["num"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") - } - - protoReq.Num, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_1); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_EchoService_Echo_2 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1, "lang": 2}, Base: []int{1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 1, 2, 3, 4}} -) - -func request_EchoService_Echo_2(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - val, ok = pathParams["num"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") - } - - protoReq.Num, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) - } - - val, ok = pathParams["lang"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "lang") - } - - if protoReq.Code == nil { - protoReq.Code = &SimpleMessage_Lang{} - } else if _, ok := protoReq.Code.(*SimpleMessage_Lang); !ok { - return nil, metadata, grpc.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_Lang, but: %t\n", protoReq.Code) - } - protoReq.Code.(*SimpleMessage_Lang).Lang, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "lang", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_EchoService_Echo_3 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "line_num": 1, "status": 2, "note": 3}, Base: []int{1, 1, 2, 1, 3, 0, 0, 0}, Check: []int{0, 1, 1, 1, 4, 2, 3, 5}} -) - -func request_EchoService_Echo_3(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - val, ok = pathParams["line_num"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "line_num") - } - - if protoReq.Code == nil { - protoReq.Code = &SimpleMessage_LineNum{} - } else if _, ok := protoReq.Code.(*SimpleMessage_LineNum); !ok { - return nil, metadata, grpc.Errorf(codes.InvalidArgument, "expect type: *SimpleMessage_LineNum, but: %t\n", protoReq.Code) - } - protoReq.Code.(*SimpleMessage_LineNum).LineNum, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "line_num", err) - } - - val, ok = pathParams["status.note"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "status.note") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "status.note", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "status.note", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_3); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_EchoService_Echo_4 = &utilities.DoubleArray{Encoding: map[string]int{"no": 0, "note": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} -) - -func request_EchoService_Echo_4(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["no.note"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "no.note") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "no.note", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "no.note", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_Echo_4); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_EchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_EchoService_EchoDelete_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_EchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client EchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SimpleMessage - var metadata runtime.ServerMetadata - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_EchoService_EchoDelete_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterEchoServiceHandlerFromEndpoint is same as RegisterEchoServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterEchoServiceHandler(ctx, mux, conn) -} - -// RegisterEchoServiceHandler registers the http handlers for service EchoService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterEchoServiceHandlerClient(ctx, mux, NewEchoServiceClient(conn)) -} - -// RegisterEchoServiceHandler registers the http handlers for service EchoService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "EchoServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "EchoServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "EchoServiceClient" to call the correct interceptors. -func RegisterEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client EchoServiceClient) error { - - mux.Handle("POST", pattern_EchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_EchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_EchoService_Echo_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_Echo_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_Echo_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_EchoService_Echo_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_Echo_3(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_Echo_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_EchoService_Echo_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_Echo_4(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_Echo_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_EchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("DELETE", pattern_EchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_EchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_EchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_EchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo", "id"}, "")) - - pattern_EchoService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "echo", "id", "num"}, "")) - - pattern_EchoService_Echo_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "echo", "id", "num", "lang"}, "")) - - pattern_EchoService_Echo_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "example", "echo1", "id", "line_num", "status.note"}, "")) - - pattern_EchoService_Echo_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo2", "no.note"}, "")) - - pattern_EchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, "")) - - pattern_EchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, "")) -) - -var ( - forward_EchoService_Echo_0 = runtime.ForwardResponseMessage - - forward_EchoService_Echo_1 = runtime.ForwardResponseMessage - - forward_EchoService_Echo_2 = runtime.ForwardResponseMessage - - forward_EchoService_Echo_3 = runtime.ForwardResponseMessage - - forward_EchoService_Echo_4 = runtime.ForwardResponseMessage - - forward_EchoService_EchoBody_0 = runtime.ForwardResponseMessage - - forward_EchoService_EchoDelete_0 = runtime.ForwardResponseMessage -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.proto deleted file mode 100755 index 710d057..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.proto +++ /dev/null @@ -1,72 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; - -// Echo Service -// -// Echo Service API consists of a single service which returns -// a message. -package grpc.gateway.examples.examplepb; - -import "google/api/annotations.proto"; - -// Embedded represents a message embedded in SimpleMessage. -message Embedded { - oneof mark { - int64 progress = 1; - string note = 2; - } -} - -// SimpleMessage represents a simple message sent to the Echo service. -message SimpleMessage { - // Id represents the message identifier. - string id = 1; - int64 num = 2; - oneof code { - int64 line_num = 3; - string lang = 4; - } - Embedded status = 5; - oneof ext { - int64 en = 6; - Embedded no = 7; - } -} - -// Echo service responds to incoming echo requests. -service EchoService { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - rpc Echo(SimpleMessage) returns (SimpleMessage) { - option (google.api.http) = { - post: "/v1/example/echo/{id}" - additional_bindings { - get: "/v1/example/echo/{id}/{num}" - } - additional_bindings { - get: "/v1/example/echo/{id}/{num}/{lang}" - } - additional_bindings { - get: "/v1/example/echo1/{id}/{line_num}/{status.note}" - } - additional_bindings { - get: "/v1/example/echo2/{no.note}" - } - }; - } - // EchoBody method receives a simple message and returns it. - rpc EchoBody(SimpleMessage) returns (SimpleMessage) { - option (google.api.http) = { - post: "/v1/example/echo_body" - body: "*" - }; - } - // EchoDelete method receives a simple message and returns it. - rpc EchoDelete(SimpleMessage) returns (SimpleMessage) { - option (google.api.http) = { - delete: "/v1/example/echo_delete" - }; - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.swagger.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.swagger.json deleted file mode 100755 index c14354f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/echo_service.swagger.json +++ /dev/null @@ -1,503 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "Echo Service", - "description": "Echo Service API consists of a single service which returns\na message.", - "version": "version not set" - }, - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/v1/example/echo/{id}": { - "post": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo/{id}/{num}": { - "get": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo2", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "num", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "line_num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "lang", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "status.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "status.note", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "en", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.note", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo/{id}/{num}/{lang}": { - "get": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo3", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "num", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "lang", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "line_num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "status.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "status.note", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "en", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.note", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo1/{id}/{line_num}/{status.note}": { - "get": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo4", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "line_num", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "status.note", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "lang", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "status.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "en", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo2/{no.note}": { - "get": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo5", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "no.note", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "id", - "description": "Id represents the message identifier.", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "line_num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "lang", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "status.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "en", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo_body": { - "post": { - "summary": "EchoBody method receives a simple message and returns it.", - "operationId": "EchoBody", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - ], - "tags": [ - "EchoService" - ] - } - }, - "/v1/example/echo_delete": { - "delete": { - "summary": "EchoDelete method receives a simple message and returns it.", - "operationId": "EchoDelete", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "description": "Id represents the message identifier.", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "line_num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "lang", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "status.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "status.note", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "en", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.progress", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "no.note", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "EchoService" - ] - } - } - }, - "definitions": { - "examplepbEmbedded": { - "type": "object", - "properties": { - "progress": { - "type": "string", - "format": "int64" - }, - "note": { - "type": "string" - } - }, - "description": "Embedded represents a message embedded in SimpleMessage." - }, - "examplepbSimpleMessage": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Id represents the message identifier." - }, - "num": { - "type": "string", - "format": "int64" - }, - "line_num": { - "type": "string", - "format": "int64" - }, - "lang": { - "type": "string" - }, - "status": { - "$ref": "#/definitions/examplepbEmbedded" - }, - "en": { - "type": "string", - "format": "int64" - }, - "no": { - "$ref": "#/definitions/examplepbEmbedded" - } - }, - "description": "SimpleMessage represents a simple message sent to the Echo service." - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.go deleted file mode 100755 index 55be438..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.go +++ /dev/null @@ -1,840 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/flow_combination.proto - -package examplepb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type EmptyProto struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EmptyProto) Reset() { *m = EmptyProto{} } -func (m *EmptyProto) String() string { return proto.CompactTextString(m) } -func (*EmptyProto) ProtoMessage() {} -func (*EmptyProto) Descriptor() ([]byte, []int) { - return fileDescriptor_flow_combination_40371c0acedc1fc5, []int{0} -} -func (m *EmptyProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EmptyProto.Unmarshal(m, b) -} -func (m *EmptyProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EmptyProto.Marshal(b, m, deterministic) -} -func (dst *EmptyProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EmptyProto.Merge(dst, src) -} -func (m *EmptyProto) XXX_Size() int { - return xxx_messageInfo_EmptyProto.Size(m) -} -func (m *EmptyProto) XXX_DiscardUnknown() { - xxx_messageInfo_EmptyProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EmptyProto proto.InternalMessageInfo - -type NonEmptyProto struct { - A string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"` - B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"` - C string `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NonEmptyProto) Reset() { *m = NonEmptyProto{} } -func (m *NonEmptyProto) String() string { return proto.CompactTextString(m) } -func (*NonEmptyProto) ProtoMessage() {} -func (*NonEmptyProto) Descriptor() ([]byte, []int) { - return fileDescriptor_flow_combination_40371c0acedc1fc5, []int{1} -} -func (m *NonEmptyProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NonEmptyProto.Unmarshal(m, b) -} -func (m *NonEmptyProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NonEmptyProto.Marshal(b, m, deterministic) -} -func (dst *NonEmptyProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_NonEmptyProto.Merge(dst, src) -} -func (m *NonEmptyProto) XXX_Size() int { - return xxx_messageInfo_NonEmptyProto.Size(m) -} -func (m *NonEmptyProto) XXX_DiscardUnknown() { - xxx_messageInfo_NonEmptyProto.DiscardUnknown(m) -} - -var xxx_messageInfo_NonEmptyProto proto.InternalMessageInfo - -func (m *NonEmptyProto) GetA() string { - if m != nil { - return m.A - } - return "" -} - -func (m *NonEmptyProto) GetB() string { - if m != nil { - return m.B - } - return "" -} - -func (m *NonEmptyProto) GetC() string { - if m != nil { - return m.C - } - return "" -} - -type UnaryProto struct { - Str string `protobuf:"bytes,1,opt,name=str" json:"str,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UnaryProto) Reset() { *m = UnaryProto{} } -func (m *UnaryProto) String() string { return proto.CompactTextString(m) } -func (*UnaryProto) ProtoMessage() {} -func (*UnaryProto) Descriptor() ([]byte, []int) { - return fileDescriptor_flow_combination_40371c0acedc1fc5, []int{2} -} -func (m *UnaryProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UnaryProto.Unmarshal(m, b) -} -func (m *UnaryProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UnaryProto.Marshal(b, m, deterministic) -} -func (dst *UnaryProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_UnaryProto.Merge(dst, src) -} -func (m *UnaryProto) XXX_Size() int { - return xxx_messageInfo_UnaryProto.Size(m) -} -func (m *UnaryProto) XXX_DiscardUnknown() { - xxx_messageInfo_UnaryProto.DiscardUnknown(m) -} - -var xxx_messageInfo_UnaryProto proto.InternalMessageInfo - -func (m *UnaryProto) GetStr() string { - if m != nil { - return m.Str - } - return "" -} - -type NestedProto struct { - A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"` - B string `protobuf:"bytes,2,opt,name=b" json:"b,omitempty"` - C string `protobuf:"bytes,3,opt,name=c" json:"c,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NestedProto) Reset() { *m = NestedProto{} } -func (m *NestedProto) String() string { return proto.CompactTextString(m) } -func (*NestedProto) ProtoMessage() {} -func (*NestedProto) Descriptor() ([]byte, []int) { - return fileDescriptor_flow_combination_40371c0acedc1fc5, []int{3} -} -func (m *NestedProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NestedProto.Unmarshal(m, b) -} -func (m *NestedProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NestedProto.Marshal(b, m, deterministic) -} -func (dst *NestedProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_NestedProto.Merge(dst, src) -} -func (m *NestedProto) XXX_Size() int { - return xxx_messageInfo_NestedProto.Size(m) -} -func (m *NestedProto) XXX_DiscardUnknown() { - xxx_messageInfo_NestedProto.DiscardUnknown(m) -} - -var xxx_messageInfo_NestedProto proto.InternalMessageInfo - -func (m *NestedProto) GetA() *UnaryProto { - if m != nil { - return m.A - } - return nil -} - -func (m *NestedProto) GetB() string { - if m != nil { - return m.B - } - return "" -} - -func (m *NestedProto) GetC() string { - if m != nil { - return m.C - } - return "" -} - -type SingleNestedProto struct { - A *UnaryProto `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SingleNestedProto) Reset() { *m = SingleNestedProto{} } -func (m *SingleNestedProto) String() string { return proto.CompactTextString(m) } -func (*SingleNestedProto) ProtoMessage() {} -func (*SingleNestedProto) Descriptor() ([]byte, []int) { - return fileDescriptor_flow_combination_40371c0acedc1fc5, []int{4} -} -func (m *SingleNestedProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SingleNestedProto.Unmarshal(m, b) -} -func (m *SingleNestedProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SingleNestedProto.Marshal(b, m, deterministic) -} -func (dst *SingleNestedProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_SingleNestedProto.Merge(dst, src) -} -func (m *SingleNestedProto) XXX_Size() int { - return xxx_messageInfo_SingleNestedProto.Size(m) -} -func (m *SingleNestedProto) XXX_DiscardUnknown() { - xxx_messageInfo_SingleNestedProto.DiscardUnknown(m) -} - -var xxx_messageInfo_SingleNestedProto proto.InternalMessageInfo - -func (m *SingleNestedProto) GetA() *UnaryProto { - if m != nil { - return m.A - } - return nil -} - -func init() { - proto.RegisterType((*EmptyProto)(nil), "grpc.gateway.examples.examplepb.EmptyProto") - proto.RegisterType((*NonEmptyProto)(nil), "grpc.gateway.examples.examplepb.NonEmptyProto") - proto.RegisterType((*UnaryProto)(nil), "grpc.gateway.examples.examplepb.UnaryProto") - proto.RegisterType((*NestedProto)(nil), "grpc.gateway.examples.examplepb.NestedProto") - proto.RegisterType((*SingleNestedProto)(nil), "grpc.gateway.examples.examplepb.SingleNestedProto") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// FlowCombinationClient is the client API for FlowCombination service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type FlowCombinationClient interface { - RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) - RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) - StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) - StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) - RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) - RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) - RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) - RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) - RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) - RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) -} - -type flowCombinationClient struct { - cc *grpc.ClientConn -} - -func NewFlowCombinationClient(cc *grpc.ClientConn) FlowCombinationClient { - return &flowCombinationClient{cc} -} - -func (c *flowCombinationClient) RpcEmptyRpc(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) { - out := new(EmptyProto) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *flowCombinationClient) RpcEmptyStream(ctx context.Context, in *EmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcEmptyStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[0], "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyStream", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationRpcEmptyStreamClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type FlowCombination_RpcEmptyStreamClient interface { - Recv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationRpcEmptyStreamClient struct { - grpc.ClientStream -} - -func (x *flowCombinationRpcEmptyStreamClient) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *flowCombinationClient) StreamEmptyRpc(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyRpcClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[1], "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyRpc", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationStreamEmptyRpcClient{stream} - return x, nil -} - -type FlowCombination_StreamEmptyRpcClient interface { - Send(*EmptyProto) error - CloseAndRecv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationStreamEmptyRpcClient struct { - grpc.ClientStream -} - -func (x *flowCombinationStreamEmptyRpcClient) Send(m *EmptyProto) error { - return x.ClientStream.SendMsg(m) -} - -func (x *flowCombinationStreamEmptyRpcClient) CloseAndRecv() (*EmptyProto, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *flowCombinationClient) StreamEmptyStream(ctx context.Context, opts ...grpc.CallOption) (FlowCombination_StreamEmptyStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[2], "/grpc.gateway.examples.examplepb.FlowCombination/StreamEmptyStream", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationStreamEmptyStreamClient{stream} - return x, nil -} - -type FlowCombination_StreamEmptyStreamClient interface { - Send(*EmptyProto) error - Recv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationStreamEmptyStreamClient struct { - grpc.ClientStream -} - -func (x *flowCombinationStreamEmptyStreamClient) Send(m *EmptyProto) error { - return x.ClientStream.SendMsg(m) -} - -func (x *flowCombinationStreamEmptyStreamClient) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *flowCombinationClient) RpcBodyRpc(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (*EmptyProto, error) { - out := new(EmptyProto) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *flowCombinationClient) RpcPathSingleNestedRpc(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (*EmptyProto, error) { - out := new(EmptyProto) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *flowCombinationClient) RpcPathNestedRpc(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (*EmptyProto, error) { - out := new(EmptyProto) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *flowCombinationClient) RpcBodyStream(ctx context.Context, in *NonEmptyProto, opts ...grpc.CallOption) (FlowCombination_RpcBodyStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[3], "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyStream", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationRpcBodyStreamClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type FlowCombination_RpcBodyStreamClient interface { - Recv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationRpcBodyStreamClient struct { - grpc.ClientStream -} - -func (x *flowCombinationRpcBodyStreamClient) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *flowCombinationClient) RpcPathSingleNestedStream(ctx context.Context, in *SingleNestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathSingleNestedStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[4], "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedStream", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationRpcPathSingleNestedStreamClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type FlowCombination_RpcPathSingleNestedStreamClient interface { - Recv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationRpcPathSingleNestedStreamClient struct { - grpc.ClientStream -} - -func (x *flowCombinationRpcPathSingleNestedStreamClient) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *flowCombinationClient) RpcPathNestedStream(ctx context.Context, in *NestedProto, opts ...grpc.CallOption) (FlowCombination_RpcPathNestedStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &_FlowCombination_serviceDesc.Streams[5], "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedStream", opts...) - if err != nil { - return nil, err - } - x := &flowCombinationRpcPathNestedStreamClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type FlowCombination_RpcPathNestedStreamClient interface { - Recv() (*EmptyProto, error) - grpc.ClientStream -} - -type flowCombinationRpcPathNestedStreamClient struct { - grpc.ClientStream -} - -func (x *flowCombinationRpcPathNestedStreamClient) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// FlowCombinationServer is the server API for FlowCombination service. -type FlowCombinationServer interface { - RpcEmptyRpc(context.Context, *EmptyProto) (*EmptyProto, error) - RpcEmptyStream(*EmptyProto, FlowCombination_RpcEmptyStreamServer) error - StreamEmptyRpc(FlowCombination_StreamEmptyRpcServer) error - StreamEmptyStream(FlowCombination_StreamEmptyStreamServer) error - RpcBodyRpc(context.Context, *NonEmptyProto) (*EmptyProto, error) - RpcPathSingleNestedRpc(context.Context, *SingleNestedProto) (*EmptyProto, error) - RpcPathNestedRpc(context.Context, *NestedProto) (*EmptyProto, error) - RpcBodyStream(*NonEmptyProto, FlowCombination_RpcBodyStreamServer) error - RpcPathSingleNestedStream(*SingleNestedProto, FlowCombination_RpcPathSingleNestedStreamServer) error - RpcPathNestedStream(*NestedProto, FlowCombination_RpcPathNestedStreamServer) error -} - -func RegisterFlowCombinationServer(s *grpc.Server, srv FlowCombinationServer) { - s.RegisterService(&_FlowCombination_serviceDesc, srv) -} - -func _FlowCombination_RpcEmptyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(EmptyProto) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcEmptyRpc", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(FlowCombinationServer).RpcEmptyRpc(ctx, req.(*EmptyProto)) - } - return interceptor(ctx, in, info, handler) -} - -func _FlowCombination_RpcEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(EmptyProto) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(FlowCombinationServer).RpcEmptyStream(m, &flowCombinationRpcEmptyStreamServer{stream}) -} - -type FlowCombination_RpcEmptyStreamServer interface { - Send(*EmptyProto) error - grpc.ServerStream -} - -type flowCombinationRpcEmptyStreamServer struct { - grpc.ServerStream -} - -func (x *flowCombinationRpcEmptyStreamServer) Send(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -func _FlowCombination_StreamEmptyRpc_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(FlowCombinationServer).StreamEmptyRpc(&flowCombinationStreamEmptyRpcServer{stream}) -} - -type FlowCombination_StreamEmptyRpcServer interface { - SendAndClose(*EmptyProto) error - Recv() (*EmptyProto, error) - grpc.ServerStream -} - -type flowCombinationStreamEmptyRpcServer struct { - grpc.ServerStream -} - -func (x *flowCombinationStreamEmptyRpcServer) SendAndClose(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -func (x *flowCombinationStreamEmptyRpcServer) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _FlowCombination_StreamEmptyStream_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(FlowCombinationServer).StreamEmptyStream(&flowCombinationStreamEmptyStreamServer{stream}) -} - -type FlowCombination_StreamEmptyStreamServer interface { - Send(*EmptyProto) error - Recv() (*EmptyProto, error) - grpc.ServerStream -} - -type flowCombinationStreamEmptyStreamServer struct { - grpc.ServerStream -} - -func (x *flowCombinationStreamEmptyStreamServer) Send(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -func (x *flowCombinationStreamEmptyStreamServer) Recv() (*EmptyProto, error) { - m := new(EmptyProto) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _FlowCombination_RpcBodyRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(NonEmptyProto) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(FlowCombinationServer).RpcBodyRpc(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcBodyRpc", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(FlowCombinationServer).RpcBodyRpc(ctx, req.(*NonEmptyProto)) - } - return interceptor(ctx, in, info, handler) -} - -func _FlowCombination_RpcPathSingleNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SingleNestedProto) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathSingleNestedRpc", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(FlowCombinationServer).RpcPathSingleNestedRpc(ctx, req.(*SingleNestedProto)) - } - return interceptor(ctx, in, info, handler) -} - -func _FlowCombination_RpcPathNestedRpc_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(NestedProto) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.FlowCombination/RpcPathNestedRpc", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(FlowCombinationServer).RpcPathNestedRpc(ctx, req.(*NestedProto)) - } - return interceptor(ctx, in, info, handler) -} - -func _FlowCombination_RpcBodyStream_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(NonEmptyProto) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(FlowCombinationServer).RpcBodyStream(m, &flowCombinationRpcBodyStreamServer{stream}) -} - -type FlowCombination_RpcBodyStreamServer interface { - Send(*EmptyProto) error - grpc.ServerStream -} - -type flowCombinationRpcBodyStreamServer struct { - grpc.ServerStream -} - -func (x *flowCombinationRpcBodyStreamServer) Send(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -func _FlowCombination_RpcPathSingleNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(SingleNestedProto) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(FlowCombinationServer).RpcPathSingleNestedStream(m, &flowCombinationRpcPathSingleNestedStreamServer{stream}) -} - -type FlowCombination_RpcPathSingleNestedStreamServer interface { - Send(*EmptyProto) error - grpc.ServerStream -} - -type flowCombinationRpcPathSingleNestedStreamServer struct { - grpc.ServerStream -} - -func (x *flowCombinationRpcPathSingleNestedStreamServer) Send(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -func _FlowCombination_RpcPathNestedStream_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(NestedProto) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(FlowCombinationServer).RpcPathNestedStream(m, &flowCombinationRpcPathNestedStreamServer{stream}) -} - -type FlowCombination_RpcPathNestedStreamServer interface { - Send(*EmptyProto) error - grpc.ServerStream -} - -type flowCombinationRpcPathNestedStreamServer struct { - grpc.ServerStream -} - -func (x *flowCombinationRpcPathNestedStreamServer) Send(m *EmptyProto) error { - return x.ServerStream.SendMsg(m) -} - -var _FlowCombination_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.FlowCombination", - HandlerType: (*FlowCombinationServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "RpcEmptyRpc", - Handler: _FlowCombination_RpcEmptyRpc_Handler, - }, - { - MethodName: "RpcBodyRpc", - Handler: _FlowCombination_RpcBodyRpc_Handler, - }, - { - MethodName: "RpcPathSingleNestedRpc", - Handler: _FlowCombination_RpcPathSingleNestedRpc_Handler, - }, - { - MethodName: "RpcPathNestedRpc", - Handler: _FlowCombination_RpcPathNestedRpc_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "RpcEmptyStream", - Handler: _FlowCombination_RpcEmptyStream_Handler, - ServerStreams: true, - }, - { - StreamName: "StreamEmptyRpc", - Handler: _FlowCombination_StreamEmptyRpc_Handler, - ClientStreams: true, - }, - { - StreamName: "StreamEmptyStream", - Handler: _FlowCombination_StreamEmptyStream_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "RpcBodyStream", - Handler: _FlowCombination_RpcBodyStream_Handler, - ServerStreams: true, - }, - { - StreamName: "RpcPathSingleNestedStream", - Handler: _FlowCombination_RpcPathSingleNestedStream_Handler, - ServerStreams: true, - }, - { - StreamName: "RpcPathNestedStream", - Handler: _FlowCombination_RpcPathNestedStream_Handler, - ServerStreams: true, - }, - }, - Metadata: "examples/proto/examplepb/flow_combination.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/flow_combination.proto", fileDescriptor_flow_combination_40371c0acedc1fc5) -} - -var fileDescriptor_flow_combination_40371c0acedc1fc5 = []byte{ - // 655 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x96, 0xbf, 0x8f, 0x12, 0x41, - 0x14, 0xc7, 0xf3, 0xb8, 0xc4, 0xe4, 0x86, 0xfb, 0xc1, 0x2d, 0x06, 0x81, 0xc3, 0xe3, 0x6e, 0xbc, - 0x44, 0xe2, 0x8f, 0x5d, 0x82, 0xd5, 0x51, 0x9e, 0xd1, 0x92, 0x5c, 0xb8, 0xd8, 0x6c, 0x63, 0x66, - 0x87, 0x15, 0x48, 0x60, 0x67, 0x6e, 0x77, 0x0d, 0x5e, 0x08, 0x31, 0xb1, 0xb1, 0xb4, 0xf0, 0x0f, - 0xb0, 0xb4, 0xf2, 0x1f, 0xb0, 0xb3, 0xb2, 0x31, 0xb1, 0x30, 0xb1, 0xb3, 0xb3, 0xf3, 0x9f, 0x30, - 0xfb, 0xf6, 0xc7, 0xb0, 0x0a, 0x6e, 0x30, 0x62, 0xb7, 0x6f, 0xe6, 0xbd, 0x37, 0x9f, 0xf9, 0xce, - 0xf7, 0x11, 0x88, 0x61, 0x3f, 0x63, 0x63, 0x39, 0xb2, 0x3d, 0x43, 0xba, 0xc2, 0x17, 0x71, 0x28, - 0x2d, 0xe3, 0xc9, 0x48, 0x4c, 0x1e, 0x73, 0x31, 0xb6, 0x86, 0x0e, 0xf3, 0x87, 0xc2, 0xd1, 0x31, - 0x41, 0xab, 0xf7, 0x5d, 0xc9, 0xf5, 0x3e, 0xf3, 0xed, 0x09, 0xbb, 0xd4, 0xe3, 0x6a, 0x3d, 0xa9, - 0xab, 0xd6, 0xfa, 0x42, 0xf4, 0x47, 0xb6, 0xc1, 0xe4, 0xd0, 0x60, 0x8e, 0x23, 0x7c, 0xac, 0xf6, - 0xc2, 0x72, 0xba, 0x45, 0xc8, 0x83, 0xb1, 0xf4, 0x2f, 0xcf, 0x30, 0x3a, 0x21, 0xdb, 0x1d, 0xe1, - 0xa8, 0x05, 0x6d, 0x8b, 0x00, 0x2b, 0xc3, 0x21, 0x34, 0x36, 0xbb, 0xc0, 0x82, 0xc8, 0x2a, 0xe7, - 0xc2, 0xc8, 0x0a, 0x22, 0x5e, 0xde, 0x08, 0x23, 0x4e, 0x0f, 0x08, 0x79, 0xe4, 0x30, 0x37, 0xaa, - 0x2b, 0x90, 0x0d, 0xcf, 0x77, 0xa3, 0xca, 0xe0, 0x93, 0xf6, 0x48, 0xbe, 0x63, 0x7b, 0xbe, 0xdd, - 0x0b, 0x13, 0x4e, 0xe2, 0xc6, 0xf9, 0xd6, 0x6d, 0x3d, 0xe3, 0x0a, 0xba, 0x6a, 0x9c, 0x45, 0xd1, - 0x21, 0x7b, 0xe7, 0x43, 0xa7, 0x3f, 0xb2, 0xff, 0xcd, 0x59, 0xad, 0x4f, 0xbb, 0x64, 0xf7, 0xe1, - 0x48, 0x4c, 0xee, 0x2b, 0xdd, 0xb5, 0xe7, 0x24, 0xdf, 0x95, 0x1c, 0x45, 0xea, 0x4a, 0xae, 0x65, - 0xb7, 0x54, 0x7a, 0x56, 0x57, 0x49, 0xa6, 0xa5, 0x17, 0x5f, 0xbe, 0xbf, 0xce, 0x15, 0xe8, 0x8e, - 0xe1, 0x4a, 0x6e, 0xd8, 0xc1, 0x46, 0xf0, 0xa5, 0xbd, 0x04, 0xb2, 0x13, 0x13, 0x9c, 0xfb, 0xae, - 0xcd, 0xc6, 0x6b, 0x84, 0xa8, 0x20, 0x44, 0x91, 0xee, 0xcd, 0x41, 0x78, 0x78, 0x68, 0x13, 0x90, - 0x24, 0x24, 0xf8, 0x0f, 0x72, 0x28, 0x92, 0xf0, 0x7c, 0xa5, 0x48, 0x03, 0xb4, 0x57, 0x40, 0xf6, - 0xe6, 0x48, 0xd6, 0x2e, 0x4b, 0x0d, 0x61, 0x4a, 0xf4, 0x6a, 0x1a, 0x26, 0x0c, 0x1a, 0xd0, 0x04, - 0xed, 0x5d, 0x8e, 0x90, 0xae, 0xe4, 0xa7, 0xa2, 0x87, 0xba, 0xe8, 0x99, 0xdd, 0x53, 0x93, 0xb7, - 0x1a, 0xcd, 0x07, 0x40, 0x9c, 0xf7, 0x40, 0xb7, 0xf1, 0x99, 0x2c, 0xd1, 0x43, 0x61, 0xda, 0x70, - 0xcb, 0xdc, 0xa7, 0x15, 0x5c, 0x93, 0xcc, 0x1f, 0x18, 0x53, 0x36, 0x33, 0xa6, 0xd6, 0xcc, 0x98, - 0xf2, 0x59, 0xb0, 0x68, 0xc6, 0xe6, 0xba, 0x78, 0x6a, 0xbb, 0x58, 0x61, 0xd6, 0x69, 0x55, 0xb5, - 0x48, 0xd5, 0x60, 0x3f, 0x6e, 0x96, 0x69, 0x51, 0x25, 0x24, 0x75, 0xc1, 0xce, 0x11, 0xad, 0x2d, - 0x28, 0x4d, 0xa5, 0x54, 0xe8, 0xb5, 0x34, 0x4c, 0xb2, 0xab, 0xbd, 0x01, 0x52, 0xea, 0x4a, 0x7e, - 0xc6, 0xfc, 0xc1, 0xfc, 0x08, 0x07, 0xda, 0xb5, 0x32, 0xb5, 0xf8, 0x6d, 0xe8, 0x57, 0xd3, 0xef, - 0x18, 0xe5, 0x3b, 0x88, 0xf8, 0x03, 0xb8, 0xbb, 0x0e, 0xf6, 0x32, 0xa6, 0x4c, 0xf7, 0x7c, 0x17, - 0x2f, 0xaf, 0x7d, 0x03, 0x52, 0x88, 0x08, 0x15, 0xdb, 0x9d, 0xec, 0x77, 0xfd, 0x5b, 0x2a, 0x07, - 0xa9, 0x06, 0xf4, 0x70, 0x29, 0xd5, 0xdc, 0xb3, 0x64, 0xc0, 0x27, 0x8f, 0xb3, 0x64, 0xbf, 0x0d, - 0x5c, 0xfb, 0x98, 0x23, 0xdb, 0x91, 0x63, 0xa3, 0xf9, 0x59, 0xab, 0x69, 0xbf, 0x86, 0xa6, 0xfd, - 0x0c, 0xb4, 0xa0, 0x6c, 0x13, 0x0e, 0x50, 0xe0, 0xdb, 0xf9, 0x0b, 0xa5, 0x7c, 0x1b, 0xa6, 0x98, - 0xf1, 0x4f, 0x52, 0xe8, 0xa0, 0x68, 0x91, 0xd2, 0xeb, 0x4b, 0xdc, 0x1b, 0x37, 0xe6, 0xe6, 0x3e, - 0x2d, 0xfd, 0x6a, 0x60, 0xb5, 0x79, 0x4c, 0xeb, 0x4b, 0x3d, 0xac, 0xb2, 0x6a, 0xd1, 0x90, 0x2c, - 0x4c, 0x68, 0x82, 0xf6, 0x16, 0x48, 0x65, 0x81, 0x97, 0x23, 0x55, 0xd7, 0x6e, 0xe7, 0x9b, 0x28, - 0xec, 0x51, 0x74, 0x95, 0x45, 0x2f, 0x9e, 0x90, 0xfe, 0x00, 0x52, 0x4c, 0x79, 0x3a, 0x62, 0x5c, - 0xa3, 0xad, 0x27, 0x48, 0x77, 0x41, 0x6f, 0xfc, 0xd1, 0xd6, 0x4a, 0xec, 0xec, 0x7b, 0x24, 0xaf, - 0xb6, 0x3c, 0xa5, 0x0d, 0xbc, 0x09, 0xa7, 0x79, 0x73, 0x33, 0x41, 0xb2, 0xae, 0xe0, 0x3f, 0xa0, - 0x7b, 0x3f, 0x03, 0x00, 0x00, 0xff, 0xff, 0x36, 0xcd, 0x7d, 0x1f, 0x73, 0x09, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.gw.go deleted file mode 100755 index 9bc3288..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.pb.gw.go +++ /dev/null @@ -1,1889 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/flow_combination.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -func request_FlowCombination_RpcEmptyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq EmptyProto - var metadata runtime.ServerMetadata - - msg, err := client.RpcEmptyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_FlowCombination_RpcEmptyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcEmptyStreamClient, runtime.ServerMetadata, error) { - var protoReq EmptyProto - var metadata runtime.ServerMetadata - - stream, err := client.RpcEmptyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -func request_FlowCombination_StreamEmptyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var metadata runtime.ServerMetadata - stream, err := client.StreamEmptyRpc(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - for { - var protoReq EmptyProto - err = dec.Decode(&protoReq) - if err == io.EOF { - break - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err = stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return nil, metadata, err - } - } - - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header - - msg, err := stream.CloseAndRecv() - metadata.TrailerMD = stream.Trailer() - return msg, metadata, err - -} - -func request_FlowCombination_StreamEmptyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_StreamEmptyStreamClient, runtime.ServerMetadata, error) { - var metadata runtime.ServerMetadata - stream, err := client.StreamEmptyStream(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - handleSend := func() error { - var protoReq EmptyProto - err := dec.Decode(&protoReq) - if err == io.EOF { - return err - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return err - } - if err := stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return err - } - return nil - } - if err := handleSend(); err != nil { - if cerr := stream.CloseSend(); cerr != nil { - grpclog.Printf("Failed to terminate client stream: %v", cerr) - } - if err == io.EOF { - return stream, metadata, nil - } - return nil, metadata, err - } - go func() { - for { - if err := handleSend(); err != nil { - break - } - } - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - } - }() - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil -} - -func request_FlowCombination_RpcBodyRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_FlowCombination_RpcBodyRpc_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - val, ok = pathParams["c"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "c") - } - - protoReq.C, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "c", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcBodyRpc_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_FlowCombination_RpcBodyRpc_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyRpc_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_FlowCombination_RpcBodyRpc_3(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcBodyRpc_4 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_FlowCombination_RpcBodyRpc_4(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyRpc_4); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcBodyRpc_5 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} -) - -func request_FlowCombination_RpcBodyRpc_5(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyRpc_5); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcBodyRpc_6 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_FlowCombination_RpcBodyRpc_6(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyRpc_6); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcBodyRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcPathSingleNestedRpc_0 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} -) - -func request_FlowCombination_RpcPathSingleNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SingleNestedProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathSingleNestedRpc_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcPathSingleNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcPathNestedRpc_0 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2, "b": 3}, Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 3, 1, 2, 4, 5}} -) - -func request_FlowCombination_RpcPathNestedRpc_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedRpc_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcPathNestedRpc_1 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} -) - -func request_FlowCombination_RpcPathNestedRpc_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedRpc_1); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_FlowCombination_RpcPathNestedRpc_2 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2}, Base: []int{1, 1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 3, 2, 4}} -) - -func request_FlowCombination_RpcPathNestedRpc_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedRpc_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RpcPathNestedRpc(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_FlowCombination_RpcBodyStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -func request_FlowCombination_RpcBodyStream_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - val, ok = pathParams["c"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "c") - } - - protoReq.C, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "c", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcBodyStream_2 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_FlowCombination_RpcBodyStream_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyStream_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -func request_FlowCombination_RpcBodyStream_3(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcBodyStream_4 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_FlowCombination_RpcBodyStream_4(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyStream_4); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcBodyStream_5 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} -) - -func request_FlowCombination_RpcBodyStream_5(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyStream_5); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcBodyStream_6 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_FlowCombination_RpcBodyStream_6(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcBodyStreamClient, runtime.ServerMetadata, error) { - var protoReq NonEmptyProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a") - } - - protoReq.A, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcBodyStream_6); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcBodyStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcPathSingleNestedStream_0 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} -) - -func request_FlowCombination_RpcPathSingleNestedStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathSingleNestedStreamClient, runtime.ServerMetadata, error) { - var protoReq SingleNestedProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathSingleNestedStream_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcPathSingleNestedStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcPathNestedStream_0 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2, "b": 3}, Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, Check: []int{0, 1, 1, 3, 1, 2, 4, 5}} -) - -func request_FlowCombination_RpcPathNestedStream_0(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - val, ok = pathParams["b"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "b") - } - - protoReq.B, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "b", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedStream_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcPathNestedStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcPathNestedStream_1 = &utilities.DoubleArray{Encoding: map[string]int{"a": 0, "str": 1}, Base: []int{1, 1, 1, 0}, Check: []int{0, 1, 2, 3}} -) - -func request_FlowCombination_RpcPathNestedStream_1(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedStream_1); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcPathNestedStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -var ( - filter_FlowCombination_RpcPathNestedStream_2 = &utilities.DoubleArray{Encoding: map[string]int{"c": 0, "a": 1, "str": 2}, Base: []int{1, 1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 3, 2, 4}} -) - -func request_FlowCombination_RpcPathNestedStream_2(ctx context.Context, marshaler runtime.Marshaler, client FlowCombinationClient, req *http.Request, pathParams map[string]string) (FlowCombination_RpcPathNestedStreamClient, runtime.ServerMetadata, error) { - var protoReq NestedProto - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq.C); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["a.str"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "a.str") - } - - err = runtime.PopulateFieldFromPath(&protoReq, "a.str", val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "a.str", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_FlowCombination_RpcPathNestedStream_2); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - stream, err := client.RpcPathNestedStream(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -// RegisterFlowCombinationHandlerFromEndpoint is same as RegisterFlowCombinationHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterFlowCombinationHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterFlowCombinationHandler(ctx, mux, conn) -} - -// RegisterFlowCombinationHandler registers the http handlers for service FlowCombination to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterFlowCombinationHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterFlowCombinationHandlerClient(ctx, mux, NewFlowCombinationClient(conn)) -} - -// RegisterFlowCombinationHandler registers the http handlers for service FlowCombination to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "FlowCombinationClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "FlowCombinationClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "FlowCombinationClient" to call the correct interceptors. -func RegisterFlowCombinationHandlerClient(ctx context.Context, mux *runtime.ServeMux, client FlowCombinationClient) error { - - mux.Handle("POST", pattern_FlowCombination_RpcEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcEmptyRpc_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcEmptyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcEmptyStream_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcEmptyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_StreamEmptyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_StreamEmptyRpc_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_StreamEmptyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_StreamEmptyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_StreamEmptyStream_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_StreamEmptyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_3(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_3(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_4(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_4(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_5(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_5(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyRpc_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyRpc_6(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyRpc_6(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathSingleNestedRpc_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathSingleNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedRpc_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedRpc_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedRpc_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedRpc_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedRpc_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedRpc_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedRpc_2(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_1(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_2(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_3, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_3(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_3(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_4, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_4(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_4(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_5, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_5(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_5(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcBodyStream_6, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcBodyStream_6(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcBodyStream_6(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathSingleNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathSingleNestedStream_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathSingleNestedStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedStream_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedStream_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedStream_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedStream_1(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_FlowCombination_RpcPathNestedStream_2, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_FlowCombination_RpcPathNestedStream_2(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_FlowCombination_RpcPathNestedStream_2(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_FlowCombination_RpcEmptyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "empty"}, "")) - - pattern_FlowCombination_RpcEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "empty", "stream"}, "")) - - pattern_FlowCombination_StreamEmptyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"stream", "empty", "rpc"}, "")) - - pattern_FlowCombination_StreamEmptyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"stream", "empty"}, "")) - - pattern_FlowCombination_RpcBodyRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "body"}, "")) - - pattern_FlowCombination_RpcBodyRpc_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 0}, []string{"rpc", "path", "a", "b", "c"}, "")) - - pattern_FlowCombination_RpcBodyRpc_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 0}, []string{"rpc", "query"}, "")) - - pattern_FlowCombination_RpcBodyRpc_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 0}, []string{"rpc", "body", "path", "a", "b"}, "")) - - pattern_FlowCombination_RpcBodyRpc_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 0}, []string{"rpc", "body", "query"}, "")) - - pattern_FlowCombination_RpcBodyRpc_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 2, 0}, []string{"rpc", "body", "path", "a", "query"}, "")) - - pattern_FlowCombination_RpcBodyRpc_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 0}, []string{"rpc", "path", "a", "query"}, "")) - - pattern_FlowCombination_RpcPathSingleNestedRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "")) - - pattern_FlowCombination_RpcPathNestedRpc_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 2, 0}, []string{"rpc", "path-nested", "a.str", "b"}, "")) - - pattern_FlowCombination_RpcPathNestedRpc_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "")) - - pattern_FlowCombination_RpcPathNestedRpc_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 0}, []string{"rpc", "path-nested", "a.str"}, "")) - - pattern_FlowCombination_RpcBodyStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "body", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"rpc", "path", "a", "b", "c", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"rpc", "query", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_3 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"rpc", "body", "path", "a", "b", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_4 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"rpc", "body", "query", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_5 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 2, 5}, []string{"rpc", "body", "path", "a", "query", "stream"}, "")) - - pattern_FlowCombination_RpcBodyStream_6 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3, 2, 4}, []string{"rpc", "path", "a", "query", "stream"}, "")) - - pattern_FlowCombination_RpcPathSingleNestedStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "")) - - pattern_FlowCombination_RpcPathNestedStream_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"rpc", "path-nested", "a.str", "b", "stream"}, "")) - - pattern_FlowCombination_RpcPathNestedStream_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "")) - - pattern_FlowCombination_RpcPathNestedStream_2 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"rpc", "path-nested", "a.str", "stream"}, "")) -) - -var ( - forward_FlowCombination_RpcEmptyRpc_0 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcEmptyStream_0 = runtime.ForwardResponseStream - - forward_FlowCombination_StreamEmptyRpc_0 = runtime.ForwardResponseMessage - - forward_FlowCombination_StreamEmptyStream_0 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyRpc_0 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_1 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_2 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_3 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_4 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_5 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyRpc_6 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcPathSingleNestedRpc_0 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcPathNestedRpc_0 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcPathNestedRpc_1 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcPathNestedRpc_2 = runtime.ForwardResponseMessage - - forward_FlowCombination_RpcBodyStream_0 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_1 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_2 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_3 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_4 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_5 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcBodyStream_6 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcPathSingleNestedStream_0 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcPathNestedStream_0 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcPathNestedStream_1 = runtime.ForwardResponseStream - - forward_FlowCombination_RpcPathNestedStream_2 = runtime.ForwardResponseStream -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.proto deleted file mode 100755 index 6009608..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/flow_combination.proto +++ /dev/null @@ -1,168 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; -package grpc.gateway.examples.examplepb; - -import "google/api/annotations.proto"; - -message EmptyProto {} - -message NonEmptyProto { - string a = 1; - string b = 2; - string c = 3; -} - -message UnaryProto { - string str = 1; -} - -message NestedProto { - UnaryProto a = 1; - string b = 2; - string c = 3; -} - -message SingleNestedProto { - UnaryProto a = 1; -} - -service FlowCombination { - rpc RpcEmptyRpc(EmptyProto) returns (EmptyProto) { - option (google.api.http) = { - post: "/rpc/empty/rpc" - }; - } - rpc RpcEmptyStream(EmptyProto) returns (stream EmptyProto) { - option (google.api.http) = { - post: "/rpc/empty/stream" - }; - } - rpc StreamEmptyRpc(stream EmptyProto) returns (EmptyProto) { - option (google.api.http) = { - post: "/stream/empty/rpc" - }; - } - rpc StreamEmptyStream(stream EmptyProto) returns (stream EmptyProto) { - option (google.api.http) = { - post: "/stream/empty/stream" - }; - } - - rpc RpcBodyRpc(NonEmptyProto) returns (EmptyProto) { - option (google.api.http) = { - // w/ body; w/o path; w/o query - post: "/rpc/body/rpc" - body: "*" - - // w/o body; w/ path; w/o query - additional_bindings { - post: "/rpc/path/{a}/{b}/{c}/rpc" - } - // w/o body; w/o path; w/ query - additional_bindings { - post: "/rpc/query/rpc" - } - // w/ body; w/ path; w/o query - additional_bindings { - post: "/rpc/body/path/{a}/{b}/rpc" - body: "c" - } - // w/ body; w/o path; w/ query - additional_bindings { - post: "/rpc/body/query/rpc" - body: "c" - } - // w/ body; w/ path; w/ query - additional_bindings { - post: "/rpc/body/path/{a}/query/rpc" - body: "c" - } - // w/o body; w/ path; w/ query - additional_bindings { - post: "/rpc/path/{a}/query/rpc" - } - }; - } - rpc RpcPathSingleNestedRpc(SingleNestedProto) returns (EmptyProto) { - option (google.api.http) = { - // w/o body; w/ path (IsNestedProto3); w/o query - post: "/rpc/path-nested/{a.str}/rpc" - }; - } - rpc RpcPathNestedRpc(NestedProto) returns (EmptyProto) { - option (google.api.http) = { - // w/ body; w/ path (IsNestedProto3); w/o query - post: "/rpc/path-nested/{a.str}/{b}/rpc" - body: "c" - - // w/o body; w/ path (IsNestedProto3); w/ query - additional_bindings { - post: "/rpc/path-nested/{a.str}/rpc" - } - // w/ body; w/ path (IsNestedProto3); w/ query - additional_bindings { - post: "/rpc/path-nested/{a.str}/rpc" - body: "c" - } - }; - } - - rpc RpcBodyStream(NonEmptyProto) returns (stream EmptyProto) { - option (google.api.http) = { - // w/ body; w/o path; w/o query - post: "/rpc/body/stream" - body: "*" - - // w/o body; w/ path; w/o query - additional_bindings { - post: "/rpc/path/{a}/{b}/{c}/stream" - } - // w/o body; w/o path; w/ query - additional_bindings { - post: "/rpc/query/stream" - } - // w/ body; w/ path; w/o query - additional_bindings { - post: "/rpc/body/path/{a}/{b}/stream" - body: "c" - } - // w/ body; w/o path; w/ query - additional_bindings { - post: "/rpc/body/query/stream" - body: "c" - } - // w/ body; w/ path; w/ query - additional_bindings { - post: "/rpc/body/path/{a}/query/stream" - body: "c" - } - // w/o body; w/ path; w/ query - additional_bindings { - post: "/rpc/path/{a}/query/stream" - } - }; - } - rpc RpcPathSingleNestedStream(SingleNestedProto) returns (stream EmptyProto) { - option (google.api.http) = { - // w/o body; w/ path (IsNestedProto3); w/o query - post: "/rpc/path-nested/{a.str}/stream" - }; - } - rpc RpcPathNestedStream(NestedProto) returns (stream EmptyProto) { - option (google.api.http) = { - // w/ body; w/ path (IsNestedProto3); w/o query - post: "/rpc/path-nested/{a.str}/{b}/stream" - body: "c" - - // w/o body; w/ path (IsNestedProto3); w/ query - additional_bindings { - post: "/rpc/path-nested/{a.str}/stream" - } - // w/ body; w/ path (IsNestedProto3); w/ query - additional_bindings { - post: "/rpc/path-nested/{a.str}/stream" - body: "c" - } - }; - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.go deleted file mode 100755 index cc0c274..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.go +++ /dev/null @@ -1,286 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/stream.proto - -package examplepb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import empty "github.com/golang/protobuf/ptypes/empty" -import sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// StreamServiceClient is the client API for StreamService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type StreamServiceClient interface { - BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error) - List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error) - BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error) -} - -type streamServiceClient struct { - cc *grpc.ClientConn -} - -func NewStreamServiceClient(cc *grpc.ClientConn) StreamServiceClient { - return &streamServiceClient{cc} -} - -func (c *streamServiceClient) BulkCreate(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkCreateClient, error) { - stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[0], "/grpc.gateway.examples.examplepb.StreamService/BulkCreate", opts...) - if err != nil { - return nil, err - } - x := &streamServiceBulkCreateClient{stream} - return x, nil -} - -type StreamService_BulkCreateClient interface { - Send(*ABitOfEverything) error - CloseAndRecv() (*empty.Empty, error) - grpc.ClientStream -} - -type streamServiceBulkCreateClient struct { - grpc.ClientStream -} - -func (x *streamServiceBulkCreateClient) Send(m *ABitOfEverything) error { - return x.ClientStream.SendMsg(m) -} - -func (x *streamServiceBulkCreateClient) CloseAndRecv() (*empty.Empty, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(empty.Empty) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *streamServiceClient) List(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (StreamService_ListClient, error) { - stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[1], "/grpc.gateway.examples.examplepb.StreamService/List", opts...) - if err != nil { - return nil, err - } - x := &streamServiceListClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type StreamService_ListClient interface { - Recv() (*ABitOfEverything, error) - grpc.ClientStream -} - -type streamServiceListClient struct { - grpc.ClientStream -} - -func (x *streamServiceListClient) Recv() (*ABitOfEverything, error) { - m := new(ABitOfEverything) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *streamServiceClient) BulkEcho(ctx context.Context, opts ...grpc.CallOption) (StreamService_BulkEchoClient, error) { - stream, err := c.cc.NewStream(ctx, &_StreamService_serviceDesc.Streams[2], "/grpc.gateway.examples.examplepb.StreamService/BulkEcho", opts...) - if err != nil { - return nil, err - } - x := &streamServiceBulkEchoClient{stream} - return x, nil -} - -type StreamService_BulkEchoClient interface { - Send(*sub.StringMessage) error - Recv() (*sub.StringMessage, error) - grpc.ClientStream -} - -type streamServiceBulkEchoClient struct { - grpc.ClientStream -} - -func (x *streamServiceBulkEchoClient) Send(m *sub.StringMessage) error { - return x.ClientStream.SendMsg(m) -} - -func (x *streamServiceBulkEchoClient) Recv() (*sub.StringMessage, error) { - m := new(sub.StringMessage) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// StreamServiceServer is the server API for StreamService service. -type StreamServiceServer interface { - BulkCreate(StreamService_BulkCreateServer) error - List(*empty.Empty, StreamService_ListServer) error - BulkEcho(StreamService_BulkEchoServer) error -} - -func RegisterStreamServiceServer(s *grpc.Server, srv StreamServiceServer) { - s.RegisterService(&_StreamService_serviceDesc, srv) -} - -func _StreamService_BulkCreate_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(StreamServiceServer).BulkCreate(&streamServiceBulkCreateServer{stream}) -} - -type StreamService_BulkCreateServer interface { - SendAndClose(*empty.Empty) error - Recv() (*ABitOfEverything, error) - grpc.ServerStream -} - -type streamServiceBulkCreateServer struct { - grpc.ServerStream -} - -func (x *streamServiceBulkCreateServer) SendAndClose(m *empty.Empty) error { - return x.ServerStream.SendMsg(m) -} - -func (x *streamServiceBulkCreateServer) Recv() (*ABitOfEverything, error) { - m := new(ABitOfEverything) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _StreamService_List_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(empty.Empty) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(StreamServiceServer).List(m, &streamServiceListServer{stream}) -} - -type StreamService_ListServer interface { - Send(*ABitOfEverything) error - grpc.ServerStream -} - -type streamServiceListServer struct { - grpc.ServerStream -} - -func (x *streamServiceListServer) Send(m *ABitOfEverything) error { - return x.ServerStream.SendMsg(m) -} - -func _StreamService_BulkEcho_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(StreamServiceServer).BulkEcho(&streamServiceBulkEchoServer{stream}) -} - -type StreamService_BulkEchoServer interface { - Send(*sub.StringMessage) error - Recv() (*sub.StringMessage, error) - grpc.ServerStream -} - -type streamServiceBulkEchoServer struct { - grpc.ServerStream -} - -func (x *streamServiceBulkEchoServer) Send(m *sub.StringMessage) error { - return x.ServerStream.SendMsg(m) -} - -func (x *streamServiceBulkEchoServer) Recv() (*sub.StringMessage, error) { - m := new(sub.StringMessage) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _StreamService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.StreamService", - HandlerType: (*StreamServiceServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "BulkCreate", - Handler: _StreamService_BulkCreate_Handler, - ClientStreams: true, - }, - { - StreamName: "List", - Handler: _StreamService_List_Handler, - ServerStreams: true, - }, - { - StreamName: "BulkEcho", - Handler: _StreamService_BulkEcho_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "examples/proto/examplepb/stream.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/stream.proto", fileDescriptor_stream_0929397c5d8d3331) -} - -var fileDescriptor_stream_0929397c5d8d3331 = []byte{ - // 319 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x90, 0xb1, 0x4e, 0xc3, 0x30, - 0x10, 0x86, 0x15, 0x40, 0x08, 0x8c, 0x58, 0x3c, 0x30, 0x04, 0xa4, 0x42, 0x05, 0xa2, 0x30, 0xd8, - 0x6d, 0xd9, 0xd8, 0x28, 0xea, 0x06, 0x62, 0xe8, 0xc6, 0x52, 0xd9, 0xd1, 0xd5, 0xb5, 0x9a, 0xc4, - 0x96, 0x7d, 0x29, 0x54, 0x62, 0x62, 0x64, 0xed, 0x8b, 0xf0, 0x2e, 0xbc, 0x02, 0x0f, 0x82, 0xea, - 0xa4, 0x1d, 0x10, 0x51, 0xcb, 0x78, 0xbe, 0xff, 0xf7, 0xfd, 0xdf, 0x4f, 0x2e, 0xe0, 0x55, 0x64, - 0x36, 0x05, 0xcf, 0xad, 0x33, 0x68, 0x78, 0x35, 0x5a, 0xc9, 0x3d, 0x3a, 0x10, 0x19, 0x0b, 0xcf, - 0xb4, 0xa1, 0x9c, 0x4d, 0x98, 0x12, 0x08, 0x2f, 0x62, 0xc6, 0x96, 0x1e, 0xb6, 0x52, 0xc7, 0x27, - 0xca, 0x18, 0x95, 0x02, 0x17, 0x56, 0x73, 0x91, 0xe7, 0x06, 0x05, 0x6a, 0x93, 0xfb, 0xd2, 0x1e, - 0x1f, 0x57, 0xdb, 0x30, 0xc9, 0x62, 0xc4, 0x21, 0xb3, 0x38, 0xab, 0x96, 0xdd, 0xda, 0x08, 0x62, - 0x28, 0x35, 0x0e, 0xcd, 0x68, 0x08, 0x53, 0x70, 0x33, 0x1c, 0xeb, 0x5c, 0x55, 0x9e, 0xd3, 0x5f, - 0x1e, 0x5f, 0x48, 0x9e, 0x81, 0xf7, 0x42, 0x41, 0xa9, 0xe8, 0x7e, 0x6e, 0x93, 0xc3, 0x41, 0x40, - 0x18, 0x80, 0x9b, 0xea, 0x04, 0xe8, 0x47, 0x44, 0x48, 0xaf, 0x48, 0x27, 0xf7, 0x0e, 0x04, 0x02, - 0xed, 0xb0, 0x35, 0x4c, 0xec, 0xae, 0xa7, 0xf1, 0x69, 0xd4, 0x5f, 0xdd, 0x8e, 0x8f, 0x58, 0xc9, - 0xc1, 0x96, 0x1c, 0xac, 0xbf, 0xe0, 0x68, 0xf2, 0xf7, 0xaf, 0xef, 0xf9, 0xd6, 0x55, 0xf3, 0x9c, - 0x4f, 0x3b, 0xcb, 0xf8, 0x7f, 0x85, 0xe7, 0xb2, 0x48, 0x27, 0xb7, 0xd1, 0x75, 0x2b, 0xa2, 0x6f, - 0x64, 0xe7, 0x41, 0x7b, 0xa4, 0x35, 0x5f, 0xc6, 0xff, 0x4f, 0xd7, 0xbc, 0x0c, 0x29, 0xce, 0x68, - 0x63, 0x4d, 0x8a, 0x76, 0x44, 0xe7, 0x11, 0xd9, 0x5b, 0x54, 0xd1, 0x4f, 0xc6, 0x86, 0xb6, 0x6a, - 0x4e, 0xf9, 0x42, 0xb2, 0x01, 0x3a, 0x9d, 0xab, 0xc7, 0xb2, 0xd9, 0x78, 0x63, 0xe5, 0xe6, 0x8d, - 0x40, 0x32, 0x36, 0xa1, 0x91, 0x76, 0xd4, 0x3b, 0x78, 0xde, 0x5f, 0xe1, 0xc9, 0xdd, 0x50, 0xc8, - 0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1d, 0x63, 0x7a, 0xd9, 0xa1, 0x02, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.gw.go deleted file mode 100755 index 642d59a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.pb.gw.go +++ /dev/null @@ -1,285 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/stream.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -func request_StreamService_BulkCreate_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var metadata runtime.ServerMetadata - stream, err := client.BulkCreate(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - for { - var protoReq ABitOfEverything - err = dec.Decode(&protoReq) - if err == io.EOF { - break - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err = stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return nil, metadata, err - } - } - - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header - - msg, err := stream.CloseAndRecv() - metadata.TrailerMD = stream.Trailer() - return msg, metadata, err - -} - -func request_StreamService_List_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_ListClient, runtime.ServerMetadata, error) { - var protoReq empty.Empty - var metadata runtime.ServerMetadata - - stream, err := client.List(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil - -} - -func request_StreamService_BulkEcho_0(ctx context.Context, marshaler runtime.Marshaler, client StreamServiceClient, req *http.Request, pathParams map[string]string) (StreamService_BulkEchoClient, runtime.ServerMetadata, error) { - var metadata runtime.ServerMetadata - stream, err := client.BulkEcho(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - handleSend := func() error { - var protoReq sub.StringMessage - err := dec.Decode(&protoReq) - if err == io.EOF { - return err - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return err - } - if err := stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return err - } - return nil - } - if err := handleSend(); err != nil { - if cerr := stream.CloseSend(); cerr != nil { - grpclog.Printf("Failed to terminate client stream: %v", cerr) - } - if err == io.EOF { - return stream, metadata, nil - } - return nil, metadata, err - } - go func() { - for { - if err := handleSend(); err != nil { - break - } - } - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - } - }() - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil -} - -// RegisterStreamServiceHandlerFromEndpoint is same as RegisterStreamServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterStreamServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterStreamServiceHandler(ctx, mux, conn) -} - -// RegisterStreamServiceHandler registers the http handlers for service StreamService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterStreamServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterStreamServiceHandlerClient(ctx, mux, NewStreamServiceClient(conn)) -} - -// RegisterStreamServiceHandler registers the http handlers for service StreamService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "StreamServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "StreamServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "StreamServiceClient" to call the correct interceptors. -func RegisterStreamServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client StreamServiceClient) error { - - mux.Handle("POST", pattern_StreamService_BulkCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_StreamService_BulkCreate_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_StreamService_BulkCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_StreamService_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_StreamService_List_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_StreamService_List_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_StreamService_BulkEcho_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_StreamService_BulkEcho_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_StreamService_BulkEcho_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_StreamService_BulkCreate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "bulk"}, "")) - - pattern_StreamService_List_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "a_bit_of_everything"}, "")) - - pattern_StreamService_BulkEcho_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "example", "a_bit_of_everything", "echo"}, "")) -) - -var ( - forward_StreamService_BulkCreate_0 = runtime.ForwardResponseMessage - - forward_StreamService_List_0 = runtime.ForwardResponseStream - - forward_StreamService_BulkEcho_0 = runtime.ForwardResponseStream -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.proto deleted file mode 100755 index 66e59dd..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/stream.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; -package grpc.gateway.examples.examplepb; - -import "google/api/annotations.proto"; -import "google/protobuf/empty.proto"; -import "examples/proto/examplepb/a_bit_of_everything.proto"; -import "examples/proto/sub/message.proto"; - -// Defines some more operations to be added to ABitOfEverythingService -service StreamService { - rpc BulkCreate(stream ABitOfEverything) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1/example/a_bit_of_everything/bulk" - body: "*" - }; - } - rpc List(google.protobuf.Empty) returns (stream ABitOfEverything) { - option (google.api.http) = { - get: "/v1/example/a_bit_of_everything" - }; - } - rpc BulkEcho(stream grpc.gateway.examples.sub.StringMessage) returns (stream grpc.gateway.examples.sub.StringMessage) { - option (google.api.http) = { - post: "/v1/example/a_bit_of_everything/echo" - body: "*" - }; - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.go deleted file mode 100755 index 733ab6e..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.go +++ /dev/null @@ -1,270 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/unannotated_echo_service.proto - -package examplepb - -/* -Unannotated Echo Service -Similar to echo_service.proto but without annotations. See -unannotated_echo_service.yaml for the equivalent of the annotations in -gRPC API configuration format. - -Echo Service API consists of a single service which returns -a message. -*/ - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. -type UnannotatedSimpleMessage struct { - // Id represents the message identifier. - Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` - Num int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` - Duration *duration.Duration `protobuf:"bytes,3,opt,name=duration" json:"duration,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UnannotatedSimpleMessage) Reset() { *m = UnannotatedSimpleMessage{} } -func (m *UnannotatedSimpleMessage) String() string { return proto.CompactTextString(m) } -func (*UnannotatedSimpleMessage) ProtoMessage() {} -func (*UnannotatedSimpleMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_unannotated_echo_service_33987b03bf51a339, []int{0} -} -func (m *UnannotatedSimpleMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UnannotatedSimpleMessage.Unmarshal(m, b) -} -func (m *UnannotatedSimpleMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UnannotatedSimpleMessage.Marshal(b, m, deterministic) -} -func (dst *UnannotatedSimpleMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_UnannotatedSimpleMessage.Merge(dst, src) -} -func (m *UnannotatedSimpleMessage) XXX_Size() int { - return xxx_messageInfo_UnannotatedSimpleMessage.Size(m) -} -func (m *UnannotatedSimpleMessage) XXX_DiscardUnknown() { - xxx_messageInfo_UnannotatedSimpleMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_UnannotatedSimpleMessage proto.InternalMessageInfo - -func (m *UnannotatedSimpleMessage) GetId() string { - if m != nil { - return m.Id - } - return "" -} - -func (m *UnannotatedSimpleMessage) GetNum() int64 { - if m != nil { - return m.Num - } - return 0 -} - -func (m *UnannotatedSimpleMessage) GetDuration() *duration.Duration { - if m != nil { - return m.Duration - } - return nil -} - -func init() { - proto.RegisterType((*UnannotatedSimpleMessage)(nil), "grpc.gateway.examples.examplepb.UnannotatedSimpleMessage") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// UnannotatedEchoServiceClient is the client API for UnannotatedEchoService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type UnannotatedEchoServiceClient interface { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - Echo(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) - // EchoBody method receives a simple message and returns it. - EchoBody(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) - // EchoDelete method receives a simple message and returns it. - EchoDelete(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) -} - -type unannotatedEchoServiceClient struct { - cc *grpc.ClientConn -} - -func NewUnannotatedEchoServiceClient(cc *grpc.ClientConn) UnannotatedEchoServiceClient { - return &unannotatedEchoServiceClient{cc} -} - -func (c *unannotatedEchoServiceClient) Echo(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { - out := new(UnannotatedSimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.UnannotatedEchoService/Echo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *unannotatedEchoServiceClient) EchoBody(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { - out := new(UnannotatedSimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.UnannotatedEchoService/EchoBody", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *unannotatedEchoServiceClient) EchoDelete(ctx context.Context, in *UnannotatedSimpleMessage, opts ...grpc.CallOption) (*UnannotatedSimpleMessage, error) { - out := new(UnannotatedSimpleMessage) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.UnannotatedEchoService/EchoDelete", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// UnannotatedEchoServiceServer is the server API for UnannotatedEchoService service. -type UnannotatedEchoServiceServer interface { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - Echo(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) - // EchoBody method receives a simple message and returns it. - EchoBody(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) - // EchoDelete method receives a simple message and returns it. - EchoDelete(context.Context, *UnannotatedSimpleMessage) (*UnannotatedSimpleMessage, error) -} - -func RegisterUnannotatedEchoServiceServer(s *grpc.Server, srv UnannotatedEchoServiceServer) { - s.RegisterService(&_UnannotatedEchoService_serviceDesc, srv) -} - -func _UnannotatedEchoService_Echo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UnannotatedSimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(UnannotatedEchoServiceServer).Echo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.UnannotatedEchoService/Echo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(UnannotatedEchoServiceServer).Echo(ctx, req.(*UnannotatedSimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _UnannotatedEchoService_EchoBody_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UnannotatedSimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(UnannotatedEchoServiceServer).EchoBody(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.UnannotatedEchoService/EchoBody", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(UnannotatedEchoServiceServer).EchoBody(ctx, req.(*UnannotatedSimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -func _UnannotatedEchoService_EchoDelete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UnannotatedSimpleMessage) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(UnannotatedEchoServiceServer).EchoDelete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.UnannotatedEchoService/EchoDelete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(UnannotatedEchoServiceServer).EchoDelete(ctx, req.(*UnannotatedSimpleMessage)) - } - return interceptor(ctx, in, info, handler) -} - -var _UnannotatedEchoService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.UnannotatedEchoService", - HandlerType: (*UnannotatedEchoServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Echo", - Handler: _UnannotatedEchoService_Echo_Handler, - }, - { - MethodName: "EchoBody", - Handler: _UnannotatedEchoService_EchoBody_Handler, - }, - { - MethodName: "EchoDelete", - Handler: _UnannotatedEchoService_EchoDelete_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/unannotated_echo_service.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/unannotated_echo_service.proto", fileDescriptor_unannotated_echo_service_33987b03bf51a339) -} - -var fileDescriptor_unannotated_echo_service_33987b03bf51a339 = []byte{ - // 268 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xad, 0x48, 0xcc, - 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x87, 0x72, 0x0b, 0x92, 0xf4, - 0x4b, 0xf3, 0x12, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x52, 0x53, 0xe2, 0x53, 0x93, 0x33, 0xf2, - 0xe3, 0x8b, 0x53, 0x8b, 0xca, 0x32, 0x93, 0x53, 0xf5, 0xc0, 0x0a, 0x85, 0xe4, 0xd3, 0x8b, 0x0a, - 0x92, 0xf5, 0xd2, 0x13, 0x4b, 0x52, 0xcb, 0x13, 0x2b, 0xf5, 0x60, 0xa6, 0xe8, 0xc1, 0xf5, 0x4b, - 0xc9, 0xa5, 0xe7, 0xe7, 0xa7, 0xe7, 0xa4, 0x42, 0xcc, 0x4d, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, - 0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0x83, 0x18, 0xa0, 0x54, 0xcc, 0x25, 0x11, 0x8a, 0xb0, 0x22, 0x38, - 0x13, 0xa4, 0xcd, 0x37, 0xb5, 0xb8, 0x38, 0x31, 0x3d, 0x55, 0x88, 0x8f, 0x8b, 0x29, 0x33, 0x45, - 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x88, 0x29, 0x33, 0x45, 0x48, 0x80, 0x8b, 0x39, 0xaf, 0x34, - 0x57, 0x82, 0x49, 0x81, 0x51, 0x83, 0x39, 0x08, 0xc4, 0x14, 0x32, 0xe5, 0xe2, 0x80, 0x99, 0x27, - 0xc1, 0xac, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa9, 0x07, 0xb1, 0x50, 0x0f, 0x66, 0xa1, 0x9e, 0x0b, - 0x54, 0x41, 0x10, 0x5c, 0xa9, 0xd1, 0x3c, 0x66, 0x2e, 0x31, 0x24, 0x5b, 0x5d, 0x93, 0x33, 0xf2, - 0x83, 0x21, 0xde, 0x12, 0xaa, 0xe1, 0x62, 0x01, 0x71, 0x85, 0x2c, 0xf5, 0x08, 0xf8, 0x4c, 0x0f, - 0x97, 0xb3, 0xa5, 0xc8, 0xd7, 0x2a, 0xd4, 0xc0, 0xc8, 0xc5, 0x01, 0xb2, 0xde, 0x29, 0x3f, 0xa5, - 0x72, 0x80, 0x9c, 0xd0, 0xc4, 0xc8, 0xc5, 0x05, 0x72, 0x82, 0x4b, 0x6a, 0x4e, 0x6a, 0x49, 0xea, - 0xc0, 0x38, 0xc2, 0x89, 0x3b, 0x8a, 0x13, 0xae, 0x2a, 0x89, 0x0d, 0x1c, 0x95, 0xc6, 0x80, 0x00, - 0x00, 0x00, 0xff, 0xff, 0x9a, 0xa7, 0x7c, 0x41, 0xa5, 0x02, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.gw.go deleted file mode 100755 index 65007db..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.pb.gw.go +++ /dev/null @@ -1,317 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/unannotated_echo_service.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -var ( - filter_UnannotatedEchoService_Echo_0 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) - -func request_UnannotatedEchoService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq UnannotatedSimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_UnannotatedEchoService_Echo_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_UnannotatedEchoService_Echo_1 = &utilities.DoubleArray{Encoding: map[string]int{"id": 0, "num": 1}, Base: []int{1, 1, 2, 0, 0}, Check: []int{0, 1, 1, 2, 3}} -) - -func request_UnannotatedEchoService_Echo_1(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq UnannotatedSimpleMessage - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - val, ok = pathParams["num"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "num") - } - - protoReq.Num, err = runtime.Int64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "num", err) - } - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_UnannotatedEchoService_Echo_1); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Echo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func request_UnannotatedEchoService_EchoBody_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq UnannotatedSimpleMessage - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EchoBody(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -var ( - filter_UnannotatedEchoService_EchoDelete_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_UnannotatedEchoService_EchoDelete_0(ctx context.Context, marshaler runtime.Marshaler, client UnannotatedEchoServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq UnannotatedSimpleMessage - var metadata runtime.ServerMetadata - - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_UnannotatedEchoService_EchoDelete_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.EchoDelete(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterUnannotatedEchoServiceHandlerFromEndpoint is same as RegisterUnannotatedEchoServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterUnannotatedEchoServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterUnannotatedEchoServiceHandler(ctx, mux, conn) -} - -// RegisterUnannotatedEchoServiceHandler registers the http handlers for service UnannotatedEchoService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterUnannotatedEchoServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterUnannotatedEchoServiceHandlerClient(ctx, mux, NewUnannotatedEchoServiceClient(conn)) -} - -// RegisterUnannotatedEchoServiceHandler registers the http handlers for service UnannotatedEchoService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "UnannotatedEchoServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "UnannotatedEchoServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "UnannotatedEchoServiceClient" to call the correct interceptors. -func RegisterUnannotatedEchoServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client UnannotatedEchoServiceClient) error { - - mux.Handle("POST", pattern_UnannotatedEchoService_Echo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_UnannotatedEchoService_Echo_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_UnannotatedEchoService_Echo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("GET", pattern_UnannotatedEchoService_Echo_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_UnannotatedEchoService_Echo_1(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_UnannotatedEchoService_Echo_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_UnannotatedEchoService_EchoBody_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_UnannotatedEchoService_EchoBody_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_UnannotatedEchoService_EchoBody_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("DELETE", pattern_UnannotatedEchoService_EchoDelete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_UnannotatedEchoService_EchoDelete_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_UnannotatedEchoService_EchoDelete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_UnannotatedEchoService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1", "example", "echo", "id"}, "")) - - pattern_UnannotatedEchoService_Echo_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "example", "echo", "id", "num"}, "")) - - pattern_UnannotatedEchoService_EchoBody_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_body"}, "")) - - pattern_UnannotatedEchoService_EchoDelete_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "echo_delete"}, "")) -) - -var ( - forward_UnannotatedEchoService_Echo_0 = runtime.ForwardResponseMessage - - forward_UnannotatedEchoService_Echo_1 = runtime.ForwardResponseMessage - - forward_UnannotatedEchoService_EchoBody_0 = runtime.ForwardResponseMessage - - forward_UnannotatedEchoService_EchoDelete_0 = runtime.ForwardResponseMessage -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.proto deleted file mode 100755 index 9187f78..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.proto +++ /dev/null @@ -1,37 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; - -// Unannotated Echo Service -// Similar to echo_service.proto but without annotations. See -// unannotated_echo_service.yaml for the equivalent of the annotations in -// gRPC API configuration format. -// -// Echo Service API consists of a single service which returns -// a message. -package grpc.gateway.examples.examplepb; - -// Do not need annotations.proto, can still use well known types as usual -import "google/protobuf/duration.proto"; - -// UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service. -message UnannotatedSimpleMessage { - // Id represents the message identifier. - string id = 1; - int64 num = 2; - google.protobuf.Duration duration = 3; -} - -// Echo service responds to incoming echo requests. -service UnannotatedEchoService { - // Echo method receives a simple message and returns it. - // - // The message posted as the id parameter will also be - // returned. - rpc Echo(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); - - // EchoBody method receives a simple message and returns it. - rpc EchoBody(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); - - // EchoDelete method receives a simple message and returns it. - rpc EchoDelete(UnannotatedSimpleMessage) returns (UnannotatedSimpleMessage); -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.swagger.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.swagger.json deleted file mode 100755 index 9bfa9f2..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.swagger.json +++ /dev/null @@ -1,170 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "examples/proto/examplepb/unannotated_echo_service.proto", - "description": "Unannotated Echo Service\nSimilar to echo_service.proto but without annotations. See\nunannotated_echo_service.yaml for the equivalent of the annotations in\ngRPC API configuration format.\n\nEcho Service API consists of a single service which returns\na message.", - "version": "version not set" - }, - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/v1/example/echo/{id}": { - "post": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - } - ], - "tags": [ - "UnannotatedEchoService" - ] - } - }, - "/v1/example/echo/{id}/{num}": { - "get": { - "summary": "Echo method receives a simple message and returns it.", - "description": "The message posted as the id parameter will also be\nreturned.", - "operationId": "Echo2", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "type": "string" - }, - { - "name": "num", - "in": "path", - "required": true, - "type": "string", - "format": "int64" - }, - { - "name": "duration", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "UnannotatedEchoService" - ] - } - }, - "/v1/example/echo_body": { - "post": { - "summary": "EchoBody method receives a simple message and returns it.", - "operationId": "EchoBody", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" - } - } - ], - "tags": [ - "UnannotatedEchoService" - ] - } - }, - "/v1/example/echo_delete": { - "delete": { - "summary": "EchoDelete method receives a simple message and returns it.", - "operationId": "EchoDelete", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbUnannotatedSimpleMessage" - } - } - }, - "parameters": [ - { - "name": "id", - "description": "Id represents the message identifier.", - "in": "query", - "required": false, - "type": "string" - }, - { - "name": "num", - "in": "query", - "required": false, - "type": "string", - "format": "int64" - }, - { - "name": "duration", - "in": "query", - "required": false, - "type": "string" - } - ], - "tags": [ - "UnannotatedEchoService" - ] - } - } - }, - "definitions": { - "examplepbUnannotatedSimpleMessage": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Id represents the message identifier." - }, - "num": { - "type": "string", - "format": "int64" - }, - "duration": { - "type": "string" - } - }, - "description": "UnannotatedSimpleMessage represents a simple message sent to the unannotated Echo service." - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.yaml b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.yaml deleted file mode 100755 index cd3a978..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/unannotated_echo_service.yaml +++ /dev/null @@ -1,15 +0,0 @@ -type: google.api.Service -config_version: 3 - -http: - rules: - - selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.Echo - post: "/v1/example/echo/{id}" - additional_bindings: - - get: "/v1/example/echo/{id}/{num}" - - selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.EchoBody - post: "/v1/example/echo_body" - body: "*" - - selector: grpc.gateway.examples.examplepb.UnannotatedEchoService.EchoDelete - delete: "/v1/example/echo_delete" - diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.go deleted file mode 100755 index a5065f9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.go +++ /dev/null @@ -1,209 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/examplepb/wrappers.proto - -package examplepb - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import wrappers "github.com/golang/protobuf/ptypes/wrappers" -import _ "google.golang.org/genproto/googleapis/api/annotations" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Wrappers struct { - StringValue *wrappers.StringValue `protobuf:"bytes,1,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - Int32Value *wrappers.Int32Value `protobuf:"bytes,2,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Int64Value *wrappers.Int64Value `protobuf:"bytes,3,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - FloatValue *wrappers.FloatValue `protobuf:"bytes,4,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue *wrappers.DoubleValue `protobuf:"bytes,5,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - BoolValue *wrappers.BoolValue `protobuf:"bytes,6,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Wrappers) Reset() { *m = Wrappers{} } -func (m *Wrappers) String() string { return proto.CompactTextString(m) } -func (*Wrappers) ProtoMessage() {} -func (*Wrappers) Descriptor() ([]byte, []int) { - return fileDescriptor_wrappers_c39e75a579a3cddc, []int{0} -} -func (m *Wrappers) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Wrappers.Unmarshal(m, b) -} -func (m *Wrappers) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Wrappers.Marshal(b, m, deterministic) -} -func (dst *Wrappers) XXX_Merge(src proto.Message) { - xxx_messageInfo_Wrappers.Merge(dst, src) -} -func (m *Wrappers) XXX_Size() int { - return xxx_messageInfo_Wrappers.Size(m) -} -func (m *Wrappers) XXX_DiscardUnknown() { - xxx_messageInfo_Wrappers.DiscardUnknown(m) -} - -var xxx_messageInfo_Wrappers proto.InternalMessageInfo - -func (m *Wrappers) GetStringValue() *wrappers.StringValue { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *Wrappers) GetInt32Value() *wrappers.Int32Value { - if m != nil { - return m.Int32Value - } - return nil -} - -func (m *Wrappers) GetInt64Value() *wrappers.Int64Value { - if m != nil { - return m.Int64Value - } - return nil -} - -func (m *Wrappers) GetFloatValue() *wrappers.FloatValue { - if m != nil { - return m.FloatValue - } - return nil -} - -func (m *Wrappers) GetDoubleValue() *wrappers.DoubleValue { - if m != nil { - return m.DoubleValue - } - return nil -} - -func (m *Wrappers) GetBoolValue() *wrappers.BoolValue { - if m != nil { - return m.BoolValue - } - return nil -} - -func init() { - proto.RegisterType((*Wrappers)(nil), "grpc.gateway.examples.examplepb.Wrappers") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// WrappersServiceClient is the client API for WrappersService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type WrappersServiceClient interface { - Create(ctx context.Context, in *Wrappers, opts ...grpc.CallOption) (*Wrappers, error) -} - -type wrappersServiceClient struct { - cc *grpc.ClientConn -} - -func NewWrappersServiceClient(cc *grpc.ClientConn) WrappersServiceClient { - return &wrappersServiceClient{cc} -} - -func (c *wrappersServiceClient) Create(ctx context.Context, in *Wrappers, opts ...grpc.CallOption) (*Wrappers, error) { - out := new(Wrappers) - err := c.cc.Invoke(ctx, "/grpc.gateway.examples.examplepb.WrappersService/Create", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// WrappersServiceServer is the server API for WrappersService service. -type WrappersServiceServer interface { - Create(context.Context, *Wrappers) (*Wrappers, error) -} - -func RegisterWrappersServiceServer(s *grpc.Server, srv WrappersServiceServer) { - s.RegisterService(&_WrappersService_serviceDesc, srv) -} - -func _WrappersService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Wrappers) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WrappersServiceServer).Create(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.gateway.examples.examplepb.WrappersService/Create", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WrappersServiceServer).Create(ctx, req.(*Wrappers)) - } - return interceptor(ctx, in, info, handler) -} - -var _WrappersService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gateway.examples.examplepb.WrappersService", - HandlerType: (*WrappersServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Create", - Handler: _WrappersService_Create_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "examples/proto/examplepb/wrappers.proto", -} - -func init() { - proto.RegisterFile("examples/proto/examplepb/wrappers.proto", fileDescriptor_wrappers_c39e75a579a3cddc) -} - -var fileDescriptor_wrappers_c39e75a579a3cddc = []byte{ - // 333 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0xd2, 0xcf, 0x4a, 0x3b, 0x31, - 0x10, 0x07, 0x70, 0xb6, 0xfd, 0xfd, 0x8a, 0xcd, 0x0a, 0xc2, 0xe2, 0x41, 0xd7, 0x62, 0xa5, 0x17, - 0xff, 0x1c, 0xb2, 0xd8, 0x96, 0x82, 0x22, 0x08, 0x55, 0x04, 0xaf, 0x16, 0x14, 0xbc, 0x48, 0xd2, - 0xa6, 0x4b, 0x20, 0xee, 0x84, 0x6c, 0xda, 0xea, 0x49, 0xf4, 0x11, 0xf4, 0xd1, 0x7c, 0x05, 0x1f, - 0x44, 0x36, 0x9d, 0x6c, 0xc1, 0x52, 0xf4, 0x36, 0xb3, 0xf9, 0x7e, 0x06, 0x86, 0x1d, 0xb2, 0x2f, - 0x9e, 0xd8, 0xa3, 0x56, 0x22, 0x4f, 0xb4, 0x01, 0x0b, 0x09, 0xb6, 0x9a, 0x27, 0x33, 0xc3, 0xb4, - 0x16, 0x26, 0xa7, 0xee, 0x21, 0x6a, 0xa6, 0x46, 0x0f, 0x69, 0xca, 0xac, 0x98, 0xb1, 0x67, 0xea, - 0x15, 0x2d, 0xf3, 0x71, 0x23, 0x05, 0x48, 0x95, 0x48, 0x98, 0x96, 0x09, 0xcb, 0x32, 0xb0, 0xcc, - 0x4a, 0xc8, 0x90, 0xc7, 0xbb, 0xf8, 0xea, 0x3a, 0x3e, 0x19, 0xff, 0x18, 0xdf, 0x7a, 0xad, 0x92, - 0xb5, 0x3b, 0xfc, 0x14, 0x9d, 0x93, 0xf5, 0xdc, 0x1a, 0x99, 0xa5, 0x0f, 0x53, 0xa6, 0x26, 0x62, - 0x2b, 0xd8, 0x0b, 0x0e, 0xc2, 0x76, 0x83, 0xce, 0x67, 0x50, 0x3f, 0x83, 0x0e, 0x5c, 0xe8, 0xb6, - 0xc8, 0xdc, 0x84, 0xf9, 0xa2, 0x89, 0xce, 0x48, 0x28, 0x33, 0xdb, 0x69, 0xa3, 0xaf, 0x38, 0xbf, - 0xb3, 0xe4, 0xaf, 0x8b, 0xcc, 0x9c, 0x13, 0x59, 0xd6, 0xa8, 0x7b, 0x5d, 0xd4, 0xd5, 0xd5, 0xba, - 0xd7, 0x5d, 0x68, 0xac, 0x0b, 0x3d, 0x56, 0xc0, 0x2c, 0xea, 0x7f, 0x2b, 0xf4, 0x55, 0x91, 0x41, - 0x3d, 0x2e, 0xeb, 0x62, 0xf5, 0x11, 0x4c, 0xb8, 0x12, 0xc8, 0xff, 0xaf, 0x58, 0xfd, 0xd2, 0x85, - 0x70, 0xf5, 0xd1, 0xa2, 0x89, 0x4e, 0x08, 0xe1, 0x00, 0x0a, 0x79, 0xcd, 0xf1, 0x78, 0x89, 0xf7, - 0x01, 0xd4, 0x1c, 0xd7, 0xb9, 0x2f, 0xdb, 0xef, 0x01, 0xd9, 0xf0, 0xff, 0x60, 0x20, 0xcc, 0x54, - 0x0e, 0x45, 0xf4, 0x42, 0x6a, 0x17, 0x46, 0x30, 0x2b, 0xa2, 0x43, 0xfa, 0xcb, 0x05, 0x50, 0x6f, - 0xe3, 0xbf, 0x47, 0x5b, 0xcd, 0xb7, 0xcf, 0xaf, 0x8f, 0xca, 0x76, 0x6b, 0x33, 0x99, 0x1e, 0xfb, - 0xe3, 0x2b, 0x6f, 0xe3, 0x34, 0x38, 0xea, 0x87, 0xf7, 0xf5, 0x92, 0xf1, 0x9a, 0x5b, 0xa0, 0xf3, - 0x1d, 0x00, 0x00, 0xff, 0xff, 0x3f, 0xa4, 0x0c, 0xe1, 0xb6, 0x02, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.gw.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.gw.go deleted file mode 100755 index b42c771..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.pb.gw.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: examples/proto/examplepb/wrappers.proto - -/* -Package examplepb is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package examplepb - -import ( - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray - -func request_WrappersService_Create_0(ctx context.Context, marshaler runtime.Marshaler, client WrappersServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq Wrappers - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Create(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -// RegisterWrappersServiceHandlerFromEndpoint is same as RegisterWrappersServiceHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterWrappersServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterWrappersServiceHandler(ctx, mux, conn) -} - -// RegisterWrappersServiceHandler registers the http handlers for service WrappersService to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterWrappersServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterWrappersServiceHandlerClient(ctx, mux, NewWrappersServiceClient(conn)) -} - -// RegisterWrappersServiceHandler registers the http handlers for service WrappersService to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "WrappersServiceClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "WrappersServiceClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "WrappersServiceClient" to call the correct interceptors. -func RegisterWrappersServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client WrappersServiceClient) error { - - mux.Handle("POST", pattern_WrappersService_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_WrappersService_Create_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_WrappersService_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_WrappersService_Create_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "example", "wrappers"}, "")) -) - -var ( - forward_WrappersService_Create_0 = runtime.ForwardResponseMessage -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.proto deleted file mode 100755 index 094b0a4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; -option go_package = "examplepb"; -package grpc.gateway.examples.examplepb; - -import "google/api/annotations.proto"; -import "google/protobuf/wrappers.proto"; - -message Wrappers { - google.protobuf.StringValue string_value = 1; - google.protobuf.Int32Value int32_value = 2; - google.protobuf.Int64Value int64_value = 3; - google.protobuf.FloatValue float_value = 4; - google.protobuf.DoubleValue double_value = 5; - google.protobuf.BoolValue bool_value = 6; -} - -service WrappersService { - rpc Create(Wrappers) returns (Wrappers) { - option (google.api.http) = { - post: "/v1/example/wrappers" - body: "*" - }; - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.swagger.json b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.swagger.json deleted file mode 100755 index 37c6144..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb/wrappers.swagger.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "examples/proto/examplepb/wrappers.proto", - "version": "version not set" - }, - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/v1/example/wrappers": { - "post": { - "operationId": "Create", - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/examplepbWrappers" - } - } - }, - "parameters": [ - { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/examplepbWrappers" - } - } - ], - "tags": [ - "WrappersService" - ] - } - } - }, - "definitions": { - "examplepbWrappers": { - "type": "object", - "properties": { - "string_value": { - "type": "string" - }, - "int32_value": { - "type": "integer", - "format": "int32" - }, - "int64_value": { - "type": "integer", - "format": "int64" - }, - "float_value": { - "type": "number", - "format": "float" - }, - "double_value": { - "type": "number", - "format": "double" - }, - "bool_value": { - "type": "boolean", - "format": "boolean" - } - } - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/BUILD.bazel deleted file mode 100755 index bc5874b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/BUILD.bazel +++ /dev/null @@ -1,21 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") - -package(default_visibility = ["//visibility:public"]) - -proto_library( - name = "sub_proto", - srcs = ["message.proto"], -) - -go_proto_library( - name = "sub_go_proto", - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub", - proto = ":sub_proto", -) - -go_library( - name = "go_default_library", - embed = [":sub_go_proto"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub", -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.pb.go deleted file mode 100755 index 8161243..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.pb.go +++ /dev/null @@ -1,77 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/sub/message.proto - -package sub - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type StringMessage struct { - Value *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StringMessage) Reset() { *m = StringMessage{} } -func (m *StringMessage) String() string { return proto.CompactTextString(m) } -func (*StringMessage) ProtoMessage() {} -func (*StringMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_message_c180d3d1a4bbfe02, []int{0} -} -func (m *StringMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StringMessage.Unmarshal(m, b) -} -func (m *StringMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StringMessage.Marshal(b, m, deterministic) -} -func (dst *StringMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_StringMessage.Merge(dst, src) -} -func (m *StringMessage) XXX_Size() int { - return xxx_messageInfo_StringMessage.Size(m) -} -func (m *StringMessage) XXX_DiscardUnknown() { - xxx_messageInfo_StringMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_StringMessage proto.InternalMessageInfo - -func (m *StringMessage) GetValue() string { - if m != nil && m.Value != nil { - return *m.Value - } - return "" -} - -func init() { - proto.RegisterType((*StringMessage)(nil), "grpc.gateway.examples.sub.StringMessage") -} - -func init() { - proto.RegisterFile("examples/proto/sub/message.proto", fileDescriptor_message_c180d3d1a4bbfe02) -} - -var fileDescriptor_message_c180d3d1a4bbfe02 = []byte{ - // 114 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xad, 0x48, 0xcc, - 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x2e, 0x4d, 0xd2, 0xcf, - 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x03, 0x8b, 0x08, 0x49, 0xa6, 0x17, 0x15, 0x24, 0xeb, - 0xa5, 0x27, 0x96, 0xa4, 0x96, 0x27, 0x56, 0xea, 0xc1, 0x94, 0xeb, 0x15, 0x97, 0x26, 0x29, 0xa9, - 0x72, 0xf1, 0x06, 0x97, 0x14, 0x65, 0xe6, 0xa5, 0xfb, 0x42, 0x74, 0x08, 0x89, 0x70, 0xb1, 0x96, - 0x25, 0xe6, 0x94, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x69, 0x70, 0x06, 0x41, 0x38, 0x4e, 0xac, 0x51, - 0xcc, 0xc5, 0xa5, 0x49, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6c, 0x00, 0x25, 0x33, 0x6b, 0x00, - 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.proto deleted file mode 100755 index 7702a93..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub/message.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto2"; -option go_package = "sub"; -package grpc.gateway.examples.sub; - -message StringMessage { - required string value = 1; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/BUILD.bazel deleted file mode 100755 index 539f5b6..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/BUILD.bazel +++ /dev/null @@ -1,21 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") - -package(default_visibility = ["//visibility:public"]) - -proto_library( - name = "sub2_proto", - srcs = ["message.proto"], -) - -go_proto_library( - name = "sub2_go_proto", - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2", - proto = ":sub2_proto", -) - -go_library( - name = "go_default_library", - embed = [":sub2_go_proto"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2", -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.pb.go deleted file mode 100755 index a0a812c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.pb.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: examples/proto/sub2/message.proto - -package sub2 // import "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type IdMessage struct { - Uuid string `protobuf:"bytes,1,opt,name=uuid" json:"uuid,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *IdMessage) Reset() { *m = IdMessage{} } -func (m *IdMessage) String() string { return proto.CompactTextString(m) } -func (*IdMessage) ProtoMessage() {} -func (*IdMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_message_1fa155de06adc960, []int{0} -} -func (m *IdMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_IdMessage.Unmarshal(m, b) -} -func (m *IdMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_IdMessage.Marshal(b, m, deterministic) -} -func (dst *IdMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_IdMessage.Merge(dst, src) -} -func (m *IdMessage) XXX_Size() int { - return xxx_messageInfo_IdMessage.Size(m) -} -func (m *IdMessage) XXX_DiscardUnknown() { - xxx_messageInfo_IdMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_IdMessage proto.InternalMessageInfo - -func (m *IdMessage) GetUuid() string { - if m != nil { - return m.Uuid - } - return "" -} - -func init() { - proto.RegisterType((*IdMessage)(nil), "sub2.IdMessage") -} - -func init() { - proto.RegisterFile("examples/proto/sub2/message.proto", fileDescriptor_message_1fa155de06adc960) -} - -var fileDescriptor_message_1fa155de06adc960 = []byte{ - // 130 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4c, 0xad, 0x48, 0xcc, - 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x2f, 0x2e, 0x4d, 0x32, 0xd2, - 0xcf, 0x4d, 0x2d, 0x2e, 0x4e, 0x4c, 0x4f, 0xd5, 0x03, 0x0b, 0x09, 0xb1, 0x80, 0xc4, 0x94, 0xe4, - 0xb9, 0x38, 0x3d, 0x53, 0x7c, 0x21, 0x12, 0x42, 0x42, 0x5c, 0x2c, 0xa5, 0xa5, 0x99, 0x29, 0x12, - 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x93, 0x4d, 0x94, 0x55, 0x7a, 0x66, 0x49, 0x46, - 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x51, 0x41, 0xb2, 0x6e, 0x6a, 0x72, 0x7e, 0x71, - 0x65, 0x71, 0x49, 0x2a, 0x94, 0x9b, 0x9e, 0x58, 0x92, 0x5a, 0x9e, 0x58, 0xa9, 0x8f, 0xc5, 0xca, - 0x24, 0x36, 0x30, 0xdb, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x49, 0xe7, 0x2f, 0x90, 0x00, - 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.proto deleted file mode 100755 index 59c9bd9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2/message.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -option go_package = "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2"; -package sub2; - -message IdMessage { - string uuid = 1; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/BUILD.bazel deleted file mode 100755 index 61fff8a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/BUILD.bazel +++ /dev/null @@ -1,30 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "a_bit_of_everything.go", - "echo.go", - "flow_combination.go", - "main.go", - "unannotatedecho.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/examples/server", - deps = [ - "//examples/proto/examplepb:go_default_library", - "//examples/proto/sub:go_default_library", - "//examples/proto/sub2:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//ptypes/duration:go_default_library", - "@com_github_golang_protobuf//ptypes/empty:go_default_library", - "@com_github_rogpeppe_fastuuid//:go_default_library", - "@org_golang_google_genproto//googleapis/rpc/errdetails:go_default_library", - "@org_golang_google_grpc//:go_default_library", - "@org_golang_google_grpc//codes:go_default_library", - "@org_golang_google_grpc//metadata:go_default_library", - "@org_golang_google_grpc//status:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/a_bit_of_everything.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/a_bit_of_everything.go deleted file mode 100755 index 2d8dec5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/a_bit_of_everything.go +++ /dev/null @@ -1,272 +0,0 @@ -package server - -import ( - "context" - "fmt" - "io" - "sync" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/empty" - examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - sub "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub" - sub2 "github.com/grpc-ecosystem/grpc-gateway/examples/proto/sub2" - "github.com/rogpeppe/fastuuid" - "google.golang.org/genproto/googleapis/rpc/errdetails" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Implements of ABitOfEverythingServiceServer - -var uuidgen = fastuuid.MustNewGenerator() - -type _ABitOfEverythingServer struct { - v map[string]*examples.ABitOfEverything - m sync.Mutex -} - -type ABitOfEverythingServer interface { - examples.ABitOfEverythingServiceServer - examples.StreamServiceServer -} - -func newABitOfEverythingServer() ABitOfEverythingServer { - return &_ABitOfEverythingServer{ - v: make(map[string]*examples.ABitOfEverything), - } -} - -func (s *_ABitOfEverythingServer) Create(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - var uuid string - for { - uuid = fmt.Sprintf("%x", uuidgen.Next()) - if _, ok := s.v[uuid]; !ok { - break - } - } - s.v[uuid] = msg - s.v[uuid].Uuid = uuid - glog.Infof("%v", s.v[uuid]) - return s.v[uuid], nil -} - -func (s *_ABitOfEverythingServer) CreateBody(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { - return s.Create(ctx, msg) -} - -func (s *_ABitOfEverythingServer) BulkCreate(stream examples.StreamService_BulkCreateServer) error { - count := 0 - ctx := stream.Context() - for { - msg, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - return err - } - count++ - glog.Error(msg) - if _, err = s.Create(ctx, msg); err != nil { - return err - } - } - - err := stream.SendHeader(metadata.New(map[string]string{ - "count": fmt.Sprintf("%d", count), - })) - if err != nil { - return nil - } - - stream.SetTrailer(metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return stream.SendAndClose(new(empty.Empty)) -} - -func (s *_ABitOfEverythingServer) Lookup(ctx context.Context, msg *sub2.IdMessage) (*examples.ABitOfEverything, error) { - s.m.Lock() - defer s.m.Unlock() - glog.Info(msg) - - err := grpc.SendHeader(ctx, metadata.New(map[string]string{ - "uuid": msg.Uuid, - })) - if err != nil { - return nil, err - } - - if a, ok := s.v[msg.Uuid]; ok { - return a, nil - } - - grpc.SetTrailer(ctx, metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return nil, status.Errorf(codes.NotFound, "not found") -} - -func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamService_ListServer) error { - s.m.Lock() - defer s.m.Unlock() - - err := stream.SendHeader(metadata.New(map[string]string{ - "count": fmt.Sprintf("%d", len(s.v)), - })) - if err != nil { - return nil - } - - for _, msg := range s.v { - if err := stream.Send(msg); err != nil { - return err - } - } - - // return error when metadata includes error header - if header, ok := metadata.FromIncomingContext(stream.Context()); ok { - if v, ok := header["error"]; ok { - stream.SetTrailer(metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return status.Errorf(codes.InvalidArgument, "error metadata: %v", v) - } - } - return nil -} - -func (s *_ABitOfEverythingServer) Update(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - if _, ok := s.v[msg.Uuid]; ok { - s.v[msg.Uuid] = msg - } else { - return nil, status.Errorf(codes.NotFound, "not found") - } - return new(empty.Empty), nil -} - -func (s *_ABitOfEverythingServer) Delete(ctx context.Context, msg *sub2.IdMessage) (*empty.Empty, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - if _, ok := s.v[msg.Uuid]; ok { - delete(s.v, msg.Uuid) - } else { - return nil, status.Errorf(codes.NotFound, "not found") - } - return new(empty.Empty), nil -} - -func (s *_ABitOfEverythingServer) GetQuery(ctx context.Context, msg *examples.ABitOfEverything) (*empty.Empty, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - if _, ok := s.v[msg.Uuid]; ok { - s.v[msg.Uuid] = msg - } else { - return nil, status.Errorf(codes.NotFound, "not found") - } - return new(empty.Empty), nil -} - -func (s *_ABitOfEverythingServer) Echo(ctx context.Context, msg *sub.StringMessage) (*sub.StringMessage, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - return msg, nil -} - -func (s *_ABitOfEverythingServer) BulkEcho(stream examples.StreamService_BulkEchoServer) error { - var msgs []*sub.StringMessage - for { - msg, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - return err - } - msgs = append(msgs, msg) - } - - hmd := metadata.New(map[string]string{ - "foo": "foo1", - "bar": "bar1", - }) - if err := stream.SendHeader(hmd); err != nil { - return err - } - - for _, msg := range msgs { - glog.Info(msg) - if err := stream.Send(msg); err != nil { - return err - } - } - - stream.SetTrailer(metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return nil -} - -func (s *_ABitOfEverythingServer) DeepPathEcho(ctx context.Context, msg *examples.ABitOfEverything) (*examples.ABitOfEverything, error) { - s.m.Lock() - defer s.m.Unlock() - - glog.Info(msg) - return msg, nil -} - -func (s *_ABitOfEverythingServer) NoBindings(ctx context.Context, msg *duration.Duration) (*empty.Empty, error) { - return nil, nil -} - -func (s *_ABitOfEverythingServer) Timeout(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { - select { - case <-ctx.Done(): - return nil, ctx.Err() - } -} - -func (s *_ABitOfEverythingServer) ErrorWithDetails(ctx context.Context, msg *empty.Empty) (*empty.Empty, error) { - stat, err := status.New(codes.Unknown, "with details"). - WithDetails(proto.Message( - &errdetails.DebugInfo{ - StackEntries: []string{"foo:1"}, - Detail: "error debug details", - }, - )) - if err != nil { - return nil, status.Errorf(codes.Internal, "unexpected error adding details: %s", err) - } - return nil, stat.Err() -} - -func (s *_ABitOfEverythingServer) GetMessageWithBody(ctx context.Context, msg *examples.MessageWithBody) (*empty.Empty, error) { - return &empty.Empty{}, nil -} - -func (s *_ABitOfEverythingServer) PostWithEmptyBody(ctx context.Context, msg *examples.Body) (*empty.Empty, error) { - return &empty.Empty{}, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/echo.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/echo.go deleted file mode 100755 index 249aeb0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/echo.go +++ /dev/null @@ -1,41 +0,0 @@ -package server - -import ( - "context" - - "github.com/golang/glog" - examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" -) - -// Implements of EchoServiceServer - -type echoServer struct{} - -func newEchoServer() examples.EchoServiceServer { - return new(echoServer) -} - -func (s *echoServer) Echo(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { - glog.Info(msg) - return msg, nil -} - -func (s *echoServer) EchoBody(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { - glog.Info(msg) - grpc.SendHeader(ctx, metadata.New(map[string]string{ - "foo": "foo1", - "bar": "bar1", - })) - grpc.SetTrailer(ctx, metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return msg, nil -} - -func (s *echoServer) EchoDelete(ctx context.Context, msg *examples.SimpleMessage) (*examples.SimpleMessage, error) { - glog.Info(msg) - return msg, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/flow_combination.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/flow_combination.go deleted file mode 100755 index 516510f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/flow_combination.go +++ /dev/null @@ -1,72 +0,0 @@ -package server - -import ( - "context" - "io" - - examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" -) - -type flowCombinationServer struct{} - -func newFlowCombinationServer() examples.FlowCombinationServer { - return &flowCombinationServer{} -} - -func (s flowCombinationServer) RpcEmptyRpc(ctx context.Context, req *examples.EmptyProto) (*examples.EmptyProto, error) { - return req, nil -} - -func (s flowCombinationServer) RpcEmptyStream(req *examples.EmptyProto, stream examples.FlowCombination_RpcEmptyStreamServer) error { - return stream.Send(req) -} - -func (s flowCombinationServer) StreamEmptyRpc(stream examples.FlowCombination_StreamEmptyRpcServer) error { - for { - _, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - return err - } - } - return stream.SendAndClose(new(examples.EmptyProto)) -} - -func (s flowCombinationServer) StreamEmptyStream(stream examples.FlowCombination_StreamEmptyStreamServer) error { - for { - _, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - return err - } - } - return stream.Send(new(examples.EmptyProto)) -} - -func (s flowCombinationServer) RpcBodyRpc(ctx context.Context, req *examples.NonEmptyProto) (*examples.EmptyProto, error) { - return new(examples.EmptyProto), nil -} - -func (s flowCombinationServer) RpcPathSingleNestedRpc(ctx context.Context, req *examples.SingleNestedProto) (*examples.EmptyProto, error) { - return new(examples.EmptyProto), nil -} - -func (s flowCombinationServer) RpcPathNestedRpc(ctx context.Context, req *examples.NestedProto) (*examples.EmptyProto, error) { - return new(examples.EmptyProto), nil -} - -func (s flowCombinationServer) RpcBodyStream(req *examples.NonEmptyProto, stream examples.FlowCombination_RpcBodyStreamServer) error { - return stream.Send(new(examples.EmptyProto)) -} - -func (s flowCombinationServer) RpcPathSingleNestedStream(req *examples.SingleNestedProto, stream examples.FlowCombination_RpcPathSingleNestedStreamServer) error { - return stream.Send(new(examples.EmptyProto)) -} - -func (s flowCombinationServer) RpcPathNestedStream(req *examples.NestedProto, stream examples.FlowCombination_RpcPathNestedStreamServer) error { - return stream.Send(new(examples.EmptyProto)) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/main.go deleted file mode 100755 index 4cd385f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/main.go +++ /dev/null @@ -1,38 +0,0 @@ -package server - -import ( - "context" - "net" - - "github.com/golang/glog" - examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "google.golang.org/grpc" -) - -// Run starts the example gRPC service. -// "network" and "address" are passed to net.Listen. -func Run(ctx context.Context, network, address string) error { - l, err := net.Listen(network, address) - if err != nil { - return err - } - defer func() { - if err := l.Close(); err != nil { - glog.Errorf("Failed to close %s %s: %v", network, address, err) - } - }() - - s := grpc.NewServer() - examples.RegisterEchoServiceServer(s, newEchoServer()) - examples.RegisterFlowCombinationServer(s, newFlowCombinationServer()) - - abe := newABitOfEverythingServer() - examples.RegisterABitOfEverythingServiceServer(s, abe) - examples.RegisterStreamServiceServer(s, abe) - - go func() { - defer s.GracefulStop() - <-ctx.Done() - }() - return s.Serve(l) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/unannotatedecho.go b/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/unannotatedecho.go deleted file mode 100755 index bf3bff0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/examples/server/unannotatedecho.go +++ /dev/null @@ -1,40 +0,0 @@ -package server - -import ( - "context" - "github.com/golang/glog" - examples "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" -) - -// Implements of UnannotatedEchoServiceServer - -type unannotatedEchoServer struct{} - -func newUnannotatedEchoServer() examples.UnannotatedEchoServiceServer { - return new(unannotatedEchoServer) -} - -func (s *unannotatedEchoServer) Echo(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { - glog.Info(msg) - return msg, nil -} - -func (s *unannotatedEchoServer) EchoBody(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { - glog.Info(msg) - grpc.SendHeader(ctx, metadata.New(map[string]string{ - "foo": "foo1", - "bar": "bar1", - })) - grpc.SetTrailer(ctx, metadata.New(map[string]string{ - "foo": "foo2", - "bar": "bar2", - })) - return msg, nil -} - -func (s *unannotatedEchoServer) EchoDelete(ctx context.Context, msg *examples.UnannotatedSimpleMessage) (*examples.UnannotatedSimpleMessage, error) { - glog.Info(msg) - return msg, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel deleted file mode 100755 index fc4850f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel +++ /dev/null @@ -1,41 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") -load("@io_bazel_rules_go//proto:compiler.bzl", "go_proto_compiler") - -package(default_visibility = ["//visibility:private"]) - -go_library( - name = "go_default_library", - srcs = ["main.go"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway", - deps = [ - "//codegenerator:go_default_library", - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-grpc-gateway/gengateway:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) - -go_binary( - name = "protoc-gen-grpc-gateway", - embed = [":go_default_library"], -) - -go_proto_compiler( - name = "go_gen_grpc_gateway", - options = ["logtostderr=true"], - plugin = ":protoc-gen-grpc-gateway", - suffix = ".pb.gw.go", - visibility = ["//visibility:public"], - deps = [ - "//runtime:go_default_library", - "//utilities:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@org_golang_google_grpc//:go_default_library", - "@org_golang_google_grpc//codes:go_default_library", - "@org_golang_google_grpc//grpclog:go_default_library", - "@org_golang_google_grpc//status:go_default_library", - "@org_golang_x_net//context:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel deleted file mode 100755 index 93670c5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel +++ /dev/null @@ -1,44 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//:generators"]) - -go_library( - name = "go_default_library", - srcs = [ - "grpc_api_configuration.go", - "grpc_api_service.go", - "registry.go", - "services.go", - "types.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor", - deps = [ - "//protoc-gen-grpc-gateway/httprule:go_default_library", - "@com_github_ghodss_yaml//:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - "@org_golang_google_genproto//googleapis/api/annotations:go_default_library", - ], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = [ - "grpc_api_configuration_test.go", - "registry_test.go", - "services_test.go", - "types_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//protoc-gen-grpc-gateway/httprule:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go deleted file mode 100755 index ca68ed7..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go +++ /dev/null @@ -1,71 +0,0 @@ -package descriptor - -import ( - "bytes" - "fmt" - "io/ioutil" - "strings" - - "github.com/ghodss/yaml" - "github.com/golang/protobuf/jsonpb" -) - -func loadGrpcAPIServiceFromYAML(yamlFileContents []byte, yamlSourceLogName string) (*GrpcAPIService, error) { - jsonContents, err := yaml.YAMLToJSON(yamlFileContents) - if err != nil { - return nil, fmt.Errorf("Failed to convert gRPC API Configuration from YAML in '%v' to JSON: %v", yamlSourceLogName, err) - } - - // As our GrpcAPIService is incomplete accept unkown fields. - unmarshaler := jsonpb.Unmarshaler{ - AllowUnknownFields: true, - } - - serviceConfiguration := GrpcAPIService{} - if err := unmarshaler.Unmarshal(bytes.NewReader(jsonContents), &serviceConfiguration); err != nil { - return nil, fmt.Errorf("Failed to parse gRPC API Configuration from YAML in '%v': %v", yamlSourceLogName, err) - } - - return &serviceConfiguration, nil -} - -func registerHTTPRulesFromGrpcAPIService(registry *Registry, service *GrpcAPIService, sourceLogName string) error { - if service.HTTP == nil { - // Nothing to do - return nil - } - - for _, rule := range service.HTTP.GetRules() { - selector := "." + strings.Trim(rule.GetSelector(), " ") - if strings.ContainsAny(selector, "*, ") { - return fmt.Errorf("Selector '%v' in %v must specify a single service method without wildcards", rule.GetSelector(), sourceLogName) - } - - registry.AddExternalHTTPRule(selector, rule) - } - - return nil -} - -// LoadGrpcAPIServiceFromYAML loads a gRPC API Configuration from the given YAML file -// and registers the HttpRule descriptions contained in it as externalHTTPRules in -// the given registry. This must be done before loading the proto file. -// -// You can learn more about gRPC API Service descriptions from google's documentation -// at https://cloud.google.com/endpoints/docs/grpc/grpc-service-config -// -// Note that for the purposes of the gateway generator we only consider a subset of all -// available features google supports in their service descriptions. -func (r *Registry) LoadGrpcAPIServiceFromYAML(yamlFile string) error { - yamlFileContents, err := ioutil.ReadFile(yamlFile) - if err != nil { - return fmt.Errorf("Failed to read gRPC API Configuration description from '%v': %v", yamlFile, err) - } - - service, err := loadGrpcAPIServiceFromYAML(yamlFileContents, yamlFile) - if err != nil { - return err - } - - return registerHTTPRulesFromGrpcAPIService(r, service, yamlFile) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration_test.go deleted file mode 100755 index cc6cb44..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration_test.go +++ /dev/null @@ -1,164 +0,0 @@ -package descriptor - -import ( - "strings" - "testing" -) - -func TestLoadGrpcAPIServiceFromYAMLEmpty(t *testing.T) { - service, err := loadGrpcAPIServiceFromYAML([]byte(``), "empty") - if err != nil { - t.Fatal(err) - } - - if service == nil { - t.Fatal("No service returned") - } - - if service.HTTP != nil { - t.Fatal("HTTP not empty") - } -} - -func TestLoadGrpcAPIServiceFromYAMLInvalidType(t *testing.T) { - // Ideally this would fail but for now this test documents that it doesn't - service, err := loadGrpcAPIServiceFromYAML([]byte(`type: not.the.right.type`), "invalidtype") - if err != nil { - t.Fatal(err) - } - - if service == nil { - t.Fatal("No service returned") - } -} - -func TestLoadGrpcAPIServiceFromYAMLSingleRule(t *testing.T) { - service, err := loadGrpcAPIServiceFromYAML([]byte(` -type: google.api.Service -config_version: 3 - -http: - rules: - - selector: grpctest.YourService.Echo - post: /v1/myecho - body: "*" -`), "example") - if err != nil { - t.Fatal(err) - } - - if service.HTTP == nil { - t.Fatal("HTTP is empty") - } - - if len(service.HTTP.GetRules()) != 1 { - t.Fatalf("Have %v rules instead of one. Got: %v", len(service.HTTP.GetRules()), service.HTTP.GetRules()) - } - - rule := service.HTTP.GetRules()[0] - if rule.GetSelector() != "grpctest.YourService.Echo" { - t.Errorf("Rule has unexpected selector '%v'", rule.GetSelector()) - } - if rule.GetPost() != "/v1/myecho" { - t.Errorf("Rule has unexpected post '%v'", rule.GetPost()) - } - if rule.GetBody() != "*" { - t.Errorf("Rule has unexpected body '%v'", rule.GetBody()) - } -} - -func TestLoadGrpcAPIServiceFromYAMLRejectInvalidYAML(t *testing.T) { - service, err := loadGrpcAPIServiceFromYAML([]byte(` -type: google.api.Service -config_version: 3 - -http: - rules: - - selector: grpctest.YourService.Echo - - post: thislinebreakstheselectorblockabovewiththeleadingdash - body: "*" -`), "invalidyaml") - if err == nil { - t.Fatal(err) - } - - if !strings.Contains(err.Error(), "line 7") { - t.Errorf("Expected yaml error to be detected in line 7. Got other error: %v", err) - } - - if service != nil { - t.Fatal("Service returned") - } -} - -func TestLoadGrpcAPIServiceFromYAMLMultipleWithAdditionalBindings(t *testing.T) { - service, err := loadGrpcAPIServiceFromYAML([]byte(` -type: google.api.Service -config_version: 3 - -http: - rules: - - selector: first.selector - post: /my/post/path - body: "*" - additional_bindings: - - post: /additional/post/path - - put: /additional/put/{value}/path - - delete: "{value}" - - patch: "/additional/patch/{value}" - - selector: some.other.service - delete: foo -`), "example") - if err != nil { - t.Fatalf("Failed to load service description from YAML: %v", err) - } - - if service == nil { - t.Fatal("No service returned") - } - - if service.HTTP == nil { - t.Fatal("HTTP is empty") - } - - if len(service.HTTP.GetRules()) != 2 { - t.Fatalf("%v service(s) returned when two were expected. Got: %v", len(service.HTTP.GetRules()), service.HTTP) - } - - first := service.HTTP.GetRules()[0] - if first.GetSelector() != "first.selector" { - t.Errorf("first.selector has unexpected selector '%v'", first.GetSelector()) - } - if first.GetBody() != "*" { - t.Errorf("first.selector has unexpected body '%v'", first.GetBody()) - } - if first.GetPost() != "/my/post/path" { - t.Errorf("first.selector has unexpected post '%v'", first.GetPost()) - } - if len(first.GetAdditionalBindings()) != 4 { - t.Fatalf("first.selector has unexpected number of bindings %v instead of four. Got: %v", len(first.GetAdditionalBindings()), first.GetAdditionalBindings()) - } - if first.GetAdditionalBindings()[0].GetPost() != "/additional/post/path" { - t.Errorf("first.selector additional binding 0 has unexpected post '%v'", first.GetAdditionalBindings()[0].GetPost()) - } - if first.GetAdditionalBindings()[1].GetPut() != "/additional/put/{value}/path" { - t.Errorf("first.selector additional binding 1 has unexpected put '%v'", first.GetAdditionalBindings()[0].GetPost()) - } - if first.GetAdditionalBindings()[2].GetDelete() != "{value}" { - t.Errorf("first.selector additional binding 2 has unexpected delete '%v'", first.GetAdditionalBindings()[0].GetPost()) - } - if first.GetAdditionalBindings()[3].GetPatch() != "/additional/patch/{value}" { - t.Errorf("first.selector additional binding 3 has unexpected patch '%v'", first.GetAdditionalBindings()[0].GetPost()) - } - - second := service.HTTP.GetRules()[1] - if second.GetSelector() != "some.other.service" { - t.Errorf("some.other.service has unexpected selector '%v'", second.GetSelector()) - } - if second.GetDelete() != "foo" { - t.Errorf("some.other.service has unexpected delete '%v'", second.GetDelete()) - } - if len(second.GetAdditionalBindings()) != 0 { - t.Errorf("some.other.service has %v additional bindings when it should not have any. Got: %v", len(second.GetAdditionalBindings()), second.GetAdditionalBindings()) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go deleted file mode 100755 index 75b8240..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go +++ /dev/null @@ -1,31 +0,0 @@ -package descriptor - -import ( - "github.com/golang/protobuf/proto" - "google.golang.org/genproto/googleapis/api/annotations" -) - -// GrpcAPIService represents a stripped down version of google.api.Service . -// Compare to https://github.com/googleapis/googleapis/blob/master/google/api/service.proto -// The original imports 23 other protobuf files we are not interested in. If a significant -// subset (>50%) of these start being reproduced in this file we should swap to using the -// full generated version instead. -// -// For the purposes of the gateway generator we only consider a small subset of all -// available features google supports in their service descriptions. Thanks to backwards -// compatibility guarantees by protobuf it is safe for us to remove the other fields. -// We also only implement the absolute minimum of protobuf generator boilerplate to use -// our simplified version. These should be pretty stable too. -type GrpcAPIService struct { - // Http Rule. Named Http in the actual proto. Changed to suppress linter warning. - HTTP *annotations.Http `protobuf:"bytes,9,opt,name=http" json:"http,omitempty"` -} - -// ProtoMessage returns an empty GrpcAPIService element -func (*GrpcAPIService) ProtoMessage() {} - -// Reset resets the GrpcAPIService -func (m *GrpcAPIService) Reset() { *m = GrpcAPIService{} } - -// String returns the string representation of the GrpcAPIService -func (m *GrpcAPIService) String() string { return proto.CompactTextString(m) } diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go deleted file mode 100755 index b09e193..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go +++ /dev/null @@ -1,375 +0,0 @@ -package descriptor - -import ( - "fmt" - "path" - "path/filepath" - "strings" - - "github.com/golang/glog" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "google.golang.org/genproto/googleapis/api/annotations" -) - -// Registry is a registry of information extracted from plugin.CodeGeneratorRequest. -type Registry struct { - // msgs is a mapping from fully-qualified message name to descriptor - msgs map[string]*Message - - // enums is a mapping from fully-qualified enum name to descriptor - enums map[string]*Enum - - // files is a mapping from file path to descriptor - files map[string]*File - - // prefix is a prefix to be inserted to golang package paths generated from proto package names. - prefix string - - // importPath is used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored. - importPath string - - // pkgMap is a user-specified mapping from file path to proto package. - pkgMap map[string]string - - // pkgAliases is a mapping from package aliases to package paths in go which are already taken. - pkgAliases map[string]string - - // allowDeleteBody permits http delete methods to have a body - allowDeleteBody bool - - // externalHttpRules is a mapping from fully qualified service method names to additional HttpRules applicable besides the ones found in annotations. - externalHTTPRules map[string][]*annotations.HttpRule - - // allowMerge generation one swagger file out of multiple protos - allowMerge bool - - // mergeFileName target swagger file name after merge - mergeFileName string -} - -// NewRegistry returns a new Registry. -func NewRegistry() *Registry { - return &Registry{ - msgs: make(map[string]*Message), - enums: make(map[string]*Enum), - files: make(map[string]*File), - pkgMap: make(map[string]string), - pkgAliases: make(map[string]string), - externalHTTPRules: make(map[string][]*annotations.HttpRule), - } -} - -// Load loads definitions of services, methods, messages, enumerations and fields from "req". -func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error { - for _, file := range req.GetProtoFile() { - r.loadFile(file) - } - - var targetPkg string - for _, name := range req.FileToGenerate { - target := r.files[name] - if target == nil { - return fmt.Errorf("no such file: %s", name) - } - name := r.packageIdentityName(target.FileDescriptorProto) - if targetPkg == "" { - targetPkg = name - } else { - if targetPkg != name { - return fmt.Errorf("inconsistent package names: %s %s", targetPkg, name) - } - } - - if err := r.loadServices(target); err != nil { - return err - } - } - return nil -} - -// loadFile loads messages, enumerations and fields from "file". -// It does not loads services and methods in "file". You need to call -// loadServices after loadFiles is called for all files to load services and methods. -func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) { - pkg := GoPackage{ - Path: r.goPackagePath(file), - Name: r.defaultGoPackageName(file), - } - if err := r.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil { - for i := 0; ; i++ { - alias := fmt.Sprintf("%s_%d", pkg.Name, i) - if err := r.ReserveGoPackageAlias(alias, pkg.Path); err == nil { - pkg.Alias = alias - break - } - } - } - f := &File{ - FileDescriptorProto: file, - GoPkg: pkg, - } - - r.files[file.GetName()] = f - r.registerMsg(f, nil, file.GetMessageType()) - r.registerEnum(f, nil, file.GetEnumType()) -} - -func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptor.DescriptorProto) { - for i, md := range msgs { - m := &Message{ - File: file, - Outers: outerPath, - DescriptorProto: md, - Index: i, - } - for _, fd := range md.GetField() { - m.Fields = append(m.Fields, &Field{ - Message: m, - FieldDescriptorProto: fd, - }) - } - file.Messages = append(file.Messages, m) - r.msgs[m.FQMN()] = m - glog.V(1).Infof("register name: %s", m.FQMN()) - - var outers []string - outers = append(outers, outerPath...) - outers = append(outers, m.GetName()) - r.registerMsg(file, outers, m.GetNestedType()) - r.registerEnum(file, outers, m.GetEnumType()) - } -} - -func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptor.EnumDescriptorProto) { - for i, ed := range enums { - e := &Enum{ - File: file, - Outers: outerPath, - EnumDescriptorProto: ed, - Index: i, - } - file.Enums = append(file.Enums, e) - r.enums[e.FQEN()] = e - glog.V(1).Infof("register enum name: %s", e.FQEN()) - } -} - -// LookupMsg looks up a message type by "name". -// It tries to resolve "name" from "location" if "name" is a relative message name. -func (r *Registry) LookupMsg(location, name string) (*Message, error) { - glog.V(1).Infof("lookup %s from %s", name, location) - if strings.HasPrefix(name, ".") { - m, ok := r.msgs[name] - if !ok { - return nil, fmt.Errorf("no message found: %s", name) - } - return m, nil - } - - if !strings.HasPrefix(location, ".") { - location = fmt.Sprintf(".%s", location) - } - components := strings.Split(location, ".") - for len(components) > 0 { - fqmn := strings.Join(append(components, name), ".") - if m, ok := r.msgs[fqmn]; ok { - return m, nil - } - components = components[:len(components)-1] - } - return nil, fmt.Errorf("no message found: %s", name) -} - -// LookupEnum looks up a enum type by "name". -// It tries to resolve "name" from "location" if "name" is a relative enum name. -func (r *Registry) LookupEnum(location, name string) (*Enum, error) { - glog.V(1).Infof("lookup enum %s from %s", name, location) - if strings.HasPrefix(name, ".") { - e, ok := r.enums[name] - if !ok { - return nil, fmt.Errorf("no enum found: %s", name) - } - return e, nil - } - - if !strings.HasPrefix(location, ".") { - location = fmt.Sprintf(".%s", location) - } - components := strings.Split(location, ".") - for len(components) > 0 { - fqen := strings.Join(append(components, name), ".") - if e, ok := r.enums[fqen]; ok { - return e, nil - } - components = components[:len(components)-1] - } - return nil, fmt.Errorf("no enum found: %s", name) -} - -// LookupFile looks up a file by name. -func (r *Registry) LookupFile(name string) (*File, error) { - f, ok := r.files[name] - if !ok { - return nil, fmt.Errorf("no such file given: %s", name) - } - return f, nil -} - -// LookupExternalHTTPRules looks up external http rules by fully qualified service method name -func (r *Registry) LookupExternalHTTPRules(qualifiedMethodName string) []*annotations.HttpRule { - return r.externalHTTPRules[qualifiedMethodName] -} - -// AddExternalHTTPRule adds an external http rule for the given fully qualified service method name -func (r *Registry) AddExternalHTTPRule(qualifiedMethodName string, rule *annotations.HttpRule) { - r.externalHTTPRules[qualifiedMethodName] = append(r.externalHTTPRules[qualifiedMethodName], rule) -} - -// AddPkgMap adds a mapping from a .proto file to proto package name. -func (r *Registry) AddPkgMap(file, protoPkg string) { - r.pkgMap[file] = protoPkg -} - -// SetPrefix registers the prefix to be added to go package paths generated from proto package names. -func (r *Registry) SetPrefix(prefix string) { - r.prefix = prefix -} - -// SetImportPath registers the importPath which is used as the package if no -// input files declare go_package. If it contains slashes, everything up to the -// rightmost slash is ignored. -func (r *Registry) SetImportPath(importPath string) { - r.importPath = importPath -} - -// ReserveGoPackageAlias reserves the unique alias of go package. -// If succeeded, the alias will be never used for other packages in generated go files. -// If failed, the alias is already taken by another package, so you need to use another -// alias for the package in your go files. -func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error { - if taken, ok := r.pkgAliases[alias]; ok { - if taken == pkgpath { - return nil - } - return fmt.Errorf("package name %s is already taken. Use another alias", alias) - } - r.pkgAliases[alias] = pkgpath - return nil -} - -// goPackagePath returns the go package path which go files generated from "f" should have. -// It respects the mapping registered by AddPkgMap if exists. Or use go_package as import path -// if it includes a slash, Otherwide, it generates a path from the file name of "f". -func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string { - name := f.GetName() - if pkg, ok := r.pkgMap[name]; ok { - return path.Join(r.prefix, pkg) - } - - gopkg := f.Options.GetGoPackage() - idx := strings.LastIndex(gopkg, "/") - if idx >= 0 { - if sc := strings.LastIndex(gopkg, ";"); sc > 0 { - gopkg = gopkg[:sc+1-1] - } - return gopkg - } - - return path.Join(r.prefix, path.Dir(name)) -} - -// GetAllFQMNs returns a list of all FQMNs -func (r *Registry) GetAllFQMNs() []string { - var keys []string - for k := range r.msgs { - keys = append(keys, k) - } - return keys -} - -// GetAllFQENs returns a list of all FQENs -func (r *Registry) GetAllFQENs() []string { - var keys []string - for k := range r.enums { - keys = append(keys, k) - } - return keys -} - -// SetAllowDeleteBody controls whether http delete methods may have a -// body or fail loading if encountered. -func (r *Registry) SetAllowDeleteBody(allow bool) { - r.allowDeleteBody = allow -} - -// SetAllowMerge controls whether generation one swagger file out of multiple protos -func (r *Registry) SetAllowMerge(allow bool) { - r.allowMerge = allow -} - -// IsAllowMerge whether generation one swagger file out of multiple protos -func (r *Registry) IsAllowMerge() bool { - return r.allowMerge -} - -// SetMergeFileName controls the target swagger file name out of multiple protos -func (r *Registry) SetMergeFileName(mergeFileName string) { - r.mergeFileName = mergeFileName -} - -// GetMergeFileName return the target merge swagger file name -func (r *Registry) GetMergeFileName() string { - return r.mergeFileName -} - -// sanitizePackageName replaces unallowed character in package name -// with allowed character. -func sanitizePackageName(pkgName string) string { - pkgName = strings.Replace(pkgName, ".", "_", -1) - pkgName = strings.Replace(pkgName, "-", "_", -1) - return pkgName -} - -// defaultGoPackageName returns the default go package name to be used for go files generated from "f". -// You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias. -func (r *Registry) defaultGoPackageName(f *descriptor.FileDescriptorProto) string { - name := r.packageIdentityName(f) - return sanitizePackageName(name) -} - -// packageIdentityName returns the identity of packages. -// protoc-gen-grpc-gateway rejects CodeGenerationRequests which contains more than one packages -// as protoc-gen-go does. -func (r *Registry) packageIdentityName(f *descriptor.FileDescriptorProto) string { - if f.Options != nil && f.Options.GoPackage != nil { - gopkg := f.Options.GetGoPackage() - idx := strings.LastIndex(gopkg, "/") - if idx < 0 { - gopkg = gopkg[idx+1:] - } - - gopkg = gopkg[idx+1:] - // package name is overrided with the string after the - // ';' character - sc := strings.IndexByte(gopkg, ';') - if sc < 0 { - return sanitizePackageName(gopkg) - - } - return sanitizePackageName(gopkg[sc+1:]) - } - if p := r.importPath; len(p) != 0 { - if i := strings.LastIndex(p, "/"); i >= 0 { - p = p[i+1:] - } - return p - } - - if f.Package == nil { - base := filepath.Base(f.GetName()) - ext := filepath.Ext(base) - return strings.TrimSuffix(base, ext) - } - return f.GetPackage() -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry_test.go deleted file mode 100755 index 16e7665..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry_test.go +++ /dev/null @@ -1,588 +0,0 @@ -package descriptor - -import ( - "testing" - - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" -) - -func loadFile(t *testing.T, reg *Registry, src string) *descriptor.FileDescriptorProto { - var file descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &file); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) - } - reg.loadFile(&file) - return &file -} - -func load(t *testing.T, reg *Registry, src string) error { - var req plugin.CodeGeneratorRequest - if err := proto.UnmarshalText(src, &req); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &file) failed with %v; want success", src, err) - } - return reg.Load(&req) -} - -func TestLoadFile(t *testing.T) { - reg := NewRegistry() - fd := loadFile(t, reg, ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'str' - label: LABEL_OPTIONAL - type: TYPE_STRING - number: 1 - > - > - `) - - file := reg.files["example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: ".", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } - - msg, err := reg.LookupMsg("", ".example.ExampleMessage") - if err != nil { - t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", "", ".example.ExampleMessage", err) - return - } - if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { - t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", "", ".example.ExampleMessage", got, want) - } - if got, want := msg.File, file; got != want { - t.Errorf("msg.File = %v; want %v", got, want) - } - if got := msg.Outers; got != nil { - t.Errorf("msg.Outers = %v; want %v", got, nil) - } - if got, want := len(msg.Fields), 1; got != want { - t.Errorf("len(msg.Fields) = %d; want %d", got, want) - } else if got, want := msg.Fields[0].FieldDescriptorProto, fd.MessageType[0].Field[0]; got != want { - t.Errorf("msg.Fields[0].FieldDescriptorProto = %v; want %v", got, want) - } else if got, want := msg.Fields[0].Message, msg; got != want { - t.Errorf("msg.Fields[0].Message = %v; want %v", got, want) - } - - if got, want := len(file.Messages), 1; got != want { - t.Errorf("file.Meeesages = %#v; want %#v", file.Messages, []*Message{msg}) - } - if got, want := file.Messages[0], msg; got != want { - t.Errorf("file.Meeesages[0] = %v; want %v", got, want) - } -} - -func TestLoadFileNestedPackage(t *testing.T) { - reg := NewRegistry() - loadFile(t, reg, ` - name: 'example.proto' - package: 'example.nested.nested2' - `) - - file := reg.files["example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: ".", Name: "example_nested_nested2"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithDir(t *testing.T) { - reg := NewRegistry() - loadFile(t, reg, ` - name: 'path/to/example.proto' - package: 'example' - `) - - file := reg.files["path/to/example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "path/to", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithoutPackage(t *testing.T) { - reg := NewRegistry() - loadFile(t, reg, ` - name: 'path/to/example_file.proto' - `) - - file := reg.files["path/to/example_file.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "path/to", Name: "example_file"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithMapping(t *testing.T) { - reg := NewRegistry() - reg.AddPkgMap("path/to/example.proto", "example.com/proj/example/proto") - loadFile(t, reg, ` - name: 'path/to/example.proto' - package: 'example' - `) - - file := reg.files["path/to/example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "example.com/proj/example/proto", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithPackageNameCollision(t *testing.T) { - reg := NewRegistry() - loadFile(t, reg, ` - name: 'path/to/another.proto' - package: 'example' - `) - loadFile(t, reg, ` - name: 'path/to/example.proto' - package: 'example' - `) - if err := reg.ReserveGoPackageAlias("ioutil", "io/ioutil"); err != nil { - t.Fatalf("reg.ReserveGoPackageAlias(%q) failed with %v; want success", "ioutil", err) - } - loadFile(t, reg, ` - name: 'path/to/ioutil.proto' - package: 'ioutil' - `) - - file := reg.files["path/to/another.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/another.proto") - return - } - wantPkg := GoPackage{Path: "path/to", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } - - file = reg.files["path/to/example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/example.proto") - return - } - wantPkg = GoPackage{Path: "path/to", Name: "example", Alias: ""} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } - - file = reg.files["path/to/ioutil.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "path/to/ioutil.proto") - return - } - wantPkg = GoPackage{Path: "path/to", Name: "ioutil", Alias: "ioutil_0"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithIdenticalGoPkg(t *testing.T) { - reg := NewRegistry() - reg.AddPkgMap("path/to/another.proto", "example.com/example") - reg.AddPkgMap("path/to/example.proto", "example.com/example") - loadFile(t, reg, ` - name: 'path/to/another.proto' - package: 'example' - `) - loadFile(t, reg, ` - name: 'path/to/example.proto' - package: 'example' - `) - - file := reg.files["path/to/example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "example.com/example", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } - - file = reg.files["path/to/another.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg = GoPackage{Path: "example.com/example", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadFileWithPrefix(t *testing.T) { - reg := NewRegistry() - reg.SetPrefix("third_party") - loadFile(t, reg, ` - name: 'path/to/example.proto' - package: 'example' - `) - - file := reg.files["path/to/example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "third_party/path/to", Name: "example"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLookupMsgWithoutPackage(t *testing.T) { - reg := NewRegistry() - fd := loadFile(t, reg, ` - name: 'example.proto' - message_type < - name: 'ExampleMessage' - field < - name: 'str' - label: LABEL_OPTIONAL - type: TYPE_STRING - number: 1 - > - > - `) - - msg, err := reg.LookupMsg("", ".ExampleMessage") - if err != nil { - t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", "", ".ExampleMessage", err) - return - } - if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { - t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", "", ".ExampleMessage", got, want) - } -} - -func TestLookupMsgWithNestedPackage(t *testing.T) { - reg := NewRegistry() - fd := loadFile(t, reg, ` - name: 'example.proto' - package: 'nested.nested2.mypackage' - message_type < - name: 'ExampleMessage' - field < - name: 'str' - label: LABEL_OPTIONAL - type: TYPE_STRING - number: 1 - > - > - `) - - for _, name := range []string{ - "nested.nested2.mypackage.ExampleMessage", - "nested2.mypackage.ExampleMessage", - "mypackage.ExampleMessage", - "ExampleMessage", - } { - msg, err := reg.LookupMsg("nested.nested2.mypackage", name) - if err != nil { - t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", ".nested.nested2.mypackage", name, err) - return - } - if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { - t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", ".nested.nested2.mypackage", name, got, want) - } - } - - for _, loc := range []string{ - ".nested.nested2.mypackage", - "nested.nested2.mypackage", - ".nested.nested2", - "nested.nested2", - ".nested", - "nested", - ".", - "", - "somewhere.else", - } { - name := "nested.nested2.mypackage.ExampleMessage" - msg, err := reg.LookupMsg(loc, name) - if err != nil { - t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", loc, name, err) - return - } - if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { - t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", loc, name, got, want) - } - } - - for _, loc := range []string{ - ".nested.nested2.mypackage", - "nested.nested2.mypackage", - ".nested.nested2", - "nested.nested2", - ".nested", - "nested", - } { - name := "nested2.mypackage.ExampleMessage" - msg, err := reg.LookupMsg(loc, name) - if err != nil { - t.Errorf("reg.LookupMsg(%q, %q)) failed with %v; want success", loc, name, err) - return - } - if got, want := msg.DescriptorProto, fd.MessageType[0]; got != want { - t.Errorf("reg.lookupMsg(%q, %q).DescriptorProto = %#v; want %#v", loc, name, got, want) - } - } -} - -func TestLoadWithInconsistentTargetPackage(t *testing.T) { - for _, spec := range []struct { - req string - consistent bool - }{ - // root package, no explicit go package - { - req: ` - file_to_generate: 'a.proto' - file_to_generate: 'b.proto' - proto_file < - name: 'a.proto' - message_type < name: 'A' > - service < - name: "AService" - method < - name: "Meth" - input_type: "A" - output_type: "A" - options < - [google.api.http] < post: "/v1/a" body: "*" > - > - > - > - > - proto_file < - name: 'b.proto' - message_type < name: 'B' > - service < - name: "BService" - method < - name: "Meth" - input_type: "B" - output_type: "B" - options < - [google.api.http] < post: "/v1/b" body: "*" > - > - > - > - > - `, - consistent: false, - }, - // named package, no explicit go package - { - req: ` - file_to_generate: 'a.proto' - file_to_generate: 'b.proto' - proto_file < - name: 'a.proto' - package: 'example.foo' - message_type < name: 'A' > - service < - name: "AService" - method < - name: "Meth" - input_type: "A" - output_type: "A" - options < - [google.api.http] < post: "/v1/a" body: "*" > - > - > - > - > - proto_file < - name: 'b.proto' - package: 'example.foo' - message_type < name: 'B' > - service < - name: "BService" - method < - name: "Meth" - input_type: "B" - output_type: "B" - options < - [google.api.http] < post: "/v1/b" body: "*" > - > - > - > - > - `, - consistent: true, - }, - // root package, explicit go package - { - req: ` - file_to_generate: 'a.proto' - file_to_generate: 'b.proto' - proto_file < - name: 'a.proto' - options < go_package: 'foo' > - message_type < name: 'A' > - service < - name: "AService" - method < - name: "Meth" - input_type: "A" - output_type: "A" - options < - [google.api.http] < post: "/v1/a" body: "*" > - > - > - > - > - proto_file < - name: 'b.proto' - options < go_package: 'foo' > - message_type < name: 'B' > - service < - name: "BService" - method < - name: "Meth" - input_type: "B" - output_type: "B" - options < - [google.api.http] < post: "/v1/b" body: "*" > - > - > - > - > - `, - consistent: true, - }, - // named package, explicit go package - { - req: ` - file_to_generate: 'a.proto' - file_to_generate: 'b.proto' - proto_file < - name: 'a.proto' - package: 'example.foo' - options < go_package: 'foo' > - message_type < name: 'A' > - service < - name: "AService" - method < - name: "Meth" - input_type: "A" - output_type: "A" - options < - [google.api.http] < post: "/v1/a" body: "*" > - > - > - > - > - proto_file < - name: 'b.proto' - package: 'example.foo' - options < go_package: 'foo' > - message_type < name: 'B' > - service < - name: "BService" - method < - name: "Meth" - input_type: "B" - output_type: "B" - options < - [google.api.http] < post: "/v1/b" body: "*" > - > - > - > - > - `, - consistent: true, - }, - } { - reg := NewRegistry() - err := load(t, reg, spec.req) - if got, want := err == nil, spec.consistent; got != want { - if want { - t.Errorf("reg.Load(%s) failed with %v; want success", spec.req, err) - continue - } - t.Errorf("reg.Load(%s) succeeded; want an package inconsistency error", spec.req) - } - } -} - -func TestLoadOverridedPackageName(t *testing.T) { - reg := NewRegistry() - loadFile(t, reg, ` - name: 'example.proto' - package: 'example' - options < go_package: 'example.com/xyz;pb' > - `) - file := reg.files["example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "example.com/xyz", Name: "pb"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadSetInputPath(t *testing.T) { - reg := NewRegistry() - reg.SetImportPath("foo/examplepb") - loadFile(t, reg, ` - name: 'example.proto' - package: 'example' - `) - file := reg.files["example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: ".", Name: "examplepb"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} - -func TestLoadGoPackageInputPath(t *testing.T) { - reg := NewRegistry() - reg.SetImportPath("examplepb") - loadFile(t, reg, ` - name: 'example.proto' - package: 'example' - options < go_package: 'example.com/xyz;pb' > - `) - file := reg.files["example.proto"] - if file == nil { - t.Errorf("reg.files[%q] = nil; want non-nil", "example.proto") - return - } - wantPkg := GoPackage{Path: "example.com/xyz", Name: "pb"} - if got, want := file.GoPkg, wantPkg; got != want { - t.Errorf("file.GoPkg = %#v; want %#v", got, want) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go deleted file mode 100755 index c200e57..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go +++ /dev/null @@ -1,286 +0,0 @@ -package descriptor - -import ( - "fmt" - "strings" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" - options "google.golang.org/genproto/googleapis/api/annotations" -) - -// loadServices registers services and their methods from "targetFile" to "r". -// It must be called after loadFile is called for all files so that loadServices -// can resolve names of message types and their fields. -func (r *Registry) loadServices(file *File) error { - glog.V(1).Infof("Loading services from %s", file.GetName()) - var svcs []*Service - for _, sd := range file.GetService() { - glog.V(2).Infof("Registering %s", sd.GetName()) - svc := &Service{ - File: file, - ServiceDescriptorProto: sd, - } - for _, md := range sd.GetMethod() { - glog.V(2).Infof("Processing %s.%s", sd.GetName(), md.GetName()) - opts, err := extractAPIOptions(md) - if err != nil { - glog.Errorf("Failed to extract HttpRule from %s.%s: %v", svc.GetName(), md.GetName(), err) - return err - } - optsList := r.LookupExternalHTTPRules((&Method{Service: svc, MethodDescriptorProto: md}).FQMN()) - if opts != nil { - optsList = append(optsList, opts) - } - if len(optsList) == 0 { - glog.V(1).Infof("Found non-target method: %s.%s", svc.GetName(), md.GetName()) - } - meth, err := r.newMethod(svc, md, optsList) - if err != nil { - return err - } - svc.Methods = append(svc.Methods, meth) - } - if len(svc.Methods) == 0 { - continue - } - glog.V(2).Infof("Registered %s with %d method(s)", svc.GetName(), len(svc.Methods)) - svcs = append(svcs, svc) - } - file.Services = svcs - return nil -} - -func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, optsList []*options.HttpRule) (*Method, error) { - requestType, err := r.LookupMsg(svc.File.GetPackage(), md.GetInputType()) - if err != nil { - return nil, err - } - responseType, err := r.LookupMsg(svc.File.GetPackage(), md.GetOutputType()) - if err != nil { - return nil, err - } - meth := &Method{ - Service: svc, - MethodDescriptorProto: md, - RequestType: requestType, - ResponseType: responseType, - } - - newBinding := func(opts *options.HttpRule, idx int) (*Binding, error) { - var ( - httpMethod string - pathTemplate string - ) - switch { - case opts.GetGet() != "": - httpMethod = "GET" - pathTemplate = opts.GetGet() - if opts.Body != "" { - return nil, fmt.Errorf("must not set request body when http method is GET: %s", md.GetName()) - } - - case opts.GetPut() != "": - httpMethod = "PUT" - pathTemplate = opts.GetPut() - - case opts.GetPost() != "": - httpMethod = "POST" - pathTemplate = opts.GetPost() - - case opts.GetDelete() != "": - httpMethod = "DELETE" - pathTemplate = opts.GetDelete() - if opts.Body != "" && !r.allowDeleteBody { - return nil, fmt.Errorf("must not set request body when http method is DELETE except allow_delete_body option is true: %s", md.GetName()) - } - - case opts.GetPatch() != "": - httpMethod = "PATCH" - pathTemplate = opts.GetPatch() - - case opts.GetCustom() != nil: - custom := opts.GetCustom() - httpMethod = custom.Kind - pathTemplate = custom.Path - - default: - glog.V(1).Infof("No pattern specified in google.api.HttpRule: %s", md.GetName()) - return nil, nil - } - - parsed, err := httprule.Parse(pathTemplate) - if err != nil { - return nil, err - } - tmpl := parsed.Compile() - - if md.GetClientStreaming() && len(tmpl.Fields) > 0 { - return nil, fmt.Errorf("cannot use path parameter in client streaming") - } - - b := &Binding{ - Method: meth, - Index: idx, - PathTmpl: tmpl, - HTTPMethod: httpMethod, - } - - for _, f := range tmpl.Fields { - param, err := r.newParam(meth, f) - if err != nil { - return nil, err - } - b.PathParams = append(b.PathParams, param) - } - - // TODO(yugui) Handle query params - - b.Body, err = r.newBody(meth, opts.Body) - if err != nil { - return nil, err - } - - return b, nil - } - - applyOpts := func(opts *options.HttpRule) error { - b, err := newBinding(opts, len(meth.Bindings)) - if err != nil { - return err - } - - if b != nil { - meth.Bindings = append(meth.Bindings, b) - } - for _, additional := range opts.GetAdditionalBindings() { - if len(additional.AdditionalBindings) > 0 { - return fmt.Errorf("additional_binding in additional_binding not allowed: %s.%s", svc.GetName(), meth.GetName()) - } - b, err := newBinding(additional, len(meth.Bindings)) - if err != nil { - return err - } - meth.Bindings = append(meth.Bindings, b) - } - - return nil - } - - for _, opts := range optsList { - if err := applyOpts(opts); err != nil { - return nil, err - } - } - - return meth, nil -} - -func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRule, error) { - if meth.Options == nil { - return nil, nil - } - if !proto.HasExtension(meth.Options, options.E_Http) { - return nil, nil - } - ext, err := proto.GetExtension(meth.Options, options.E_Http) - if err != nil { - return nil, err - } - opts, ok := ext.(*options.HttpRule) - if !ok { - return nil, fmt.Errorf("extension is %T; want an HttpRule", ext) - } - return opts, nil -} - -func (r *Registry) newParam(meth *Method, path string) (Parameter, error) { - msg := meth.RequestType - fields, err := r.resolveFieldPath(msg, path) - if err != nil { - return Parameter{}, err - } - l := len(fields) - if l == 0 { - return Parameter{}, fmt.Errorf("invalid field access list for %s", path) - } - target := fields[l-1].Target - switch target.GetType() { - case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: - glog.V(2).Infoln("found aggregate type:", target, target.TypeName) - if IsWellKnownType(*target.TypeName) { - glog.V(2).Infoln("found well known aggregate type:", target) - } else { - return Parameter{}, fmt.Errorf("aggregate type %s in parameter of %s.%s: %s", target.Type, meth.Service.GetName(), meth.GetName(), path) - } - } - return Parameter{ - FieldPath: FieldPath(fields), - Method: meth, - Target: fields[l-1].Target, - }, nil -} - -func (r *Registry) newBody(meth *Method, path string) (*Body, error) { - msg := meth.RequestType - switch path { - case "": - return nil, nil - case "*": - return &Body{FieldPath: nil}, nil - } - fields, err := r.resolveFieldPath(msg, path) - if err != nil { - return nil, err - } - return &Body{FieldPath: FieldPath(fields)}, nil -} - -// lookupField looks up a field named "name" within "msg". -// It returns nil if no such field found. -func lookupField(msg *Message, name string) *Field { - for _, f := range msg.Fields { - if f.GetName() == name { - return f - } - } - return nil -} - -// resolveFieldPath resolves "path" into a list of fieldDescriptor, starting from "msg". -func (r *Registry) resolveFieldPath(msg *Message, path string) ([]FieldPathComponent, error) { - if path == "" { - return nil, nil - } - - root := msg - var result []FieldPathComponent - for i, c := range strings.Split(path, ".") { - if i > 0 { - f := result[i-1].Target - switch f.GetType() { - case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP: - var err error - msg, err = r.LookupMsg(msg.FQMN(), f.GetTypeName()) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("not an aggregate type: %s in %s", f.GetName(), path) - } - } - - glog.V(2).Infof("Lookup %s in %s", c, msg.FQMN()) - f := lookupField(msg, c) - if f == nil { - return nil, fmt.Errorf("no field %q found in %s", path, root.GetName()) - } - if f.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED { - return nil, fmt.Errorf("repeated field not allowed in field path: %s in %s", f.GetName(), path) - } - result = append(result, FieldPathComponent{Name: c, Target: f}) - } - return result, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services_test.go deleted file mode 100755 index 93a8f67..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services_test.go +++ /dev/null @@ -1,1210 +0,0 @@ -package descriptor - -import ( - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" -) - -func compilePath(t *testing.T, path string) httprule.Template { - parsed, err := httprule.Parse(path) - if err != nil { - t.Fatalf("httprule.Parse(%q) failed with %v; want success", path, err) - } - return parsed.Compile() -} - -func testExtractServices(t *testing.T, input []*descriptor.FileDescriptorProto, target string, wantSvcs []*Service) { - reg := NewRegistry() - for _, file := range input { - reg.loadFile(file) - } - err := reg.loadServices(reg.files[target]) - if err != nil { - t.Errorf("loadServices(%q) failed with %v; want success; files=%v", target, err, input) - } - - file := reg.files[target] - svcs := file.Services - var i int - for i = 0; i < len(svcs) && i < len(wantSvcs); i++ { - svc, wantSvc := svcs[i], wantSvcs[i] - if got, want := svc.ServiceDescriptorProto, wantSvc.ServiceDescriptorProto; !proto.Equal(got, want) { - t.Errorf("svcs[%d].ServiceDescriptorProto = %v; want %v; input = %v", i, got, want, input) - continue - } - var j int - for j = 0; j < len(svc.Methods) && j < len(wantSvc.Methods); j++ { - meth, wantMeth := svc.Methods[j], wantSvc.Methods[j] - if got, want := meth.MethodDescriptorProto, wantMeth.MethodDescriptorProto; !proto.Equal(got, want) { - t.Errorf("svcs[%d].Methods[%d].MethodDescriptorProto = %v; want %v; input = %v", i, j, got, want, input) - continue - } - if got, want := meth.RequestType, wantMeth.RequestType; got.FQMN() != want.FQMN() { - t.Errorf("svcs[%d].Methods[%d].RequestType = %s; want %s; input = %v", i, j, got.FQMN(), want.FQMN(), input) - } - if got, want := meth.ResponseType, wantMeth.ResponseType; got.FQMN() != want.FQMN() { - t.Errorf("svcs[%d].Methods[%d].ResponseType = %s; want %s; input = %v", i, j, got.FQMN(), want.FQMN(), input) - } - var k int - for k = 0; k < len(meth.Bindings) && k < len(wantMeth.Bindings); k++ { - binding, wantBinding := meth.Bindings[k], wantMeth.Bindings[k] - if got, want := binding.Index, wantBinding.Index; got != want { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Index = %d; want %d; input = %v", i, j, k, got, want, input) - } - if got, want := binding.PathTmpl, wantBinding.PathTmpl; !reflect.DeepEqual(got, want) { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathTmpl = %#v; want %#v; input = %v", i, j, k, got, want, input) - } - if got, want := binding.HTTPMethod, wantBinding.HTTPMethod; got != want { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].HTTPMethod = %q; want %q; input = %v", i, j, k, got, want, input) - } - - var l int - for l = 0; l < len(binding.PathParams) && l < len(wantBinding.PathParams); l++ { - param, wantParam := binding.PathParams[l], wantBinding.PathParams[l] - if got, want := param.FieldPath.String(), wantParam.FieldPath.String(); got != want { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d].FieldPath.String() = %q; want %q; input = %v", i, j, k, l, got, want, input) - continue - } - for m := 0; m < len(param.FieldPath) && m < len(wantParam.FieldPath); m++ { - field, wantField := param.FieldPath[m].Target, wantParam.FieldPath[m].Target - if got, want := field.FieldDescriptorProto, wantField.FieldDescriptorProto; !proto.Equal(got, want) { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d].FieldPath[%d].Target.FieldDescriptorProto = %v; want %v; input = %v", i, j, k, l, m, got, want, input) - } - } - } - for ; l < len(binding.PathParams); l++ { - got := binding.PathParams[l].FieldPath.String() - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d] = %q; want it to be missing; input = %v", i, j, k, l, got, input) - } - for ; l < len(wantBinding.PathParams); l++ { - want := wantBinding.PathParams[l].FieldPath.String() - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].PathParams[%d] missing; want %q; input = %v", i, j, k, l, want, input) - } - - if got, want := (binding.Body != nil), (wantBinding.Body != nil); got != want { - if got { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body = %q; want it to be missing; input = %v", i, j, k, binding.Body.FieldPath.String(), input) - } else { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body missing; want %q; input = %v", i, j, k, wantBinding.Body.FieldPath.String(), input) - } - } else if binding.Body != nil { - if got, want := binding.Body.FieldPath.String(), wantBinding.Body.FieldPath.String(); got != want { - t.Errorf("svcs[%d].Methods[%d].Bindings[%d].Body = %q; want %q; input = %v", i, j, k, got, want, input) - } - } - } - for ; k < len(meth.Bindings); k++ { - got := meth.Bindings[k] - t.Errorf("svcs[%d].Methods[%d].Bindings[%d] = %q; want it to be missing; input = %v", i, j, k, got, input) - } - for ; k < len(wantMeth.Bindings); k++ { - want := wantMeth.Bindings[k] - t.Errorf("svcs[%d].Methods[%d].Bindings[%d] missing; want %q; input = %v", i, j, k, want, input) - } - } - for ; j < len(svc.Methods); j++ { - got := svc.Methods[j].MethodDescriptorProto - t.Errorf("svcs[%d].Methods[%d] = %v; want it to be missing; input = %v", i, j, got, input) - } - for ; j < len(wantSvc.Methods); j++ { - want := wantSvc.Methods[j].MethodDescriptorProto - t.Errorf("svcs[%d].Methods[%d] missing; want %v; input = %v", i, j, want, input) - } - } - for ; i < len(svcs); i++ { - got := svcs[i].ServiceDescriptorProto - t.Errorf("svcs[%d] = %v; want it to be missing; input = %v", i, got, input) - } - for ; i < len(wantSvcs); i++ { - want := wantSvcs[i].ServiceDescriptorProto - t.Errorf("svcs[%d] missing; want %v; input = %v", i, want, input) - } -} - -func crossLinkFixture(f *File) *File { - for _, m := range f.Messages { - m.File = f - for _, f := range m.Fields { - f.Message = m - } - } - for _, svc := range f.Services { - svc.File = f - for _, m := range svc.Methods { - m.Service = svc - for _, b := range m.Bindings { - b.Method = m - for _, param := range b.PathParams { - param.Method = m - } - } - } - } - return f -} - -func TestExtractServicesSimple(t *testing.T) { - src := ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo" - body: "*" - > - > - > - > - ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - msg := &Message{ - DescriptorProto: fd.MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fd.MessageType[0].Field[0], - }, - }, - } - file := &File{ - FileDescriptorProto: &fd, - GoPkg: GoPackage{ - Path: "path/to/example.pb", - Name: "example_pb", - }, - Messages: []*Message{msg}, - Services: []*Service{ - { - ServiceDescriptorProto: fd.Service[0], - Methods: []*Method{ - { - MethodDescriptorProto: fd.Service[0].Method[0], - RequestType: msg, - ResponseType: msg, - Bindings: []*Binding{ - { - PathTmpl: compilePath(t, "/v1/example/echo"), - HTTPMethod: "POST", - Body: &Body{FieldPath: nil}, - }, - }, - }, - }, - }, - }, - } - - crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) -} - -func TestExtractServicesCrossPackage(t *testing.T) { - srcs := []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "ToString" - input_type: ".another.example.BoolMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/to_s" - body: "*" - > - > - > - > - `, ` - name: "path/to/another/example.proto", - package: "another.example" - message_type < - name: "BoolMessage" - field < - name: "bool" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_BOOL - > - > - `, - } - var fds []*descriptor.FileDescriptorProto - for _, src := range srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - fds = append(fds, &fd) - } - stringMsg := &Message{ - DescriptorProto: fds[0].MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fds[0].MessageType[0].Field[0], - }, - }, - } - boolMsg := &Message{ - DescriptorProto: fds[1].MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fds[1].MessageType[0].Field[0], - }, - }, - } - files := []*File{ - { - FileDescriptorProto: fds[0], - GoPkg: GoPackage{ - Path: "path/to/example.pb", - Name: "example_pb", - }, - Messages: []*Message{stringMsg}, - Services: []*Service{ - { - ServiceDescriptorProto: fds[0].Service[0], - Methods: []*Method{ - { - MethodDescriptorProto: fds[0].Service[0].Method[0], - RequestType: boolMsg, - ResponseType: stringMsg, - Bindings: []*Binding{ - { - PathTmpl: compilePath(t, "/v1/example/to_s"), - HTTPMethod: "POST", - Body: &Body{FieldPath: nil}, - }, - }, - }, - }, - }, - }, - }, - { - FileDescriptorProto: fds[1], - GoPkg: GoPackage{ - Path: "path/to/another/example.pb", - Name: "example_pb", - }, - Messages: []*Message{boolMsg}, - }, - } - - for _, file := range files { - crossLinkFixture(file) - } - testExtractServices(t, fds, "path/to/example.proto", files[0].Services) -} - -func TestExtractServicesWithBodyPath(t *testing.T) { - src := ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "OuterMessage" - nested_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - field < - name: "nested" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: "StringMessage" - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "OuterMessage" - output_type: "OuterMessage" - options < - [google.api.http] < - post: "/v1/example/echo" - body: "nested" - > - > - > - > - ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - msg := &Message{ - DescriptorProto: fd.MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fd.MessageType[0].Field[0], - }, - }, - } - file := &File{ - FileDescriptorProto: &fd, - GoPkg: GoPackage{ - Path: "path/to/example.pb", - Name: "example_pb", - }, - Messages: []*Message{msg}, - Services: []*Service{ - { - ServiceDescriptorProto: fd.Service[0], - Methods: []*Method{ - { - MethodDescriptorProto: fd.Service[0].Method[0], - RequestType: msg, - ResponseType: msg, - Bindings: []*Binding{ - { - PathTmpl: compilePath(t, "/v1/example/echo"), - HTTPMethod: "POST", - Body: &Body{ - FieldPath: FieldPath{ - { - Name: "nested", - Target: msg.Fields[0], - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) -} - -func TestExtractServicesWithPathParam(t *testing.T) { - src := ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - get: "/v1/example/echo/{string=*}" - > - > - > - > - ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - msg := &Message{ - DescriptorProto: fd.MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fd.MessageType[0].Field[0], - }, - }, - } - file := &File{ - FileDescriptorProto: &fd, - GoPkg: GoPackage{ - Path: "path/to/example.pb", - Name: "example_pb", - }, - Messages: []*Message{msg}, - Services: []*Service{ - { - ServiceDescriptorProto: fd.Service[0], - Methods: []*Method{ - { - MethodDescriptorProto: fd.Service[0].Method[0], - RequestType: msg, - ResponseType: msg, - Bindings: []*Binding{ - { - PathTmpl: compilePath(t, "/v1/example/echo/{string=*}"), - HTTPMethod: "GET", - PathParams: []Parameter{ - { - FieldPath: FieldPath{ - { - Name: "string", - Target: msg.Fields[0], - }, - }, - Target: msg.Fields[0], - }, - }, - }, - }, - }, - }, - }, - }, - } - - crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) -} - -func TestExtractServicesWithAdditionalBinding(t *testing.T) { - src := ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo" - body: "*" - additional_bindings < - get: "/v1/example/echo/{string}" - > - additional_bindings < - post: "/v2/example/echo" - body: "string" - > - > - > - > - > - ` - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - msg := &Message{ - DescriptorProto: fd.MessageType[0], - Fields: []*Field{ - { - FieldDescriptorProto: fd.MessageType[0].Field[0], - }, - }, - } - file := &File{ - FileDescriptorProto: &fd, - GoPkg: GoPackage{ - Path: "path/to/example.pb", - Name: "example_pb", - }, - Messages: []*Message{msg}, - Services: []*Service{ - { - ServiceDescriptorProto: fd.Service[0], - Methods: []*Method{ - { - MethodDescriptorProto: fd.Service[0].Method[0], - RequestType: msg, - ResponseType: msg, - Bindings: []*Binding{ - { - Index: 0, - PathTmpl: compilePath(t, "/v1/example/echo"), - HTTPMethod: "POST", - Body: &Body{FieldPath: nil}, - }, - { - Index: 1, - PathTmpl: compilePath(t, "/v1/example/echo/{string}"), - HTTPMethod: "GET", - PathParams: []Parameter{ - { - FieldPath: FieldPath{ - { - Name: "string", - Target: msg.Fields[0], - }, - }, - Target: msg.Fields[0], - }, - }, - Body: nil, - }, - { - Index: 2, - PathTmpl: compilePath(t, "/v2/example/echo"), - HTTPMethod: "POST", - Body: &Body{ - FieldPath: FieldPath{ - FieldPathComponent{ - Name: "string", - Target: msg.Fields[0], - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - crossLinkFixture(file) - testExtractServices(t, []*descriptor.FileDescriptorProto{&fd}, "path/to/example.proto", file.Services) -} - -func TestExtractServicesWithError(t *testing.T) { - for _, spec := range []struct { - target string - srcs []string - }{ - { - target: "path/to/example.proto", - srcs: []string{ - // message not found - ` - name: "path/to/example.proto", - package: "example" - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo" - body: "*" - > - > - > - > - `, - }, - }, - // body field path not resolved - { - target: "path/to/example.proto", - srcs: []string{` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo" - body: "bool" - > - > - > - >`, - }, - }, - // param field path not resolved - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo/{bool=*}" - > - > - > - > - `, - }, - }, - // non aggregate type on field path - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "OuterMessage" - field < - name: "mid" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - field < - name: "bool" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_BOOL - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "OuterMessage" - output_type: "OuterMessage" - options < - [google.api.http] < - post: "/v1/example/echo/{mid.bool=*}" - > - > - > - > - `, - }, - }, - // path param in client streaming - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - post: "/v1/example/echo/{bool=*}" - > - > - client_streaming: true - > - > - `, - }, - }, - // body for GET - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - get: "/v1/example/echo" - body: "string" - > - > - > - > - `, - }, - }, - // body for DELETE - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "RemoveResource" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - delete: "/v1/example/resource" - body: "string" - > - > - > - > - `, - }, - }, - // no pattern specified - { - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - service < - name: "ExampleService" - method < - name: "RemoveResource" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - body: "string" - > - > - > - > - `, - }, - }, - // unsupported path parameter type - { - target: "path/to/example.proto", - srcs: []string{` - name: "path/to/example.proto", - package: "example" - message_type < - name: "OuterMessage" - nested_type < - name: "StringMessage" - field < - name: "value" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: "StringMessage" - > - > - service < - name: "ExampleService" - method < - name: "Echo" - input_type: "OuterMessage" - output_type: "OuterMessage" - options < - [google.api.http] < - get: "/v1/example/echo/{string=*}" - > - > - > - > - `, - }, - }, - } { - reg := NewRegistry() - - var fds []*descriptor.FileDescriptorProto - for _, src := range spec.srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - reg.loadFile(&fd) - fds = append(fds, &fd) - } - err := reg.loadServices(reg.files[spec.target]) - if err == nil { - t.Errorf("loadServices(%q) succeeded; want an error; files=%v", spec.target, spec.srcs) - } - t.Log(err) - } -} - -func TestResolveFieldPath(t *testing.T) { - for _, spec := range []struct { - src string - path string - wantErr bool - }{ - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'string' - type: TYPE_STRING - label: LABEL_OPTIONAL - number: 1 - > - > - `, - path: "string", - wantErr: false, - }, - // no such field - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'string' - type: TYPE_STRING - label: LABEL_OPTIONAL - number: 1 - > - > - `, - path: "something_else", - wantErr: true, - }, - // repeated field - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'string' - type: TYPE_STRING - label: LABEL_REPEATED - number: 1 - > - > - `, - path: "string", - wantErr: true, - }, - // nested field - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'nested' - type: TYPE_MESSAGE - type_name: 'AnotherMessage' - label: LABEL_OPTIONAL - number: 1 - > - field < - name: 'terminal' - type: TYPE_BOOL - label: LABEL_OPTIONAL - number: 2 - > - > - message_type < - name: 'AnotherMessage' - field < - name: 'nested2' - type: TYPE_MESSAGE - type_name: 'ExampleMessage' - label: LABEL_OPTIONAL - number: 1 - > - > - `, - path: "nested.nested2.nested.nested2.nested.nested2.terminal", - wantErr: false, - }, - // non aggregate field on the path - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'nested' - type: TYPE_MESSAGE - type_name: 'AnotherMessage' - label: LABEL_OPTIONAL - number: 1 - > - field < - name: 'terminal' - type: TYPE_BOOL - label: LABEL_OPTIONAL - number: 2 - > - > - message_type < - name: 'AnotherMessage' - field < - name: 'nested2' - type: TYPE_MESSAGE - type_name: 'ExampleMessage' - label: LABEL_OPTIONAL - number: 1 - > - > - `, - path: "nested.terminal.nested2", - wantErr: true, - }, - // repeated field - { - src: ` - name: 'example.proto' - package: 'example' - message_type < - name: 'ExampleMessage' - field < - name: 'nested' - type: TYPE_MESSAGE - type_name: 'AnotherMessage' - label: LABEL_OPTIONAL - number: 1 - > - field < - name: 'terminal' - type: TYPE_BOOL - label: LABEL_OPTIONAL - number: 2 - > - > - message_type < - name: 'AnotherMessage' - field < - name: 'nested2' - type: TYPE_MESSAGE - type_name: 'ExampleMessage' - label: LABEL_REPEATED - number: 1 - > - > - `, - path: "nested.nested2.terminal", - wantErr: true, - }, - } { - var file descriptor.FileDescriptorProto - if err := proto.UnmarshalText(spec.src, &file); err != nil { - t.Fatalf("proto.Unmarshal(%s) failed with %v; want success", spec.src, err) - } - reg := NewRegistry() - reg.loadFile(&file) - f, err := reg.LookupFile(file.GetName()) - if err != nil { - t.Fatalf("reg.LookupFile(%q) failed with %v; want success; on file=%s", file.GetName(), err, spec.src) - } - _, err = reg.resolveFieldPath(f.Messages[0], spec.path) - if got, want := err != nil, spec.wantErr; got != want { - if want { - t.Errorf("reg.resolveFiledPath(%q, %q) succeeded; want an error", f.Messages[0].GetName(), spec.path) - continue - } - t.Errorf("reg.resolveFiledPath(%q, %q) failed with %v; want success", f.Messages[0].GetName(), spec.path, err) - } - } -} - -func TestExtractServicesWithDeleteBody(t *testing.T) { - for _, spec := range []struct { - allowDeleteBody bool - expectErr bool - target string - srcs []string - }{ - // body for DELETE, but registry configured to allow it - { - allowDeleteBody: true, - expectErr: false, - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "RemoveResource" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - delete: "/v1/example/resource" - body: "string" - > - > - > - > - `, - }, - }, - // body for DELETE, registry configured not to allow it - { - allowDeleteBody: false, - expectErr: true, - target: "path/to/example.proto", - srcs: []string{ - ` - name: "path/to/example.proto", - package: "example" - message_type < - name: "StringMessage" - field < - name: "string" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - > - > - service < - name: "ExampleService" - method < - name: "RemoveResource" - input_type: "StringMessage" - output_type: "StringMessage" - options < - [google.api.http] < - delete: "/v1/example/resource" - body: "string" - > - > - > - > - `, - }, - }, - } { - reg := NewRegistry() - reg.SetAllowDeleteBody(spec.allowDeleteBody) - - var fds []*descriptor.FileDescriptorProto - for _, src := range spec.srcs { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - reg.loadFile(&fd) - fds = append(fds, &fd) - } - err := reg.loadServices(reg.files[spec.target]) - if spec.expectErr && err == nil { - t.Errorf("loadServices(%q) succeeded; want an error; allowDeleteBody=%v, files=%v", spec.target, spec.allowDeleteBody, spec.srcs) - } - if !spec.expectErr && err != nil { - t.Errorf("loadServices(%q) failed; do not want an error; allowDeleteBody=%v, files=%v", spec.target, spec.allowDeleteBody, spec.srcs) - } - t.Log(err) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go deleted file mode 100755 index 6346b68..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go +++ /dev/null @@ -1,375 +0,0 @@ -package descriptor - -import ( - "fmt" - "strings" - - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - gogen "github.com/golang/protobuf/protoc-gen-go/generator" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" -) - -// IsWellKnownType returns true if the provided fully qualified type name is considered 'well-known'. -func IsWellKnownType(typeName string) bool { - _, ok := wellKnownTypeConv[typeName] - return ok -} - -// GoPackage represents a golang package -type GoPackage struct { - // Path is the package path to the package. - Path string - // Name is the package name of the package - Name string - // Alias is an alias of the package unique within the current invokation of grpc-gateway generator. - Alias string -} - -// Standard returns whether the import is a golang standard package. -func (p GoPackage) Standard() bool { - return !strings.Contains(p.Path, ".") -} - -// String returns a string representation of this package in the form of import line in golang. -func (p GoPackage) String() string { - if p.Alias == "" { - return fmt.Sprintf("%q", p.Path) - } - return fmt.Sprintf("%s %q", p.Alias, p.Path) -} - -// File wraps descriptor.FileDescriptorProto for richer features. -type File struct { - *descriptor.FileDescriptorProto - // GoPkg is the go package of the go file generated from this file.. - GoPkg GoPackage - // Messages is the list of messages defined in this file. - Messages []*Message - // Enums is the list of enums defined in this file. - Enums []*Enum - // Services is the list of services defined in this file. - Services []*Service -} - -// proto2 determines if the syntax of the file is proto2. -func (f *File) proto2() bool { - return f.Syntax == nil || f.GetSyntax() == "proto2" -} - -// Message describes a protocol buffer message types -type Message struct { - // File is the file where the message is defined - File *File - // Outers is a list of outer messages if this message is a nested type. - Outers []string - *descriptor.DescriptorProto - Fields []*Field - - // Index is proto path index of this message in File. - Index int -} - -// FQMN returns a fully qualified message name of this message. -func (m *Message) FQMN() string { - components := []string{""} - if m.File.Package != nil { - components = append(components, m.File.GetPackage()) - } - components = append(components, m.Outers...) - components = append(components, m.GetName()) - return strings.Join(components, ".") -} - -// GoType returns a go type name for the message type. -// It prefixes the type name with the package alias if -// its belonging package is not "currentPackage". -func (m *Message) GoType(currentPackage string) string { - var components []string - components = append(components, m.Outers...) - components = append(components, m.GetName()) - - name := strings.Join(components, "_") - if m.File.GoPkg.Path == currentPackage { - return name - } - pkg := m.File.GoPkg.Name - if alias := m.File.GoPkg.Alias; alias != "" { - pkg = alias - } - return fmt.Sprintf("%s.%s", pkg, name) -} - -// Enum describes a protocol buffer enum types -type Enum struct { - // File is the file where the enum is defined - File *File - // Outers is a list of outer messages if this enum is a nested type. - Outers []string - *descriptor.EnumDescriptorProto - - Index int -} - -// FQEN returns a fully qualified enum name of this enum. -func (e *Enum) FQEN() string { - components := []string{""} - if e.File.Package != nil { - components = append(components, e.File.GetPackage()) - } - components = append(components, e.Outers...) - components = append(components, e.GetName()) - return strings.Join(components, ".") -} - -// Service wraps descriptor.ServiceDescriptorProto for richer features. -type Service struct { - // File is the file where this service is defined. - File *File - *descriptor.ServiceDescriptorProto - // Methods is the list of methods defined in this service. - Methods []*Method -} - -// FQSN returns the fully qualified service name of this service. -func (s *Service) FQSN() string { - components := []string{""} - if s.File.Package != nil { - components = append(components, s.File.GetPackage()) - } - components = append(components, s.GetName()) - return strings.Join(components, ".") -} - -// Method wraps descriptor.MethodDescriptorProto for richer features. -type Method struct { - // Service is the service which this method belongs to. - Service *Service - *descriptor.MethodDescriptorProto - - // RequestType is the message type of requests to this method. - RequestType *Message - // ResponseType is the message type of responses from this method. - ResponseType *Message - Bindings []*Binding -} - -// FQMN returns a fully qualified rpc method name of this method. -func (m *Method) FQMN() string { - components := []string{} - components = append(components, m.Service.FQSN()) - components = append(components, m.GetName()) - return strings.Join(components, ".") -} - -// Binding describes how an HTTP endpoint is bound to a gRPC method. -type Binding struct { - // Method is the method which the endpoint is bound to. - Method *Method - // Index is a zero-origin index of the binding in the target method - Index int - // PathTmpl is path template where this method is mapped to. - PathTmpl httprule.Template - // HTTPMethod is the HTTP method which this method is mapped to. - HTTPMethod string - // PathParams is the list of parameters provided in HTTP request paths. - PathParams []Parameter - // Body describes parameters provided in HTTP request body. - Body *Body -} - -// ExplicitParams returns a list of explicitly bound parameters of "b", -// i.e. a union of field path for body and field paths for path parameters. -func (b *Binding) ExplicitParams() []string { - var result []string - if b.Body != nil { - result = append(result, b.Body.FieldPath.String()) - } - for _, p := range b.PathParams { - result = append(result, p.FieldPath.String()) - } - return result -} - -// Field wraps descriptor.FieldDescriptorProto for richer features. -type Field struct { - // Message is the message type which this field belongs to. - Message *Message - // FieldMessage is the message type of the field. - FieldMessage *Message - *descriptor.FieldDescriptorProto -} - -// Parameter is a parameter provided in http requests -type Parameter struct { - // FieldPath is a path to a proto field which this parameter is mapped to. - FieldPath - // Target is the proto field which this parameter is mapped to. - Target *Field - // Method is the method which this parameter is used for. - Method *Method -} - -// ConvertFuncExpr returns a go expression of a converter function. -// The converter function converts a string into a value for the parameter. -func (p Parameter) ConvertFuncExpr() (string, error) { - tbl := proto3ConvertFuncs - if p.Target.Message.File.proto2() { - tbl = proto2ConvertFuncs - } - typ := p.Target.GetType() - conv, ok := tbl[typ] - if !ok { - conv, ok = wellKnownTypeConv[p.Target.GetTypeName()] - } - if !ok { - return "", fmt.Errorf("unsupported field type %s of parameter %s in %s.%s", typ, p.FieldPath, p.Method.Service.GetName(), p.Method.GetName()) - } - return conv, nil -} - -// Body describes a http requtest body to be sent to the method. -type Body struct { - // FieldPath is a path to a proto field which the request body is mapped to. - // The request body is mapped to the request type itself if FieldPath is empty. - FieldPath FieldPath -} - -// AssignableExpr returns an assignable expression in Go to be used to initialize method request object. -// It starts with "msgExpr", which is the go expression of the method request object. -func (b Body) AssignableExpr(msgExpr string) string { - return b.FieldPath.AssignableExpr(msgExpr) -} - -// FieldPath is a path to a field from a request message. -type FieldPath []FieldPathComponent - -// String returns a string representation of the field path. -func (p FieldPath) String() string { - var components []string - for _, c := range p { - components = append(components, c.Name) - } - return strings.Join(components, ".") -} - -// IsNestedProto3 indicates whether the FieldPath is a nested Proto3 path. -func (p FieldPath) IsNestedProto3() bool { - if len(p) > 1 && !p[0].Target.Message.File.proto2() { - return true - } - return false -} - -// AssignableExpr is an assignable expression in Go to be used to assign a value to the target field. -// It starts with "msgExpr", which is the go expression of the method request object. -func (p FieldPath) AssignableExpr(msgExpr string) string { - l := len(p) - if l == 0 { - return msgExpr - } - - var preparations []string - components := msgExpr - for i, c := range p { - // Check if it is a oneOf field. - if c.Target.OneofIndex != nil { - index := c.Target.OneofIndex - msg := c.Target.Message - oneOfName := gogen.CamelCase(msg.GetOneofDecl()[*index].GetName()) - oneofFieldName := msg.GetName() + "_" + c.AssignableExpr() - - components = components + "." + oneOfName - s := `if %s == nil { - %s =&%s{} - } else if _, ok := %s.(*%s); !ok { - return nil, metadata, grpc.Errorf(codes.InvalidArgument, "expect type: *%s, but: %%t\n",%s) - }` - - preparations = append(preparations, fmt.Sprintf(s, components, components, oneofFieldName, components, oneofFieldName, oneofFieldName, components)) - components = components + ".(*" + oneofFieldName + ")" - } - - if i == l-1 { - components = components + "." + c.AssignableExpr() - continue - } - components = components + "." + c.ValueExpr() - } - - preparations = append(preparations, components) - return strings.Join(preparations, "\n") -} - -// FieldPathComponent is a path component in FieldPath -type FieldPathComponent struct { - // Name is a name of the proto field which this component corresponds to. - // TODO(yugui) is this necessary? - Name string - // Target is the proto field which this component corresponds to. - Target *Field -} - -// AssignableExpr returns an assignable expression in go for this field. -func (c FieldPathComponent) AssignableExpr() string { - return gogen.CamelCase(c.Name) -} - -// ValueExpr returns an expression in go for this field. -func (c FieldPathComponent) ValueExpr() string { - if c.Target.Message.File.proto2() { - return fmt.Sprintf("Get%s()", gogen.CamelCase(c.Name)) - } - return gogen.CamelCase(c.Name) -} - -var ( - proto3ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.String", - // FieldDescriptorProto_TYPE_GROUP - // FieldDescriptorProto_TYPE_MESSAGE - descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.Bytes", - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32", - // FieldDescriptorProto_TYPE_ENUM - // TODO(yugui) Handle Enum - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64", - } - - proto2ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{ - descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P", - descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P", - descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P", - descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P", - descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P", - descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P", - descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP", - descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringP", - // FieldDescriptorProto_TYPE_GROUP - // FieldDescriptorProto_TYPE_MESSAGE - // FieldDescriptorProto_TYPE_BYTES - // TODO(yugui) Handle bytes - descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P", - // FieldDescriptorProto_TYPE_ENUM - // TODO(yugui) Handle Enum - descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P", - descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P", - descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P", - } - - wellKnownTypeConv = map[string]string{ - ".google.protobuf.Timestamp": "runtime.Timestamp", - ".google.protobuf.Duration": "runtime.Duration", - } -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types_test.go deleted file mode 100755 index 1dcdb34..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package descriptor - -import ( - "testing" - - "github.com/golang/protobuf/proto" - descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" -) - -func TestGoPackageStandard(t *testing.T) { - for _, spec := range []struct { - pkg GoPackage - want bool - }{ - { - pkg: GoPackage{Path: "fmt", Name: "fmt"}, - want: true, - }, - { - pkg: GoPackage{Path: "encoding/json", Name: "json"}, - want: true, - }, - { - pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, - want: false, - }, - { - pkg: GoPackage{Path: "golang.org/x/net/context", Name: "context"}, - want: false, - }, - { - pkg: GoPackage{Path: "github.com/grpc-ecosystem/grpc-gateway", Name: "main"}, - want: false, - }, - { - pkg: GoPackage{Path: "github.com/google/googleapis/google/api/http.pb", Name: "http_pb", Alias: "htpb"}, - want: false, - }, - } { - if got, want := spec.pkg.Standard(), spec.want; got != want { - t.Errorf("%#v.Standard() = %v; want %v", spec.pkg, got, want) - } - } -} - -func TestGoPackageString(t *testing.T) { - for _, spec := range []struct { - pkg GoPackage - want string - }{ - { - pkg: GoPackage{Path: "fmt", Name: "fmt"}, - want: `"fmt"`, - }, - { - pkg: GoPackage{Path: "encoding/json", Name: "json"}, - want: `"encoding/json"`, - }, - { - pkg: GoPackage{Path: "github.com/golang/protobuf/jsonpb", Name: "jsonpb"}, - want: `"github.com/golang/protobuf/jsonpb"`, - }, - { - pkg: GoPackage{Path: "golang.org/x/net/context", Name: "context"}, - want: `"golang.org/x/net/context"`, - }, - { - pkg: GoPackage{Path: "github.com/grpc-ecosystem/grpc-gateway", Name: "main"}, - want: `"github.com/grpc-ecosystem/grpc-gateway"`, - }, - { - pkg: GoPackage{Path: "github.com/google/googleapis/google/api/http.pb", Name: "http_pb", Alias: "htpb"}, - want: `htpb "github.com/google/googleapis/google/api/http.pb"`, - }, - } { - if got, want := spec.pkg.String(), spec.want; got != want { - t.Errorf("%#v.String() = %q; want %q", spec.pkg, got, want) - } - } -} - -func TestFieldPath(t *testing.T) { - var fds []*descriptor.FileDescriptorProto - for _, src := range []string{ - ` - name: 'example.proto' - package: 'example' - message_type < - name: 'Nest' - field < - name: 'nest2_field' - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: 'Nest2' - number: 1 - > - field < - name: 'terminal_field' - label: LABEL_OPTIONAL - type: TYPE_STRING - number: 2 - > - > - syntax: "proto3" - `, ` - name: 'another.proto' - package: 'example' - message_type < - name: 'Nest2' - field < - name: 'nest_field' - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: 'Nest' - number: 1 - > - field < - name: 'terminal_field' - label: LABEL_OPTIONAL - type: TYPE_STRING - number: 2 - > - > - syntax: "proto2" - `, - } { - var fd descriptor.FileDescriptorProto - if err := proto.UnmarshalText(src, &fd); err != nil { - t.Fatalf("proto.UnmarshalText(%s, &fd) failed with %v; want success", src, err) - } - fds = append(fds, &fd) - } - nest := &Message{ - DescriptorProto: fds[0].MessageType[0], - Fields: []*Field{ - {FieldDescriptorProto: fds[0].MessageType[0].Field[0]}, - {FieldDescriptorProto: fds[0].MessageType[0].Field[1]}, - }, - } - nest2 := &Message{ - DescriptorProto: fds[1].MessageType[0], - Fields: []*Field{ - {FieldDescriptorProto: fds[1].MessageType[0].Field[0]}, - {FieldDescriptorProto: fds[1].MessageType[0].Field[1]}, - }, - } - file1 := &File{ - FileDescriptorProto: fds[0], - GoPkg: GoPackage{Path: "example", Name: "example"}, - Messages: []*Message{nest}, - } - file2 := &File{ - FileDescriptorProto: fds[1], - GoPkg: GoPackage{Path: "example", Name: "example"}, - Messages: []*Message{nest2}, - } - crossLinkFixture(file1) - crossLinkFixture(file2) - - c1 := FieldPathComponent{ - Name: "nest_field", - Target: nest2.Fields[0], - } - if got, want := c1.ValueExpr(), "GetNestField()"; got != want { - t.Errorf("c1.ValueExpr() = %q; want %q", got, want) - } - if got, want := c1.AssignableExpr(), "NestField"; got != want { - t.Errorf("c1.AssignableExpr() = %q; want %q", got, want) - } - - c2 := FieldPathComponent{ - Name: "nest2_field", - Target: nest.Fields[0], - } - if got, want := c2.ValueExpr(), "Nest2Field"; got != want { - t.Errorf("c2.ValueExpr() = %q; want %q", got, want) - } - if got, want := c2.ValueExpr(), "Nest2Field"; got != want { - t.Errorf("c2.ValueExpr() = %q; want %q", got, want) - } - - fp := FieldPath{ - c1, c2, c1, FieldPathComponent{ - Name: "terminal_field", - Target: nest.Fields[1], - }, - } - if got, want := fp.AssignableExpr("resp"), "resp.GetNestField().Nest2Field.GetNestField().TerminalField"; got != want { - t.Errorf("fp.AssignableExpr(%q) = %q; want %q", "resp", got, want) - } - - fp2 := FieldPath{ - c2, c1, c2, FieldPathComponent{ - Name: "terminal_field", - Target: nest2.Fields[1], - }, - } - if got, want := fp2.AssignableExpr("resp"), "resp.Nest2Field.GetNestField().Nest2Field.TerminalField"; got != want { - t.Errorf("fp2.AssignableExpr(%q) = %q; want %q", "resp", got, want) - } - - var fpEmpty FieldPath - if got, want := fpEmpty.AssignableExpr("resp"), "resp"; got != want { - t.Errorf("fpEmpty.AssignableExpr(%q) = %q; want %q", "resp", got, want) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel deleted file mode 100755 index 5995e5d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel +++ /dev/null @@ -1,13 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -package(default_visibility = ["//:generators"]) - -go_library( - name = "go_default_library", - srcs = ["generator.go"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator", - deps = [ - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go deleted file mode 100755 index df55da4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package generator provides an abstract interface to code generators. -package generator - -import ( - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" -) - -// Generator is an abstraction of code generators. -type Generator interface { - // Generate generates output files from input .proto files. - Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel deleted file mode 100755 index 517909b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel +++ /dev/null @@ -1,38 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//protoc-gen-grpc-gateway:__subpackages__"]) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generator.go", - "template.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway", - deps = [ - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-grpc-gateway/generator:go_default_library", - "//utilities:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - "@org_golang_google_genproto//googleapis/api/annotations:go_default_library", - ], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = [ - "generator_test.go", - "template_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-grpc-gateway/httprule:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go deleted file mode 100755 index 223d810..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package gengateway provides a code generator for grpc gateway files. -package gengateway diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go deleted file mode 100755 index 2bd8ee4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go +++ /dev/null @@ -1,114 +0,0 @@ -package gengateway - -import ( - "errors" - "fmt" - "go/format" - "path" - "path/filepath" - "strings" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator" -) - -var ( - errNoTargetService = errors.New("no target service defined in the file") -) - -type generator struct { - reg *descriptor.Registry - baseImports []descriptor.GoPackage - useRequestContext bool -} - -// New returns a new generator which generates grpc gateway files. -func New(reg *descriptor.Registry, useRequestContext bool) gen.Generator { - var imports []descriptor.GoPackage - for _, pkgpath := range []string{ - "io", - "net/http", - "github.com/grpc-ecosystem/grpc-gateway/runtime", - "github.com/grpc-ecosystem/grpc-gateway/utilities", - "github.com/golang/protobuf/proto", - "golang.org/x/net/context", - "google.golang.org/grpc", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/grpclog", - "google.golang.org/grpc/status", - } { - pkg := descriptor.GoPackage{ - Path: pkgpath, - Name: path.Base(pkgpath), - } - if err := reg.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil { - for i := 0; ; i++ { - alias := fmt.Sprintf("%s_%d", pkg.Name, i) - if err := reg.ReserveGoPackageAlias(alias, pkg.Path); err != nil { - continue - } - pkg.Alias = alias - break - } - } - imports = append(imports, pkg) - } - return &generator{reg: reg, baseImports: imports, useRequestContext: useRequestContext} -} - -func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { - var files []*plugin.CodeGeneratorResponse_File - for _, file := range targets { - glog.V(1).Infof("Processing %s", file.GetName()) - code, err := g.generate(file) - if err == errNoTargetService { - glog.V(1).Infof("%s: %v", file.GetName(), err) - continue - } - if err != nil { - return nil, err - } - formatted, err := format.Source([]byte(code)) - if err != nil { - glog.Errorf("%v: %s", err, code) - return nil, err - } - name := file.GetName() - if file.GoPkg.Path != "" { - name = fmt.Sprintf("%s/%s", file.GoPkg.Path, filepath.Base(name)) - } - ext := filepath.Ext(name) - base := strings.TrimSuffix(name, ext) - output := fmt.Sprintf("%s.pb.gw.go", base) - files = append(files, &plugin.CodeGeneratorResponse_File{ - Name: proto.String(output), - Content: proto.String(string(formatted)), - }) - glog.V(1).Infof("Will emit %s", output) - } - return files, nil -} - -func (g *generator) generate(file *descriptor.File) (string, error) { - pkgSeen := make(map[string]bool) - var imports []descriptor.GoPackage - for _, pkg := range g.baseImports { - pkgSeen[pkg.Path] = true - imports = append(imports, pkg) - } - for _, svc := range file.Services { - for _, m := range svc.Methods { - pkg := m.RequestType.File.GoPkg - if len(m.Bindings) == 0 || - pkg == file.GoPkg || pkgSeen[pkg.Path] { - continue - } - pkgSeen[pkg.Path] = true - imports = append(imports, pkg) - } - } - return applyTemplate(param{File: file, Imports: imports, UseRequestContext: g.useRequestContext}) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator_test.go deleted file mode 100755 index 986ff41..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package gengateway - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" -) - -func newExampleFileDescriptor() *descriptor.File { - return newExampleFileDescriptorWithGoPkg( - &descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - ) -} - -func newExampleFileDescriptorWithGoPkg(gp *descriptor.GoPackage) *descriptor.File { - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - } - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - msg1 := &descriptor.Message{ - DescriptorProto: msgdesc, - File: &descriptor.File{ - GoPkg: descriptor.GoPackage{ - Path: "github.com/golang/protobuf/ptypes/empty", - Name: "empty", - }, - }, - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Example"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - } - meth1 := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("ExampleWithoutBindings"), - InputType: proto.String("empty.Empty"), - OutputType: proto.String("empty.Empty"), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth, meth1}, - } - return &descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - Name: proto.String("example.proto"), - Package: proto.String("example"), - Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: *gp, - Messages: []*descriptor.Message{msg}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "GET", - Body: &descriptor.Body{FieldPath: nil}, - }, - }, - }, - { - MethodDescriptorProto: meth1, - RequestType: msg1, - ResponseType: msg1, - }, - }, - }, - }, - } -} - -func TestGenerateServiceWithoutBindings(t *testing.T) { - file := newExampleFileDescriptor() - g := &generator{} - got, err := g.generate(crossLinkFixture(file)) - if err != nil { - t.Errorf("generate(%#v) failed with %v; want success", file, err) - return - } - if notwanted := `"github.com/golang/protobuf/ptypes/empty"`; strings.Contains(got, notwanted) { - t.Errorf("generate(%#v) = %s; does not want to contain %s", file, got, notwanted) - } -} - -func TestGenerateOutputPath(t *testing.T) { - cases := []struct { - file *descriptor.File - expected string - }{ - { - file: newExampleFileDescriptorWithGoPkg( - &descriptor.GoPackage{ - Path: "example.com/path/to/example", - Name: "example_pb", - }, - ), - expected: "example.com/path/to/example", - }, - { - file: newExampleFileDescriptorWithGoPkg( - &descriptor.GoPackage{ - Path: "example", - Name: "example_pb", - }, - ), - expected: "example", - }, - } - - g := &generator{} - for _, c := range cases { - file := c.file - gots, err := g.Generate([]*descriptor.File{crossLinkFixture(file)}) - if err != nil { - t.Errorf("Generate(%#v) failed with %v; wants success", file, err) - return - } - - if len(gots) != 1 { - t.Errorf("Generate(%#v) failed; expects on result got %d", file, len(gots)) - return - } - - got := gots[0] - if got.Name == nil { - t.Errorf("Generate(%#v) failed; expects non-nil Name(%v)", file, got.Name) - return - } - - gotPath := filepath.Dir(*got.Name) - expectedPath := c.expected - if gotPath != expectedPath { - t.Errorf("Generate(%#v) failed; got path: %s expected path: %s", file, gotPath, expectedPath) - return - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go deleted file mode 100755 index 435a140..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go +++ /dev/null @@ -1,409 +0,0 @@ -package gengateway - -import ( - "bytes" - "fmt" - "strings" - "text/template" - - "github.com/golang/glog" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -type param struct { - *descriptor.File - Imports []descriptor.GoPackage - UseRequestContext bool -} - -type binding struct { - *descriptor.Binding -} - -// HasQueryParam determines if the binding needs parameters in query string. -// -// It sometimes returns true even though actually the binding does not need. -// But it is not serious because it just results in a small amount of extra codes generated. -func (b binding) HasQueryParam() bool { - if b.Body != nil && len(b.Body.FieldPath) == 0 { - return false - } - fields := make(map[string]bool) - for _, f := range b.Method.RequestType.Fields { - fields[f.GetName()] = true - } - if b.Body != nil { - delete(fields, b.Body.FieldPath.String()) - } - for _, p := range b.PathParams { - delete(fields, p.FieldPath.String()) - } - return len(fields) > 0 -} - -func (b binding) QueryParamFilter() queryParamFilter { - var seqs [][]string - if b.Body != nil { - seqs = append(seqs, strings.Split(b.Body.FieldPath.String(), ".")) - } - for _, p := range b.PathParams { - seqs = append(seqs, strings.Split(p.FieldPath.String(), ".")) - } - return queryParamFilter{utilities.NewDoubleArray(seqs)} -} - -// queryParamFilter is a wrapper of utilities.DoubleArray which provides String() to output DoubleArray.Encoding in a stable and predictable format. -type queryParamFilter struct { - *utilities.DoubleArray -} - -func (f queryParamFilter) String() string { - encodings := make([]string, len(f.Encoding)) - for str, enc := range f.Encoding { - encodings[enc] = fmt.Sprintf("%q: %d", str, enc) - } - e := strings.Join(encodings, ", ") - return fmt.Sprintf("&utilities.DoubleArray{Encoding: map[string]int{%s}, Base: %#v, Check: %#v}", e, f.Base, f.Check) -} - -type trailerParams struct { - Services []*descriptor.Service - UseRequestContext bool -} - -func applyTemplate(p param) (string, error) { - w := bytes.NewBuffer(nil) - if err := headerTemplate.Execute(w, p); err != nil { - return "", err - } - var targetServices []*descriptor.Service - for _, svc := range p.Services { - var methodWithBindingsSeen bool - svcName := strings.Title(*svc.Name) - svc.Name = &svcName - for _, meth := range svc.Methods { - glog.V(2).Infof("Processing %s.%s", svc.GetName(), meth.GetName()) - methName := strings.Title(*meth.Name) - meth.Name = &methName - for _, b := range meth.Bindings { - methodWithBindingsSeen = true - if err := handlerTemplate.Execute(w, binding{Binding: b}); err != nil { - return "", err - } - } - } - if methodWithBindingsSeen { - targetServices = append(targetServices, svc) - } - } - if len(targetServices) == 0 { - return "", errNoTargetService - } - - tp := trailerParams{ - Services: targetServices, - UseRequestContext: p.UseRequestContext, - } - if err := trailerTemplate.Execute(w, tp); err != nil { - return "", err - } - return w.String(), nil -} - -var ( - headerTemplate = template.Must(template.New("header").Parse(` -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: {{.GetName}} - -/* -Package {{.GoPkg.Name}} is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package {{.GoPkg.Name}} -import ( - {{range $i := .Imports}}{{if $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}} - - {{range $i := .Imports}}{{if not $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}} -) - -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -`)) - - handlerTemplate = template.Must(template.New("handler").Parse(` -{{if and .Method.GetClientStreaming .Method.GetServerStreaming}} -{{template "bidi-streaming-request-func" .}} -{{else if .Method.GetClientStreaming}} -{{template "client-streaming-request-func" .}} -{{else}} -{{template "client-rpc-request-func" .}} -{{end}} -`)) - - _ = template.Must(handlerTemplate.New("request-func-signature").Parse(strings.Replace(` -{{if .Method.GetServerStreaming}} -func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) ({{.Method.Service.GetName}}_{{.Method.GetName}}Client, runtime.ServerMetadata, error) -{{else}} -func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) -{{end}}`, "\n", "", -1))) - - _ = template.Must(handlerTemplate.New("client-streaming-request-func").Parse(` -{{template "request-func-signature" .}} { - var metadata runtime.ServerMetadata - stream, err := client.{{.Method.GetName}}(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - for { - var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} - err = dec.Decode(&protoReq) - if err == io.EOF { - break - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err = stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return nil, metadata, err - } - } - - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header -{{if .Method.GetServerStreaming}} - return stream, metadata, nil -{{else}} - msg, err := stream.CloseAndRecv() - metadata.TrailerMD = stream.Trailer() - return msg, metadata, err -{{end}} -} -`)) - - _ = template.Must(handlerTemplate.New("client-rpc-request-func").Parse(` -{{if .HasQueryParam}} -var ( - filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}} = {{.QueryParamFilter}} -) -{{end}} -{{template "request-func-signature" .}} { - var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} - var metadata runtime.ServerMetadata -{{if .Body}} - if err := marshaler.NewDecoder(req.Body).Decode(&{{.Body.AssignableExpr "protoReq"}}); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } -{{end}} -{{if .PathParams}} - var ( - val string - ok bool - err error - _ = err - ) - {{range $param := .PathParams}} - val, ok = pathParams[{{$param | printf "%q"}}] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}}) - } -{{if $param.IsNestedProto3 }} - err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val) -{{else}} - {{$param.AssignableExpr "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val) -{{end}} - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err) - } - {{end}} -{{end}} -{{if .HasQueryParam}} - if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } -{{end}} -{{if .Method.GetServerStreaming}} - stream, err := client.{{.Method.GetName}}(ctx, &protoReq) - if err != nil { - return nil, metadata, err - } - header, err := stream.Header() - if err != nil { - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil -{{else}} - msg, err := client.{{.Method.GetName}}(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -{{end}} -}`)) - - _ = template.Must(handlerTemplate.New("bidi-streaming-request-func").Parse(` -{{template "request-func-signature" .}} { - var metadata runtime.ServerMetadata - stream, err := client.{{.Method.GetName}}(ctx) - if err != nil { - grpclog.Printf("Failed to start streaming: %v", err) - return nil, metadata, err - } - dec := marshaler.NewDecoder(req.Body) - handleSend := func() error { - var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}} - err := dec.Decode(&protoReq) - if err == io.EOF { - return err - } - if err != nil { - grpclog.Printf("Failed to decode request: %v", err) - return err - } - if err := stream.Send(&protoReq); err != nil { - grpclog.Printf("Failed to send request: %v", err) - return err - } - return nil - } - if err := handleSend(); err != nil { - if cerr := stream.CloseSend(); cerr != nil { - grpclog.Printf("Failed to terminate client stream: %v", cerr) - } - if err == io.EOF { - return stream, metadata, nil - } - return nil, metadata, err - } - go func() { - for { - if err := handleSend(); err != nil { - break - } - } - if err := stream.CloseSend(); err != nil { - grpclog.Printf("Failed to terminate client stream: %v", err) - } - }() - header, err := stream.Header() - if err != nil { - grpclog.Printf("Failed to get header from client: %v", err) - return nil, metadata, err - } - metadata.HeaderMD = header - return stream, metadata, nil -} -`)) - - trailerTemplate = template.Must(template.New("trailer").Parse(` -{{$UseRequestContext := .UseRequestContext}} -{{range $svc := .Services}} -// Register{{$svc.GetName}}HandlerFromEndpoint is same as Register{{$svc.GetName}}Handler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func Register{{$svc.GetName}}HandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Printf("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return Register{{$svc.GetName}}Handler(ctx, mux, conn) -} - -// Register{{$svc.GetName}}Handler registers the http handlers for service {{$svc.GetName}} to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func Register{{$svc.GetName}}Handler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return Register{{$svc.GetName}}HandlerClient(ctx, mux, New{{$svc.GetName}}Client(conn)) -} - -// Register{{$svc.GetName}}Handler registers the http handlers for service {{$svc.GetName}} to "mux". -// The handlers forward requests to the grpc endpoint over the given implementation of "{{$svc.GetName}}Client". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "{{$svc.GetName}}Client" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "{{$svc.GetName}}Client" to call the correct interceptors. -func Register{{$svc.GetName}}HandlerClient(ctx context.Context, mux *runtime.ServeMux, client {{$svc.GetName}}Client) error { - {{range $m := $svc.Methods}} - {{range $b := $m.Bindings}} - mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - {{- if $UseRequestContext }} - ctx, cancel := context.WithCancel(req.Context()) - {{- else -}} - ctx, cancel := context.WithCancel(ctx) - {{- end }} - defer cancel() - if cn, ok := w.(http.CloseNotifier); ok { - go func(done <-chan struct{}, closed <-chan bool) { - select { - case <-done: - case <-closed: - cancel() - } - }(ctx.Done(), cn.CloseNotify()) - } - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - {{if $m.GetServerStreaming}} - forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - {{else}} - forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - {{end}} - }) - {{end}} - {{end}} - return nil -} - -var ( - {{range $m := $svc.Methods}} - {{range $b := $m.Bindings}} - pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = runtime.MustPattern(runtime.NewPattern({{$b.PathTmpl.Version}}, {{$b.PathTmpl.OpCodes | printf "%#v"}}, {{$b.PathTmpl.Pool | printf "%#v"}}, {{$b.PathTmpl.Verb | printf "%q"}})) - {{end}} - {{end}} -) - -var ( - {{range $m := $svc.Methods}} - {{range $b := $m.Bindings}} - forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = {{if $m.GetServerStreaming}}runtime.ForwardResponseStream{{else}}runtime.ForwardResponseMessage{{end}} - {{end}} - {{end}} -) -{{end}}`)) -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template_test.go deleted file mode 100755 index c5fb2f9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template_test.go +++ /dev/null @@ -1,404 +0,0 @@ -package gengateway - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" -) - -func crossLinkFixture(f *descriptor.File) *descriptor.File { - for _, m := range f.Messages { - m.File = f - } - for _, svc := range f.Services { - svc.File = f - for _, m := range svc.Methods { - m.Service = svc - for _, b := range m.Bindings { - b.Method = m - for _, param := range b.PathParams { - param.Method = m - } - } - } - } - return f -} - -func TestApplyTemplateHeader(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Example"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - Name: proto.String("example.proto"), - Package: proto.String("example"), - Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "GET", - Body: &descriptor.Body{FieldPath: nil}, - }, - }, - }, - }, - }, - }, - } - got, err := applyTemplate(param{File: crossLinkFixture(&file)}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - if want := "package example_pb\n"; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } -} - -func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String("NestedMessage"), - Number: proto.Int32(1), - }, - }, - } - nesteddesc := &protodescriptor.DescriptorProto{ - Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), - Number: proto.Int32(2), - }, - }, - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Echo"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - ClientStreaming: proto.Bool(false), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - for _, spec := range []struct { - serverStreaming bool - sigWant string - }{ - { - serverStreaming: false, - sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, - }, - { - serverStreaming: true, - sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, - }, - } { - meth.ServerStreaming = proto.Bool(spec.serverStreaming) - - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - nested := &descriptor.Message{ - DescriptorProto: nesteddesc, - } - - nestedField := &descriptor.Field{ - Message: msg, - FieldDescriptorProto: msg.GetField()[0], - } - intField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[0], - } - boolField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[1], - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - Name: proto.String("example.proto"), - Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg, nested}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "POST", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - }, - PathParams: []descriptor.Parameter{ - { - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "int32", - Target: intField, - }, - }), - Target: intField, - }, - }, - Body: &descriptor.Body{ - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "bool", - Target: boolField, - }, - }), - }, - }, - }, - }, - }, - }, - }, - } - got, err := applyTemplate(param{File: crossLinkFixture(&file)}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - if want := spec.sigWant; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `marshaler.NewDecoder(req.Body).Decode(&protoReq.GetNested().Bool)`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `val, ok = pathParams["nested.int32"]`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `protoReq.GetNested().Int32, err = runtime.Int32P(val)`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - } -} - -func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String("NestedMessage"), - Number: proto.Int32(1), - }, - }, - } - nesteddesc := &protodescriptor.DescriptorProto{ - Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), - Number: proto.Int32(2), - }, - }, - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Echo"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - ClientStreaming: proto.Bool(true), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - for _, spec := range []struct { - serverStreaming bool - sigWant string - }{ - { - serverStreaming: false, - sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, - }, - { - serverStreaming: true, - sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, - }, - } { - meth.ServerStreaming = proto.Bool(spec.serverStreaming) - - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - nested := &descriptor.Message{ - DescriptorProto: nesteddesc, - } - - nestedField := &descriptor.Field{ - Message: msg, - FieldDescriptorProto: msg.GetField()[0], - } - intField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[0], - } - boolField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[1], - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - Name: proto.String("example.proto"), - Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg, nested}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "POST", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - }, - PathParams: []descriptor.Parameter{ - { - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "int32", - Target: intField, - }, - }), - Target: intField, - }, - }, - Body: &descriptor.Body{ - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "bool", - Target: boolField, - }, - }), - }, - }, - }, - }, - }, - }, - }, - } - got, err := applyTemplate(param{File: crossLinkFixture(&file)}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - if want := spec.sigWant; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `marshaler.NewDecoder(req.Body)`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { - t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel deleted file mode 100755 index 89f94a1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel +++ /dev/null @@ -1,32 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//:generators"]) - -go_library( - name = "go_default_library", - srcs = [ - "compile.go", - "parse.go", - "types.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule", - deps = [ - "//utilities:go_default_library", - "@com_github_golang_glog//:go_default_library", - ], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = [ - "compile_test.go", - "parse_test.go", - "types_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//utilities:go_default_library", - "@com_github_golang_glog//:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go deleted file mode 100755 index 437039a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go +++ /dev/null @@ -1,117 +0,0 @@ -package httprule - -import ( - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -const ( - opcodeVersion = 1 -) - -// Template is a compiled representation of path templates. -type Template struct { - // Version is the version number of the format. - Version int - // OpCodes is a sequence of operations. - OpCodes []int - // Pool is a constant pool - Pool []string - // Verb is a VERB part in the template. - Verb string - // Fields is a list of field paths bound in this template. - Fields []string - // Original template (example: /v1/a_bit_of_everything) - Template string -} - -// Compiler compiles utilities representation of path templates into marshallable operations. -// They can be unmarshalled by runtime.NewPattern. -type Compiler interface { - Compile() Template -} - -type op struct { - // code is the opcode of the operation - code utilities.OpCode - - // str is a string operand of the code. - // num is ignored if str is not empty. - str string - - // num is a numeric operand of the code. - num int -} - -func (w wildcard) compile() []op { - return []op{ - {code: utilities.OpPush}, - } -} - -func (w deepWildcard) compile() []op { - return []op{ - {code: utilities.OpPushM}, - } -} - -func (l literal) compile() []op { - return []op{ - { - code: utilities.OpLitPush, - str: string(l), - }, - } -} - -func (v variable) compile() []op { - var ops []op - for _, s := range v.segments { - ops = append(ops, s.compile()...) - } - ops = append(ops, op{ - code: utilities.OpConcatN, - num: len(v.segments), - }, op{ - code: utilities.OpCapture, - str: v.path, - }) - - return ops -} - -func (t template) Compile() Template { - var rawOps []op - for _, s := range t.segments { - rawOps = append(rawOps, s.compile()...) - } - - var ( - ops []int - pool []string - fields []string - ) - consts := make(map[string]int) - for _, op := range rawOps { - ops = append(ops, int(op.code)) - if op.str == "" { - ops = append(ops, op.num) - } else { - if _, ok := consts[op.str]; !ok { - consts[op.str] = len(pool) - pool = append(pool, op.str) - } - ops = append(ops, consts[op.str]) - } - if op.code == utilities.OpCapture { - fields = append(fields, op.str) - } - } - return Template{ - Version: opcodeVersion, - OpCodes: ops, - Pool: pool, - Verb: t.verb, - Fields: fields, - Template: t.template, - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile_test.go deleted file mode 100755 index 9ef2975..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package httprule - -import ( - "reflect" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -const ( - operandFiller = 0 -) - -func TestCompile(t *testing.T) { - for _, spec := range []struct { - segs []segment - verb string - - ops []int - pool []string - fields []string - }{ - {}, - { - segs: []segment{ - wildcard{}, - }, - ops: []int{int(utilities.OpPush), operandFiller}, - }, - { - segs: []segment{ - deepWildcard{}, - }, - ops: []int{int(utilities.OpPushM), operandFiller}, - }, - { - segs: []segment{ - literal("v1"), - }, - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - }, - { - segs: []segment{ - literal("v1"), - }, - verb: "LOCK", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - }, - { - segs: []segment{ - variable{ - path: "name.nested", - segments: []segment{ - wildcard{}, - }, - }, - }, - ops: []int{ - int(utilities.OpPush), operandFiller, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"name.nested"}, - fields: []string{"name.nested"}, - }, - { - segs: []segment{ - literal("obj"), - variable{ - path: "name.nested", - segments: []segment{ - literal("a"), - wildcard{}, - literal("b"), - }, - }, - variable{ - path: "obj", - segments: []segment{ - deepWildcard{}, - }, - }, - }, - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), operandFiller, - int(utilities.OpLitPush), 2, - int(utilities.OpConcatN), 3, - int(utilities.OpCapture), 3, - int(utilities.OpPushM), operandFiller, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"obj", "a", "b", "name.nested"}, - fields: []string{"name.nested", "obj"}, - }, - } { - tmpl := template{ - segments: spec.segs, - verb: spec.verb, - } - compiled := tmpl.Compile() - if got, want := compiled.Version, opcodeVersion; got != want { - t.Errorf("tmpl.Compile().Version = %d; want %d; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) - } - if got, want := compiled.OpCodes, spec.ops; !reflect.DeepEqual(got, want) { - t.Errorf("tmpl.Compile().OpCodes = %v; want %v; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) - } - if got, want := compiled.Pool, spec.pool; !reflect.DeepEqual(got, want) { - t.Errorf("tmpl.Compile().Pool = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) - } - if got, want := compiled.Verb, spec.verb; got != want { - t.Errorf("tmpl.Compile().Verb = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) - } - if got, want := compiled.Fields, spec.fields; !reflect.DeepEqual(got, want) { - t.Errorf("tmpl.Compile().Fields = %q; want %q; segs=%#v, verb=%q", got, want, spec.segs, spec.verb) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go deleted file mode 100755 index 3be7426..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go +++ /dev/null @@ -1,351 +0,0 @@ -package httprule - -import ( - "fmt" - "strings" - - "github.com/golang/glog" -) - -// InvalidTemplateError indicates that the path template is not valid. -type InvalidTemplateError struct { - tmpl string - msg string -} - -func (e InvalidTemplateError) Error() string { - return fmt.Sprintf("%s: %s", e.msg, e.tmpl) -} - -// Parse parses the string representation of path template -func Parse(tmpl string) (Compiler, error) { - if !strings.HasPrefix(tmpl, "/") { - return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} - } - tokens, verb := tokenize(tmpl[1:]) - - p := parser{tokens: tokens} - segs, err := p.topLevelSegments() - if err != nil { - return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} - } - - return template{ - segments: segs, - verb: verb, - template: tmpl, - }, nil -} - -func tokenize(path string) (tokens []string, verb string) { - if path == "" { - return []string{eof}, "" - } - - const ( - init = iota - field - nested - ) - var ( - st = init - ) - for path != "" { - var idx int - switch st { - case init: - idx = strings.IndexAny(path, "/{") - case field: - idx = strings.IndexAny(path, ".=}") - case nested: - idx = strings.IndexAny(path, "/}") - } - if idx < 0 { - tokens = append(tokens, path) - break - } - switch r := path[idx]; r { - case '/', '.': - case '{': - st = field - case '=': - st = nested - case '}': - st = init - } - if idx == 0 { - tokens = append(tokens, path[idx:idx+1]) - } else { - tokens = append(tokens, path[:idx], path[idx:idx+1]) - } - path = path[idx+1:] - } - - l := len(tokens) - t := tokens[l-1] - if idx := strings.LastIndex(t, ":"); idx == 0 { - tokens, verb = tokens[:l-1], t[1:] - } else if idx > 0 { - tokens[l-1], verb = t[:idx], t[idx+1:] - } - tokens = append(tokens, eof) - return tokens, verb -} - -// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto. -type parser struct { - tokens []string - accepted []string -} - -// topLevelSegments is the target of this parser. -func (p *parser) topLevelSegments() ([]segment, error) { - glog.V(1).Infof("Parsing %q", p.tokens) - segs, err := p.segments() - if err != nil { - return nil, err - } - glog.V(2).Infof("accept segments: %q; %q", p.accepted, p.tokens) - if _, err := p.accept(typeEOF); err != nil { - return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, "")) - } - glog.V(2).Infof("accept eof: %q; %q", p.accepted, p.tokens) - return segs, nil -} - -func (p *parser) segments() ([]segment, error) { - s, err := p.segment() - if err != nil { - return nil, err - } - glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens) - - segs := []segment{s} - for { - if _, err := p.accept("/"); err != nil { - return segs, nil - } - s, err := p.segment() - if err != nil { - return segs, err - } - segs = append(segs, s) - glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens) - } -} - -func (p *parser) segment() (segment, error) { - if _, err := p.accept("*"); err == nil { - return wildcard{}, nil - } - if _, err := p.accept("**"); err == nil { - return deepWildcard{}, nil - } - if l, err := p.literal(); err == nil { - return l, nil - } - - v, err := p.variable() - if err != nil { - return nil, fmt.Errorf("segment neither wildcards, literal or variable: %v", err) - } - return v, err -} - -func (p *parser) literal() (segment, error) { - lit, err := p.accept(typeLiteral) - if err != nil { - return nil, err - } - return literal(lit), nil -} - -func (p *parser) variable() (segment, error) { - if _, err := p.accept("{"); err != nil { - return nil, err - } - - path, err := p.fieldPath() - if err != nil { - return nil, err - } - - var segs []segment - if _, err := p.accept("="); err == nil { - segs, err = p.segments() - if err != nil { - return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err) - } - } else { - segs = []segment{wildcard{}} - } - - if _, err := p.accept("}"); err != nil { - return nil, fmt.Errorf("unterminated variable segment: %s", path) - } - return variable{ - path: path, - segments: segs, - }, nil -} - -func (p *parser) fieldPath() (string, error) { - c, err := p.accept(typeIdent) - if err != nil { - return "", err - } - components := []string{c} - for { - if _, err = p.accept("."); err != nil { - return strings.Join(components, "."), nil - } - c, err := p.accept(typeIdent) - if err != nil { - return "", fmt.Errorf("invalid field path component: %v", err) - } - components = append(components, c) - } -} - -// A termType is a type of terminal symbols. -type termType string - -// These constants define some of valid values of termType. -// They improve readability of parse functions. -// -// You can also use "/", "*", "**", "." or "=" as valid values. -const ( - typeIdent = termType("ident") - typeLiteral = termType("literal") - typeEOF = termType("$") -) - -const ( - // eof is the terminal symbol which always appears at the end of token sequence. - eof = "\u0000" -) - -// accept tries to accept a token in "p". -// This function consumes a token and returns it if it matches to the specified "term". -// If it doesn't match, the function does not consume any tokens and return an error. -func (p *parser) accept(term termType) (string, error) { - t := p.tokens[0] - switch term { - case "/", "*", "**", ".", "=", "{", "}": - if t != string(term) { - return "", fmt.Errorf("expected %q but got %q", term, t) - } - case typeEOF: - if t != eof { - return "", fmt.Errorf("expected EOF but got %q", t) - } - case typeIdent: - if err := expectIdent(t); err != nil { - return "", err - } - case typeLiteral: - if err := expectPChars(t); err != nil { - return "", err - } - default: - return "", fmt.Errorf("unknown termType %q", term) - } - p.tokens = p.tokens[1:] - p.accepted = append(p.accepted, t) - return t, nil -} - -// expectPChars determines if "t" consists of only pchars defined in RFC3986. -// -// https://www.ietf.org/rfc/rfc3986.txt, P.49 -// pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" -// / "*" / "+" / "," / ";" / "=" -// pct-encoded = "%" HEXDIG HEXDIG -func expectPChars(t string) error { - const ( - init = iota - pct1 - pct2 - ) - st := init - for _, r := range t { - if st != init { - if !isHexDigit(r) { - return fmt.Errorf("invalid hexdigit: %c(%U)", r, r) - } - switch st { - case pct1: - st = pct2 - case pct2: - st = init - } - continue - } - - // unreserved - switch { - case 'A' <= r && r <= 'Z': - continue - case 'a' <= r && r <= 'z': - continue - case '0' <= r && r <= '9': - continue - } - switch r { - case '-', '.', '_', '~': - // unreserved - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': - // sub-delims - case ':', '@': - // rest of pchar - case '%': - // pct-encoded - st = pct1 - default: - return fmt.Errorf("invalid character in path segment: %q(%U)", r, r) - } - } - if st != init { - return fmt.Errorf("invalid percent-encoding in %q", t) - } - return nil -} - -// expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*). -func expectIdent(ident string) error { - if ident == "" { - return fmt.Errorf("empty identifier") - } - for pos, r := range ident { - switch { - case '0' <= r && r <= '9': - if pos == 0 { - return fmt.Errorf("identifier starting with digit: %s", ident) - } - continue - case 'A' <= r && r <= 'Z': - continue - case 'a' <= r && r <= 'z': - continue - case r == '_': - continue - default: - return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident) - } - } - return nil -} - -func isHexDigit(r rune) bool { - switch { - case '0' <= r && r <= '9': - return true - case 'A' <= r && r <= 'F': - return true - case 'a' <= r && r <= 'f': - return true - } - return false -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse_test.go deleted file mode 100755 index 6a49c71..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse_test.go +++ /dev/null @@ -1,313 +0,0 @@ -package httprule - -import ( - "flag" - "fmt" - "reflect" - "testing" - - "github.com/golang/glog" -) - -func TestTokenize(t *testing.T) { - for _, spec := range []struct { - src string - tokens []string - }{ - { - src: "", - tokens: []string{eof}, - }, - { - src: "v1", - tokens: []string{"v1", eof}, - }, - { - src: "v1/b", - tokens: []string{"v1", "/", "b", eof}, - }, - { - src: "v1/endpoint/*", - tokens: []string{"v1", "/", "endpoint", "/", "*", eof}, - }, - { - src: "v1/endpoint/**", - tokens: []string{"v1", "/", "endpoint", "/", "**", eof}, - }, - { - src: "v1/b/{bucket_name=*}", - tokens: []string{ - "v1", "/", - "b", "/", - "{", "bucket_name", "=", "*", "}", - eof, - }, - }, - { - src: "v1/b/{bucket_name=buckets/*}", - tokens: []string{ - "v1", "/", - "b", "/", - "{", "bucket_name", "=", "buckets", "/", "*", "}", - eof, - }, - }, - { - src: "v1/b/{bucket_name=buckets/*}/o", - tokens: []string{ - "v1", "/", - "b", "/", - "{", "bucket_name", "=", "buckets", "/", "*", "}", "/", - "o", - eof, - }, - }, - { - src: "v1/b/{bucket_name=buckets/*}/o/{name}", - tokens: []string{ - "v1", "/", - "b", "/", - "{", "bucket_name", "=", "buckets", "/", "*", "}", "/", - "o", "/", "{", "name", "}", - eof, - }, - }, - { - src: "v1/a=b&c=d;e=f:g/endpoint.rdf", - tokens: []string{ - "v1", "/", - "a=b&c=d;e=f:g", "/", - "endpoint.rdf", - eof, - }, - }, - } { - tokens, verb := tokenize(spec.src) - if got, want := tokens, spec.tokens; !reflect.DeepEqual(got, want) { - t.Errorf("tokenize(%q) = %q, _; want %q, _", spec.src, got, want) - } - if got, want := verb, ""; got != want { - t.Errorf("tokenize(%q) = _, %q; want _, %q", spec.src, got, want) - } - - src := fmt.Sprintf("%s:%s", spec.src, "LOCK") - tokens, verb = tokenize(src) - if got, want := tokens, spec.tokens; !reflect.DeepEqual(got, want) { - t.Errorf("tokenize(%q) = %q, _; want %q, _", src, got, want) - } - if got, want := verb, "LOCK"; got != want { - t.Errorf("tokenize(%q) = _, %q; want _, %q", src, got, want) - } - } -} - -func TestParseSegments(t *testing.T) { - flag.Set("v", "3") - for _, spec := range []struct { - tokens []string - want []segment - }{ - { - tokens: []string{"v1", eof}, - want: []segment{ - literal("v1"), - }, - }, - { - tokens: []string{"-._~!$&'()*+,;=:@", eof}, - want: []segment{ - literal("-._~!$&'()*+,;=:@"), - }, - }, - { - tokens: []string{"%e7%ac%ac%e4%b8%80%e7%89%88", eof}, - want: []segment{ - literal("%e7%ac%ac%e4%b8%80%e7%89%88"), - }, - }, - { - tokens: []string{"v1", "/", "*", eof}, - want: []segment{ - literal("v1"), - wildcard{}, - }, - }, - { - tokens: []string{"v1", "/", "**", eof}, - want: []segment{ - literal("v1"), - deepWildcard{}, - }, - }, - { - tokens: []string{"{", "name", "}", eof}, - want: []segment{ - variable{ - path: "name", - segments: []segment{ - wildcard{}, - }, - }, - }, - }, - { - tokens: []string{"{", "name", "=", "*", "}", eof}, - want: []segment{ - variable{ - path: "name", - segments: []segment{ - wildcard{}, - }, - }, - }, - }, - { - tokens: []string{"{", "field", ".", "nested", ".", "nested2", "=", "*", "}", eof}, - want: []segment{ - variable{ - path: "field.nested.nested2", - segments: []segment{ - wildcard{}, - }, - }, - }, - }, - { - tokens: []string{"{", "name", "=", "a", "/", "b", "/", "*", "}", eof}, - want: []segment{ - variable{ - path: "name", - segments: []segment{ - literal("a"), - literal("b"), - wildcard{}, - }, - }, - }, - }, - { - tokens: []string{ - "v1", "/", - "{", - "name", ".", "nested", ".", "nested2", - "=", - "a", "/", "b", "/", "*", - "}", "/", - "o", "/", - "{", - "another_name", - "=", - "a", "/", "b", "/", "*", "/", "c", - "}", "/", - "**", - eof}, - want: []segment{ - literal("v1"), - variable{ - path: "name.nested.nested2", - segments: []segment{ - literal("a"), - literal("b"), - wildcard{}, - }, - }, - literal("o"), - variable{ - path: "another_name", - segments: []segment{ - literal("a"), - literal("b"), - wildcard{}, - literal("c"), - }, - }, - deepWildcard{}, - }, - }, - } { - p := parser{tokens: spec.tokens} - segs, err := p.topLevelSegments() - if err != nil { - t.Errorf("parser{%q}.segments() failed with %v; want success", spec.tokens, err) - continue - } - if got, want := segs, spec.want; !reflect.DeepEqual(got, want) { - t.Errorf("parser{%q}.segments() = %#v; want %#v", spec.tokens, got, want) - } - if got := p.tokens; len(got) > 0 { - t.Errorf("p.tokens = %q; want []; spec.tokens=%q", got, spec.tokens) - } - } -} - -func TestParseSegmentsWithErrors(t *testing.T) { - flag.Set("v", "3") - for _, spec := range []struct { - tokens []string - }{ - { - // double slash - tokens: []string{"/", eof}, - }, - { - // invalid literal - tokens: []string{"a?b", eof}, - }, - { - // invalid percent-encoding - tokens: []string{"%", eof}, - }, - { - // invalid percent-encoding - tokens: []string{"%2", eof}, - }, - { - // invalid percent-encoding - tokens: []string{"a%2z", eof}, - }, - { - // empty segments - tokens: []string{eof}, - }, - { - // unterminated variable - tokens: []string{"{", "name", eof}, - }, - { - // unterminated variable - tokens: []string{"{", "name", "=", eof}, - }, - { - // unterminated variable - tokens: []string{"{", "name", "=", "*", eof}, - }, - { - // empty component in field path - tokens: []string{"{", "name", ".", "}", eof}, - }, - { - // empty component in field path - tokens: []string{"{", "name", ".", ".", "nested", "}", eof}, - }, - { - // invalid character in identifier - tokens: []string{"{", "field-name", "}", eof}, - }, - { - // no slash between segments - tokens: []string{"v1", "endpoint", eof}, - }, - { - // no slash between segments - tokens: []string{"v1", "{", "name", "}", eof}, - }, - } { - p := parser{tokens: spec.tokens} - segs, err := p.topLevelSegments() - if err == nil { - t.Errorf("parser{%q}.segments() succeeded; want InvalidTemplateError; accepted %#v", spec.tokens, segs) - continue - } - glog.V(1).Info(err) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go deleted file mode 100755 index 5a814a0..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go +++ /dev/null @@ -1,60 +0,0 @@ -package httprule - -import ( - "fmt" - "strings" -) - -type template struct { - segments []segment - verb string - template string -} - -type segment interface { - fmt.Stringer - compile() (ops []op) -} - -type wildcard struct{} - -type deepWildcard struct{} - -type literal string - -type variable struct { - path string - segments []segment -} - -func (wildcard) String() string { - return "*" -} - -func (deepWildcard) String() string { - return "**" -} - -func (l literal) String() string { - return string(l) -} - -func (v variable) String() string { - var segs []string - for _, s := range v.segments { - segs = append(segs, s.String()) - } - return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/")) -} - -func (t template) String() string { - var segs []string - for _, s := range t.segments { - segs = append(segs, s.String()) - } - str := strings.Join(segs, "/") - if t.verb != "" { - str = fmt.Sprintf("%s:%s", str, t.verb) - } - return "/" + str -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types_test.go deleted file mode 100755 index 7ed0c5c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package httprule - -import ( - "fmt" - "testing" -) - -func TestTemplateStringer(t *testing.T) { - for _, spec := range []struct { - segs []segment - want string - }{ - { - segs: []segment{ - literal("v1"), - }, - want: "/v1", - }, - { - segs: []segment{ - wildcard{}, - }, - want: "/*", - }, - { - segs: []segment{ - deepWildcard{}, - }, - want: "/**", - }, - { - segs: []segment{ - variable{ - path: "name", - segments: []segment{ - literal("a"), - }, - }, - }, - want: "/{name=a}", - }, - { - segs: []segment{ - variable{ - path: "name", - segments: []segment{ - literal("a"), - wildcard{}, - literal("b"), - }, - }, - }, - want: "/{name=a/*/b}", - }, - { - segs: []segment{ - literal("v1"), - variable{ - path: "name", - segments: []segment{ - literal("a"), - wildcard{}, - literal("b"), - }, - }, - literal("c"), - variable{ - path: "field.nested", - segments: []segment{ - wildcard{}, - literal("d"), - }, - }, - wildcard{}, - literal("e"), - deepWildcard{}, - }, - want: "/v1/{name=a/*/b}/c/{field.nested=*/d}/*/e/**", - }, - } { - tmpl := template{segments: spec.segs} - if got, want := tmpl.String(), spec.want; got != want { - t.Errorf("%#v.String() = %q; want %q", tmpl, got, want) - } - - tmpl.verb = "LOCK" - if got, want := tmpl.String(), fmt.Sprintf("%s:LOCK", spec.want); got != want { - t.Errorf("%#v.String() = %q; want %q", tmpl, got, want) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go deleted file mode 100755 index 3037d68..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go +++ /dev/null @@ -1,115 +0,0 @@ -// Command protoc-gen-grpc-gateway is a plugin for Google protocol buffer -// compiler to generate a reverse-proxy, which converts incoming RESTful -// HTTP/1 requests gRPC invocation. -// You rarely need to run this program directly. Instead, put this program -// into your $PATH with a name "protoc-gen-grpc-gateway" and run -// protoc --grpc-gateway_out=output_directory path/to/input.proto -// -// See README.md for more details. -package main - -import ( - "flag" - "os" - "strings" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/codegenerator" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway" -) - -var ( - importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files") - importPath = flag.String("import_path", "", "used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored.") - useRequestContext = flag.Bool("request_context", true, "determine whether to use http.Request's context or not") - allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body") - grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format") -) - -func main() { - flag.Parse() - defer glog.Flush() - - reg := descriptor.NewRegistry() - - glog.V(1).Info("Parsing code generator request") - req, err := codegenerator.ParseRequest(os.Stdin) - if err != nil { - glog.Fatal(err) - } - glog.V(1).Info("Parsed code generator request") - if req.Parameter != nil { - for _, p := range strings.Split(req.GetParameter(), ",") { - spec := strings.SplitN(p, "=", 2) - if len(spec) == 1 { - if err := flag.CommandLine.Set(spec[0], ""); err != nil { - glog.Fatalf("Cannot set flag %s", p) - } - continue - } - name, value := spec[0], spec[1] - if strings.HasPrefix(name, "M") { - reg.AddPkgMap(name[1:], value) - continue - } - if err := flag.CommandLine.Set(name, value); err != nil { - glog.Fatalf("Cannot set flag %s", p) - } - } - } - - g := gengateway.New(reg, *useRequestContext) - - if *grpcAPIConfiguration != "" { - if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil { - emitError(err) - return - } - } - - reg.SetPrefix(*importPrefix) - reg.SetImportPath(*importPath) - reg.SetAllowDeleteBody(*allowDeleteBody) - if err := reg.Load(req); err != nil { - emitError(err) - return - } - - var targets []*descriptor.File - for _, target := range req.FileToGenerate { - f, err := reg.LookupFile(target) - if err != nil { - glog.Fatal(err) - } - targets = append(targets, f) - } - - out, err := g.Generate(targets) - glog.V(1).Info("Processed code generator request") - if err != nil { - emitError(err) - return - } - emitFiles(out) -} - -func emitFiles(out []*plugin.CodeGeneratorResponse_File) { - emitResp(&plugin.CodeGeneratorResponse{File: out}) -} - -func emitError(err error) { - emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) -} - -func emitResp(resp *plugin.CodeGeneratorResponse) { - buf, err := proto.Marshal(resp) - if err != nil { - glog.Fatal(err) - } - if _, err := os.Stdout.Write(buf); err != nil { - glog.Fatal(err) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel deleted file mode 100755 index 62384ef..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel +++ /dev/null @@ -1,30 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test") - -package(default_visibility = ["//visibility:private"]) - -go_library( - name = "go_default_library", - srcs = ["main.go"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger", - deps = [ - "//codegenerator:go_default_library", - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-swagger/genswagger:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) - -go_binary( - name = "protoc-gen-swagger", - embed = [":go_default_library"], - visibility = ["//visibility:public"], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = ["main_test.go"], - embed = [":go_default_library"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl deleted file mode 100755 index ada0331..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl +++ /dev/null @@ -1,112 +0,0 @@ -"""Generated an open-api spec for a grpc api spec. - -Reads the the api spec in protobuf format and generate an open-api spec. -Optionally applies settings from the grpc-service configuration. -""" - -def _collect_includes(gen_dir, srcs): - """Build an include path mapping. - - It is important to not just collect unique dirnames, to also support - proto files of the same name from different packages. - - The implementation below is similar to what bazel does in its - ProtoCompileActionBuilder.java - """ - includes = [] - for src in srcs: - ref_path = src.path - - if ref_path.startswith(gen_dir): - ref_path = ref_path[len(gen_dir):].lstrip("/") - - if src.owner.workspace_root: - workspace_root = src.owner.workspace_root - ref_path = ref_path[len(workspace_root):].lstrip("/") - - include = ref_path + "=" + src.path - if include not in includes: - includes.append(include) - - return includes - -def _run_proto_gen_swagger(ctx, direct_proto_srcs, transitive_proto_srcs, actions, protoc, protoc_gen_swagger, grpc_api_configuration): - swagger_files = [] - for proto in direct_proto_srcs: - swagger_file = actions.declare_file( - "%s.swagger.json" % proto.basename[:-len(".proto")], - sibling = proto, - ) - - inputs = direct_proto_srcs + transitive_proto_srcs + [protoc_gen_swagger] - - options=["logtostderr=true"] - if grpc_api_configuration: - options.append("grpc_api_configuration=%s" % grpc_api_configuration.path) - inputs.append(grpc_api_configuration) - - includes = _collect_includes(ctx.genfiles_dir.path, direct_proto_srcs + transitive_proto_srcs) - - args = actions.args() - args.add("--plugin=%s" % protoc_gen_swagger.path) - args.add("--swagger_out=%s:%s" % (",".join(options), ctx.bin_dir.path)) - args.add(["-I%s" % include for include in includes]) - args.add(proto.path) - - actions.run( - executable = protoc, - inputs = inputs, - outputs = [swagger_file], - arguments = [args], - ) - - swagger_files.append(swagger_file) - - return swagger_files - -def _proto_gen_swagger_impl(ctx): - proto = ctx.attr.proto.proto - grpc_api_configuration = ctx.file.grpc_api_configuration - - return struct( - files=depset( - _run_proto_gen_swagger( - ctx, - direct_proto_srcs = proto.direct_sources, - transitive_proto_srcs = ctx.files._well_known_protos + proto.transitive_sources.to_list(), - actions = ctx.actions, - protoc = ctx.executable._protoc, - protoc_gen_swagger = ctx.executable._protoc_gen_swagger, - grpc_api_configuration = grpc_api_configuration - ) - ) - ) - -protoc_gen_swagger = rule( - attrs = { - "proto": attr.label( - allow_rules = ["proto_library"], - mandatory = True, - providers = ['proto'], - ), - "grpc_api_configuration": attr.label( - allow_single_file=True, - mandatory=False - ), - "_protoc": attr.label( - default = "@com_google_protobuf//:protoc", - executable = True, - cfg = "host", - ), - "_well_known_protos": attr.label( - default = "@com_google_protobuf//:well_known_protos", - allow_files = True, - ), - "_protoc_gen_swagger": attr.label( - default = Label("//protoc-gen-swagger:protoc-gen-swagger"), - executable = True, - cfg = "host", - ), - }, - implementation = _proto_gen_swagger_impl, -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel deleted file mode 100755 index 7f34844..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel +++ /dev/null @@ -1,37 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//protoc-gen-swagger:__subpackages__"]) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generator.go", - "template.go", - "types.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger", - deps = [ - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-grpc-gateway/generator:go_default_library", - "//protoc-gen-swagger/options:go_default_library", - "@com_github_golang_glog//:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = ["template_test.go"], - embed = [":go_default_library"], - deps = [ - "//protoc-gen-grpc-gateway/descriptor:go_default_library", - "//protoc-gen-grpc-gateway/httprule:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - "@com_github_golang_protobuf//protoc-gen-go/plugin:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go deleted file mode 100755 index 4d28716..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package genswagger provides a code generator for swagger. -package genswagger diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go deleted file mode 100755 index 8eba8ac..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go +++ /dev/null @@ -1,132 +0,0 @@ -package genswagger - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "path/filepath" - "strings" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator" - swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" -) - -var ( - errNoTargetService = errors.New("no target service defined in the file") -) - -type generator struct { - reg *descriptor.Registry -} - -type wrapper struct { - fileName string - swagger *swaggerObject -} - -// New returns a new generator which generates grpc gateway files. -func New(reg *descriptor.Registry) gen.Generator { - return &generator{reg: reg} -} - -// Merge a lot of swagger file (wrapper) to single one swagger file -func mergeTargetFile(targets []*wrapper, mergeFileName string) *wrapper { - var mergedTarget *wrapper - for _, f := range targets { - if mergedTarget == nil { - mergedTarget = &wrapper{ - fileName: mergeFileName, - swagger: f.swagger, - } - } else { - for k, v := range f.swagger.Definitions { - mergedTarget.swagger.Definitions[k] = v - } - for k, v := range f.swagger.Paths { - mergedTarget.swagger.Paths[k] = v - } - for k, v := range f.swagger.SecurityDefinitions { - mergedTarget.swagger.SecurityDefinitions[k] = v - } - mergedTarget.swagger.Security = append(mergedTarget.swagger.Security, f.swagger.Security...) - } - } - return mergedTarget -} - -// convert swagger file obj to plugin.CodeGeneratorResponse_File -func encodeSwagger(file *wrapper) *plugin.CodeGeneratorResponse_File { - var formatted bytes.Buffer - enc := json.NewEncoder(&formatted) - enc.SetIndent("", " ") - enc.Encode(*file.swagger) - name := file.fileName - ext := filepath.Ext(name) - base := strings.TrimSuffix(name, ext) - output := fmt.Sprintf("%s.swagger.json", base) - return &plugin.CodeGeneratorResponse_File{ - Name: proto.String(output), - Content: proto.String(formatted.String()), - } -} - -func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) { - var files []*plugin.CodeGeneratorResponse_File - if g.reg.IsAllowMerge() { - var mergedTarget *descriptor.File - // try to find proto leader - for _, f := range targets { - if proto.HasExtension(f.Options, swagger_options.E_Openapiv2Swagger) { - mergedTarget = f - break - } - } - // merge protos to leader - for _, f := range targets { - if mergedTarget == nil { - mergedTarget = f - } else { - mergedTarget.Enums = append(mergedTarget.Enums, f.Enums...) - mergedTarget.Messages = append(mergedTarget.Messages, f.Messages...) - mergedTarget.Services = append(mergedTarget.Services, f.Services...) - } - } - - targets = nil - targets = append(targets, mergedTarget) - } - - var swaggers []*wrapper - for _, file := range targets { - glog.V(1).Infof("Processing %s", file.GetName()) - swagger, err := applyTemplate(param{File: file, reg: g.reg}) - if err == errNoTargetService { - glog.V(1).Infof("%s: %v", file.GetName(), err) - continue - } - if err != nil { - return nil, err - } - swaggers = append(swaggers, &wrapper{ - fileName: file.GetName(), - swagger: swagger, - }) - } - - if g.reg.IsAllowMerge() { - targetSwagger := mergeTargetFile(swaggers, g.reg.GetMergeFileName()) - files = append(files, encodeSwagger(targetSwagger)) - glog.V(1).Infof("New swagger file will emit") - } else { - for _, file := range swaggers { - files = append(files, encodeSwagger(file)) - glog.V(1).Infof("New swagger file will emit") - } - } - return files, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go deleted file mode 100755 index c4f2b8d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go +++ /dev/null @@ -1,1189 +0,0 @@ -package genswagger - -import ( - "fmt" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "sync" - - "github.com/golang/protobuf/proto" - pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" -) - -var wktSchemas = map[string]schemaCore{ - ".google.protobuf.Timestamp": schemaCore{ - Type: "string", - Format: "date-time", - }, - ".google.protobuf.Duration": schemaCore{ - Type: "string", - }, - ".google.protobuf.StringValue": schemaCore{ - Type: "string", - }, - ".google.protobuf.Int32Value": schemaCore{ - Type: "integer", - Format: "int32", - }, - ".google.protobuf.Int64Value": schemaCore{ - Type: "integer", - Format: "int64", - }, - ".google.protobuf.FloatValue": schemaCore{ - Type: "number", - Format: "float", - }, - ".google.protobuf.DoubleValue": schemaCore{ - Type: "number", - Format: "double", - }, - ".google.protobuf.BoolValue": schemaCore{ - Type: "boolean", - Format: "boolean", - }, -} - -func listEnumNames(enum *descriptor.Enum) (names []string) { - for _, value := range enum.GetValue() { - names = append(names, value.GetName()) - } - return names -} - -func getEnumDefault(enum *descriptor.Enum) string { - for _, value := range enum.GetValue() { - if value.GetNumber() == 0 { - return value.GetName() - } - } - return "" -} - -// messageToQueryParameters converts a message to a list of swagger query parameters. -func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) { - for _, field := range message.Fields { - p, err := queryParams(message, field, "", reg, pathParams) - if err != nil { - return nil, err - } - params = append(params, p...) - } - return params, nil -} - -// queryParams converts a field to a list of swagger query parameters recuresively. -func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) { - // make sure the parameter is not already listed as a path parameter - for _, pathParam := range pathParams { - if pathParam.Target == field { - return nil, nil - } - } - schema := schemaOfField(field, reg) - fieldType := field.GetTypeName() - if message.File != nil { - comments := fieldProtoComments(reg, message, field) - if err := updateSwaggerDataFromComments(&schema, comments); err != nil { - return nil, err - } - } - - isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM - items := schema.Items - if schema.Type != "" || isEnum { - if schema.Type == "object" { - return nil, nil // TODO: currently, mapping object in query parameter is not supported - } - if items != nil && (items.Type == "" || items.Type == "object") && !isEnum { - return nil, nil // TODO: currently, mapping object in query parameter is not supported - } - desc := schema.Description - if schema.Title != "" { // merge title because title of parameter object will be ignored - desc = strings.TrimSpace(schema.Title + ". " + schema.Description) - } - param := swaggerParameterObject{ - Name: prefix + field.GetName(), - Description: desc, - In: "query", - Type: schema.Type, - Items: schema.Items, - Format: schema.Format, - } - if isEnum { - enum, err := reg.LookupEnum("", fieldType) - if err != nil { - return nil, fmt.Errorf("unknown enum type %s", fieldType) - } - if items != nil { // array - param.Items = &swaggerItemsObject{ - Type: "string", - Enum: listEnumNames(enum), - } - } else { - param.Type = "string" - param.Enum = listEnumNames(enum) - param.Default = getEnumDefault(enum) - } - valueComments := enumValueProtoComments(reg, enum) - if valueComments != "" { - param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n") - } - } - return []swaggerParameterObject{param}, nil - } - - // nested type, recurse - msg, err := reg.LookupMsg("", fieldType) - if err != nil { - return nil, fmt.Errorf("unknown message type %s", fieldType) - } - for _, nestedField := range msg.Fields { - p, err := queryParams(msg, nestedField, prefix+field.GetName()+".", reg, pathParams) - if err != nil { - return nil, err - } - params = append(params, p...) - } - return params, nil -} - -// findServicesMessagesAndEnumerations discovers all messages and enums defined in the RPC methods of the service. -func findServicesMessagesAndEnumerations(s []*descriptor.Service, reg *descriptor.Registry, m messageMap, e enumMap, refs refMap) { - for _, svc := range s { - for _, meth := range svc.Methods { - // Request may be fully included in query - if _, ok := refs[fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))]; ok { - m[fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)] = meth.RequestType - } - findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e) - - m[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = meth.ResponseType - findNestedMessagesAndEnumerations(meth.ResponseType, reg, m, e) - } - } -} - -// findNestedMessagesAndEnumerations those can be generated by the services. -func findNestedMessagesAndEnumerations(message *descriptor.Message, reg *descriptor.Registry, m messageMap, e enumMap) { - // Iterate over all the fields that - for _, t := range message.Fields { - fieldType := t.GetTypeName() - // If the type is an empty string then it is a proto primitive - if fieldType != "" { - if _, ok := m[fieldType]; !ok { - msg, err := reg.LookupMsg("", fieldType) - if err != nil { - enum, err := reg.LookupEnum("", fieldType) - if err != nil { - panic(err) - } - e[fieldType] = enum - continue - } - m[fieldType] = msg - findNestedMessagesAndEnumerations(msg, reg, m, e) - } - } - } -} - -func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry) { - for name, msg := range messages { - switch name { - case ".google.protobuf.Timestamp": - continue - case ".google.protobuf.Duration": - continue - case ".google.protobuf.StringValue": - continue - case ".google.protobuf.Int32Value": - continue - case ".google.protobuf.Int64Value": - continue - case ".google.protobuf.FloatValue": - continue - case ".google.protobuf.DoubleValue": - continue - case ".google.protobuf.BoolValue": - continue - } - if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry { - continue - } - schema := swaggerSchemaObject{ - schemaCore: schemaCore{ - Type: "object", - }, - } - msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index)) - if err := updateSwaggerDataFromComments(&schema, msgComments); err != nil { - panic(err) - } - opts, err := extractSchemaOptionFromMessageDescriptor(msg.DescriptorProto) - if err != nil { - panic(err) - } - if opts != nil { - if opts.ExternalDocs != nil { - if schema.ExternalDocs == nil { - schema.ExternalDocs = &swaggerExternalDocumentationObject{} - } - if opts.ExternalDocs.Description != "" { - schema.ExternalDocs.Description = opts.ExternalDocs.Description - } - if opts.ExternalDocs.Url != "" { - schema.ExternalDocs.URL = opts.ExternalDocs.Url - } - } - - // TODO(ivucica): add remaining fields of schema object - } - - for _, f := range msg.Fields { - fieldValue := schemaOfField(f, reg) - comments := fieldProtoComments(reg, msg, f) - if err := updateSwaggerDataFromComments(&fieldValue, comments); err != nil { - panic(err) - } - - schema.Properties = append(schema.Properties, keyVal{f.GetName(), fieldValue}) - } - d[fullyQualifiedNameToSwaggerName(msg.FQMN(), reg)] = schema - } -} - -// schemaOfField returns a swagger Schema Object for a protobuf field. -func schemaOfField(f *descriptor.Field, reg *descriptor.Registry) swaggerSchemaObject { - const ( - singular = 0 - array = 1 - object = 2 - ) - var ( - core schemaCore - aggregate int - ) - - fd := f.FieldDescriptorProto - if m, err := reg.LookupMsg("", f.GetTypeName()); err == nil { - if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry { - fd = m.GetField()[1] - aggregate = object - } - } - if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED { - aggregate = array - } - - switch ft := fd.GetType(); ft { - case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP: - if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok { - core = wktSchema - } else { - core = schemaCore{ - Ref: "#/definitions/" + fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg), - } - } - default: - ftype, format, ok := primitiveSchema(ft) - if ok { - core = schemaCore{Type: ftype, Format: format} - } else { - core = schemaCore{Type: ft.String(), Format: "UNKNOWN"} - } - } - switch aggregate { - case array: - return swaggerSchemaObject{ - schemaCore: schemaCore{ - Type: "array", - Items: (*swaggerItemsObject)(&core), - }, - } - case object: - return swaggerSchemaObject{ - schemaCore: schemaCore{ - Type: "object", - }, - AdditionalProperties: &swaggerSchemaObject{schemaCore: core}, - } - default: - return swaggerSchemaObject{schemaCore: core} - } -} - -// primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for -// the given primitive field type. -// The last return parameter is true iff the field type is actually primitive. -func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) { - switch t { - case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE: - return "number", "double", true - case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT: - return "number", "float", true - case pbdescriptor.FieldDescriptorProto_TYPE_INT64: - return "string", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_UINT64: - // 64bit integer types are marshaled as string in the default JSONPb marshaler. - // TODO(yugui) Add an option to declare 64bit integers as int64. - // - // NOTE: uint64 is not a predefined format of integer type in Swagger spec. - // So we cannot expect that uint64 is commonly supported by swagger processor. - return "string", "uint64", true - case pbdescriptor.FieldDescriptorProto_TYPE_INT32: - return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64: - // Ditto. - return "string", "uint64", true - case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32: - // Ditto. - return "integer", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_BOOL: - return "boolean", "boolean", true - case pbdescriptor.FieldDescriptorProto_TYPE_STRING: - // NOTE: in swagger specifition, format should be empty on string type - return "string", "", true - case pbdescriptor.FieldDescriptorProto_TYPE_BYTES: - return "string", "byte", true - case pbdescriptor.FieldDescriptorProto_TYPE_UINT32: - // Ditto. - return "integer", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32: - return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64: - return "string", "int64", true - case pbdescriptor.FieldDescriptorProto_TYPE_SINT32: - return "integer", "int32", true - case pbdescriptor.FieldDescriptorProto_TYPE_SINT64: - return "string", "int64", true - default: - return "", "", false - } -} - -// renderEnumerationsAsDefinition inserts enums into the definitions object. -func renderEnumerationsAsDefinition(enums enumMap, d swaggerDefinitionsObject, reg *descriptor.Registry) { - for _, enum := range enums { - enumComments := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index)) - - // it may be necessary to sort the result of the GetValue function. - enumNames := listEnumNames(enum) - defaultValue := getEnumDefault(enum) - valueComments := enumValueProtoComments(reg, enum) - if valueComments != "" { - enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n") - } - enumSchemaObject := swaggerSchemaObject{ - schemaCore: schemaCore{ - Type: "string", - Enum: enumNames, - Default: defaultValue, - }, - } - if err := updateSwaggerDataFromComments(&enumSchemaObject, enumComments); err != nil { - panic(err) - } - - d[fullyQualifiedNameToSwaggerName(enum.FQEN(), reg)] = enumSchemaObject - } -} - -// Take in a FQMN or FQEN and return a swagger safe version of the FQMN -func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) string { - registriesSeenMutex.Lock() - defer registriesSeenMutex.Unlock() - if mapping, present := registriesSeen[reg]; present { - return mapping[fqn] - } - mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...)) - registriesSeen[reg] = mapping - return mapping[fqn] -} - -// registriesSeen is used to memoise calls to resolveFullyQualifiedNameToSwaggerNames so -// we don't repeat it unnecessarily, since it can take some time. -var registriesSeen = map[*descriptor.Registry]map[string]string{} -var registriesSeenMutex sync.Mutex - -// Take the names of every proto and "uniq-ify" them. The idea is to produce a -// set of names that meet a couple of conditions. They must be stable, they -// must be unique, and they must be shorter than the FQN. -// -// This likely could be made better. This will always generate the same names -// but may not always produce optimal names. This is a reasonably close -// approximation of what they should look like in most cases. -func resolveFullyQualifiedNameToSwaggerNames(messages []string) map[string]string { - packagesByDepth := make(map[int][][]string) - uniqueNames := make(map[string]string) - - hierarchy := func(pkg string) []string { - return strings.Split(pkg, ".") - } - - for _, p := range messages { - h := hierarchy(p) - for depth := range h { - if _, ok := packagesByDepth[depth]; !ok { - packagesByDepth[depth] = make([][]string, 0) - } - packagesByDepth[depth] = append(packagesByDepth[depth], h[len(h)-depth:]) - } - } - - count := func(list [][]string, item []string) int { - i := 0 - for _, element := range list { - if reflect.DeepEqual(element, item) { - i++ - } - } - return i - } - - for _, p := range messages { - h := hierarchy(p) - for depth := 0; depth < len(h); depth++ { - if count(packagesByDepth[depth], h[len(h)-depth:]) == 1 { - uniqueNames[p] = strings.Join(h[len(h)-depth-1:], "") - break - } - if depth == len(h)-1 { - uniqueNames[p] = strings.Join(h, "") - } - } - } - return uniqueNames -} - -// Swagger expects paths of the form /path/{string_value} but grpc-gateway paths are expected to be of the form /path/{string_value=strprefix/*}. This should reformat it correctly. -func templateToSwaggerPath(path string) string { - // It seems like the right thing to do here is to just use - // strings.Split(path, "/") but that breaks badly when you hit a url like - // /{my_field=prefix/*}/ and end up with 2 sections representing my_field. - // Instead do the right thing and write a small pushdown (counter) automata - // for it. - var parts []string - depth := 0 - buffer := "" - for _, char := range path { - switch char { - case '{': - // Push on the stack - depth++ - buffer += string(char) - break - case '}': - if depth == 0 { - panic("Encountered } without matching { before it.") - } - // Pop from the stack - depth-- - buffer += "}" - case '/': - if depth == 0 { - parts = append(parts, buffer) - buffer = "" - // Since the stack was empty when we hit the '/' we are done with this - // section. - continue - } - default: - buffer += string(char) - break - } - } - - // Now append the last element to parts - parts = append(parts, buffer) - - // Parts is now an array of segments of the path. Interestingly, since the - // syntax for this subsection CAN be handled by a regexp since it has no - // memory. - re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}") - for index, part := range parts { - parts[index] = re.ReplaceAllString(part, "{$1}") - } - - return strings.Join(parts, "/") -} - -func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, refs refMap) error { - // Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array. - for svcIdx, svc := range services { - for methIdx, meth := range svc.Methods { - for bIdx, b := range meth.Bindings { - // Iterate over all the swagger parameters - parameters := swaggerParametersObject{} - for _, parameter := range b.PathParams { - - var paramType, paramFormat string - switch pt := parameter.Target.GetType(); pt { - case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE: - if descriptor.IsWellKnownType(parameter.Target.GetTypeName()) { - schema := schemaOfField(parameter.Target, reg) - paramType = schema.Type - paramFormat = schema.Format - } else { - return fmt.Errorf("only primitive and well-known types are allowed in path parameters") - } - case pbdescriptor.FieldDescriptorProto_TYPE_ENUM: - paramType = fullyQualifiedNameToSwaggerName(parameter.Target.GetTypeName(), reg) - paramFormat = "" - default: - var ok bool - paramType, paramFormat, ok = primitiveSchema(pt) - if !ok { - return fmt.Errorf("unknown field type %v", pt) - } - } - - parameters = append(parameters, swaggerParameterObject{ - Name: parameter.String(), - In: "path", - Required: true, - // Parameters in gRPC-Gateway can only be strings? - Type: paramType, - Format: paramFormat, - }) - } - // Now check if there is a body parameter - if b.Body != nil { - var schema swaggerSchemaObject - - if len(b.Body.FieldPath) == 0 { - schema = swaggerSchemaObject{ - schemaCore: schemaCore{ - Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)), - }, - } - } else { - lastField := b.Body.FieldPath[len(b.Body.FieldPath)-1] - schema = schemaOfField(lastField.Target, reg) - } - - desc := "" - if meth.GetClientStreaming() { - desc = "(streaming inputs)" - } - parameters = append(parameters, swaggerParameterObject{ - Name: "body", - Description: desc, - In: "body", - Required: true, - Schema: &schema, - }) - } else if b.HTTPMethod == "GET" || b.HTTPMethod == "DELETE" { - // add the parameters to the query string - queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams) - if err != nil { - return err - } - parameters = append(parameters, queryParams...) - } - - pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template)] - if !ok { - pathItemObject = swaggerPathItemObject{} - } - - methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method") - desc := "" - if meth.GetServerStreaming() { - desc += "(streaming responses)" - } - operationObject := &swaggerOperationObject{ - Tags: []string{svc.GetName()}, - Parameters: parameters, - Responses: swaggerResponsesObject{ - "200": swaggerResponseObject{ - Description: desc, - Schema: swaggerSchemaObject{ - schemaCore: schemaCore{ - Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)), - }, - }, - }, - }, - } - if bIdx == 0 { - operationObject.OperationID = fmt.Sprintf("%s", meth.GetName()) - } else { - // OperationID must be unique in an OpenAPI v2 definition. - operationObject.OperationID = fmt.Sprintf("%s%d", meth.GetName(), bIdx+1) - } - - // Fill reference map with referenced request messages - for _, param := range operationObject.Parameters { - if param.Schema != nil && param.Schema.Ref != "" { - refs[param.Schema.Ref] = struct{}{} - } - } - - methComments := protoComments(reg, svc.File, nil, "Service", int32(svcIdx), methProtoPath, int32(methIdx)) - if err := updateSwaggerDataFromComments(operationObject, methComments); err != nil { - panic(err) - } - - opts, err := extractOperationOptionFromMethodDescriptor(meth.MethodDescriptorProto) - if opts != nil { - if err != nil { - panic(err) - } - if opts.ExternalDocs != nil { - if operationObject.ExternalDocs == nil { - operationObject.ExternalDocs = &swaggerExternalDocumentationObject{} - } - if opts.ExternalDocs.Description != "" { - operationObject.ExternalDocs.Description = opts.ExternalDocs.Description - } - if opts.ExternalDocs.Url != "" { - operationObject.ExternalDocs.URL = opts.ExternalDocs.Url - } - } - // TODO(ivucica): this would be better supported by looking whether the method is deprecated in the proto file - operationObject.Deprecated = opts.Deprecated - - if opts.Summary != "" { - operationObject.Summary = opts.Summary - } - if opts.Description != "" { - operationObject.Description = opts.Description - } - if len(opts.Tags) > 0 { - operationObject.Tags = make([]string, len(opts.Tags)) - copy(operationObject.Tags, opts.Tags) - } - if opts.Security != nil { - newSecurity := []swaggerSecurityRequirementObject{} - if operationObject.Security == nil { - newSecurity = []swaggerSecurityRequirementObject{} - } else { - newSecurity = operationObject.Security - } - for _, secReq := range opts.Security { - newSecReq := swaggerSecurityRequirementObject{} - for secReqKey, secReqValue := range secReq.SecurityRequirement { - newSecReqValue := make([]string, len(secReqValue.Scope)) - copy(newSecReqValue, secReqValue.Scope) - newSecReq[secReqKey] = newSecReqValue - } - newSecurity = append(newSecurity, newSecReq) - } - operationObject.Security = newSecurity - } - - // TODO(ivucica): add remaining fields of operation object - } - - switch b.HTTPMethod { - case "DELETE": - pathItemObject.Delete = operationObject - break - case "GET": - pathItemObject.Get = operationObject - break - case "POST": - pathItemObject.Post = operationObject - break - case "PUT": - pathItemObject.Put = operationObject - break - case "PATCH": - pathItemObject.Patch = operationObject - break - } - paths[templateToSwaggerPath(b.PathTmpl.Template)] = pathItemObject - } - } - } - - // Success! return nil on the error object - return nil -} - -// This function is called with a param which contains the entire definition of a method. -func applyTemplate(p param) (*swaggerObject, error) { - // Create the basic template object. This is the object that everything is - // defined off of. - s := swaggerObject{ - // Swagger 2.0 is the version of this document - Swagger: "2.0", - Schemes: []string{"http", "https"}, - Consumes: []string{"application/json"}, - Produces: []string{"application/json"}, - Paths: make(swaggerPathsObject), - Definitions: make(swaggerDefinitionsObject), - Info: swaggerInfoObject{ - Title: *p.File.Name, - Version: "version not set", - }, - } - - // Loops through all the services and their exposed GET/POST/PUT/DELETE definitions - // and create entries for all of them. - refs := refMap{} - if err := renderServices(p.Services, s.Paths, p.reg, refs); err != nil { - panic(err) - } - - // Find all the service's messages and enumerations that are defined (recursively) and then - // write their request and response types out as definition objects. - m := messageMap{} - e := enumMap{} - findServicesMessagesAndEnumerations(p.Services, p.reg, m, e, refs) - renderMessagesAsDefinition(m, s.Definitions, p.reg) - renderEnumerationsAsDefinition(e, s.Definitions, p.reg) - - // File itself might have some comments and metadata. - packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") - packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath) - if err := updateSwaggerDataFromComments(&s, packageComments); err != nil { - panic(err) - } - - // There may be additional options in the swagger option in the proto. - spb, err := extractSwaggerOptionFromFileDescriptor(p.FileDescriptorProto) - if err != nil { - panic(err) - } - if spb != nil { - if spb.Swagger != "" { - s.Swagger = spb.Swagger - } - if spb.Info != nil { - if spb.Info.Title != "" { - s.Info.Title = spb.Info.Title - } - if spb.Info.Description != "" { - s.Info.Description = spb.Info.Description - } - if spb.Info.TermsOfService != "" { - s.Info.TermsOfService = spb.Info.TermsOfService - } - if spb.Info.Version != "" { - s.Info.Version = spb.Info.Version - } - if spb.Info.Contact != nil { - if s.Info.Contact == nil { - s.Info.Contact = &swaggerContactObject{} - } - if spb.Info.Contact.Name != "" { - s.Info.Contact.Name = spb.Info.Contact.Name - } - if spb.Info.Contact.Url != "" { - s.Info.Contact.URL = spb.Info.Contact.Url - } - if spb.Info.Contact.Email != "" { - s.Info.Contact.Email = spb.Info.Contact.Email - } - } - } - if spb.Host != "" { - s.Host = spb.Host - } - if spb.BasePath != "" { - s.BasePath = spb.BasePath - } - if len(spb.Schemes) > 0 { - s.Schemes = make([]string, len(spb.Schemes)) - for i, scheme := range spb.Schemes { - s.Schemes[i] = strings.ToLower(scheme.String()) - } - } - if len(spb.Consumes) > 0 { - s.Consumes = make([]string, len(spb.Consumes)) - copy(s.Consumes, spb.Consumes) - } - if len(spb.Produces) > 0 { - s.Produces = make([]string, len(spb.Produces)) - copy(s.Produces, spb.Produces) - } - if spb.SecurityDefinitions != nil && spb.SecurityDefinitions.Security != nil { - if s.SecurityDefinitions == nil { - s.SecurityDefinitions = swaggerSecurityDefinitionsObject{} - } - for secDefKey, secDefValue := range spb.SecurityDefinitions.Security { - var newSecDefValue swaggerSecuritySchemeObject - if oldSecDefValue, ok := s.SecurityDefinitions[secDefKey]; !ok { - newSecDefValue = swaggerSecuritySchemeObject{} - } else { - newSecDefValue = oldSecDefValue - } - if secDefValue.Type != swagger_options.SecurityScheme_TYPE_INVALID { - switch secDefValue.Type { - case swagger_options.SecurityScheme_TYPE_BASIC: - newSecDefValue.Type = "basic" - case swagger_options.SecurityScheme_TYPE_API_KEY: - newSecDefValue.Type = "apiKey" - case swagger_options.SecurityScheme_TYPE_OAUTH2: - newSecDefValue.Type = "oauth2" - } - } - if secDefValue.Description != "" { - newSecDefValue.Description = secDefValue.Description - } - if secDefValue.Name != "" { - newSecDefValue.Name = secDefValue.Name - } - if secDefValue.In != swagger_options.SecurityScheme_IN_INVALID { - switch secDefValue.In { - case swagger_options.SecurityScheme_IN_QUERY: - newSecDefValue.In = "query" - case swagger_options.SecurityScheme_IN_HEADER: - newSecDefValue.In = "header" - } - } - if secDefValue.Flow != swagger_options.SecurityScheme_FLOW_INVALID { - switch secDefValue.Flow { - case swagger_options.SecurityScheme_FLOW_IMPLICIT: - newSecDefValue.Flow = "implicit" - case swagger_options.SecurityScheme_FLOW_PASSWORD: - newSecDefValue.Flow = "password" - case swagger_options.SecurityScheme_FLOW_APPLICATION: - newSecDefValue.Flow = "application" - case swagger_options.SecurityScheme_FLOW_ACCESS_CODE: - newSecDefValue.Flow = "accessCode" - } - } - if secDefValue.AuthorizationUrl != "" { - newSecDefValue.AuthorizationURL = secDefValue.AuthorizationUrl - } - if secDefValue.TokenUrl != "" { - newSecDefValue.TokenURL = secDefValue.TokenUrl - } - if secDefValue.Scopes != nil { - if newSecDefValue.Scopes == nil { - newSecDefValue.Scopes = swaggerScopesObject{} - } - for scopeKey, scopeDesc := range secDefValue.Scopes.Scope { - newSecDefValue.Scopes[scopeKey] = scopeDesc - } - } - s.SecurityDefinitions[secDefKey] = newSecDefValue - } - } - if spb.Security != nil { - newSecurity := []swaggerSecurityRequirementObject{} - if s.Security == nil { - newSecurity = []swaggerSecurityRequirementObject{} - } else { - newSecurity = s.Security - } - for _, secReq := range spb.Security { - newSecReq := swaggerSecurityRequirementObject{} - for secReqKey, secReqValue := range secReq.SecurityRequirement { - newSecReqValue := make([]string, len(secReqValue.Scope)) - copy(newSecReqValue, secReqValue.Scope) - newSecReq[secReqKey] = newSecReqValue - } - newSecurity = append(newSecurity, newSecReq) - } - s.Security = newSecurity - } - if spb.ExternalDocs != nil { - if s.ExternalDocs == nil { - s.ExternalDocs = &swaggerExternalDocumentationObject{} - } - if spb.ExternalDocs.Description != "" { - s.ExternalDocs.Description = spb.ExternalDocs.Description - } - if spb.ExternalDocs.Url != "" { - s.ExternalDocs.URL = spb.ExternalDocs.Url - } - } - - // Additional fields on the OpenAPI v2 spec's "Swagger" object - // should be added here, once supported in the proto. - } - - return &s, nil -} - -// updateSwaggerDataFromComments updates a Swagger object based on a comment -// from the proto file. -// -// First paragraph of a comment is used for summary. Remaining paragraphs of -// a comment are used for description. If 'Summary' field is not present on -// the passed swaggerObject, the summary and description are joined by \n\n. -// -// If there is a field named 'Info', its 'Summary' and 'Description' fields -// will be updated instead. -// -// If there is no 'Summary', the same behavior will be attempted on 'Title', -// but only if the last character is not a period. -func updateSwaggerDataFromComments(swaggerObject interface{}, comment string) error { - if len(comment) == 0 { - return nil - } - - // Figure out what to apply changes to. - swaggerObjectValue := reflect.ValueOf(swaggerObject) - infoObjectValue := swaggerObjectValue.Elem().FieldByName("Info") - if !infoObjectValue.CanSet() { - // No such field? Apply summary and description directly to - // passed object. - infoObjectValue = swaggerObjectValue.Elem() - } - - // Figure out which properties to update. - summaryValue := infoObjectValue.FieldByName("Summary") - descriptionValue := infoObjectValue.FieldByName("Description") - usingTitle := false - if !summaryValue.CanSet() { - summaryValue = infoObjectValue.FieldByName("Title") - usingTitle = true - } - - paragraphs := strings.Split(comment, "\n\n") - - // If there is a summary (or summary-equivalent), use the first - // paragraph as summary, and the rest as description. - if summaryValue.CanSet() { - summary := strings.TrimSpace(paragraphs[0]) - description := strings.TrimSpace(strings.Join(paragraphs[1:], "\n\n")) - if !usingTitle || (len(summary) > 0 && summary[len(summary)-1] != '.') { - summaryValue.Set(reflect.ValueOf(summary)) - if len(description) > 0 { - if !descriptionValue.CanSet() { - return fmt.Errorf("Encountered object type with a summary, but no description") - } - descriptionValue.Set(reflect.ValueOf(description)) - } - return nil - } - } - - // There was no summary field on the swaggerObject. Try to apply the - // whole comment into description. - if descriptionValue.CanSet() { - descriptionValue.Set(reflect.ValueOf(strings.Join(paragraphs, "\n\n"))) - return nil - } - - return fmt.Errorf("no description nor summary property") -} - -func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field *descriptor.Field) string { - protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "Field") - for i, f := range msg.Fields { - if f == field { - return protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index), protoPath, int32(i)) - } - } - return "" -} - -func enumValueProtoComments(reg *descriptor.Registry, enum *descriptor.Enum) string { - protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.EnumDescriptorProto)(nil)), "Value") - var comments []string - for idx, value := range enum.GetValue() { - name := value.GetName() - str := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index), protoPath, int32(idx)) - if str != "" { - comments = append(comments, name+": "+str) - } - } - if len(comments) > 0 { - return "- " + strings.Join(comments, "\n - ") - } - return "" -} - -func protoComments(reg *descriptor.Registry, file *descriptor.File, outers []string, typeName string, typeIndex int32, fieldPaths ...int32) string { - if file.SourceCodeInfo == nil { - fmt.Fprintln(os.Stderr, "descriptor.File should not contain nil SourceCodeInfo") - return "" - } - - outerPaths := make([]int32, len(outers)) - for i := range outers { - location := "" - if file.Package != nil { - location = file.GetPackage() - } - - msg, err := reg.LookupMsg(location, strings.Join(outers[:i+1], ".")) - if err != nil { - panic(err) - } - outerPaths[i] = int32(msg.Index) - } - - for _, loc := range file.SourceCodeInfo.Location { - if !isProtoPathMatches(loc.Path, outerPaths, typeName, typeIndex, fieldPaths) { - continue - } - comments := "" - if loc.LeadingComments != nil { - comments = strings.TrimRight(*loc.LeadingComments, "\n") - comments = strings.TrimSpace(comments) - // TODO(ivucica): this is a hack to fix "// " being interpreted as "//". - // perhaps we should: - // - split by \n - // - determine if every (but first and last) line begins with " " - // - trim every line only if that is the case - // - join by \n - comments = strings.Replace(comments, "\n ", "\n", -1) - } - return comments - } - return "" -} - -var messageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "MessageType") -var nestedProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "NestedType") -var packageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package") - -func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, typeIndex int32, fieldPaths []int32) bool { - if typeName == "Package" && typeIndex == packageProtoPath { - // path for package comments is just [2], and all the other processing - // is too complex for it. - if len(paths) == 0 || typeIndex != paths[0] { - return false - } - return true - } - - if len(paths) != len(outerPaths)*2+2+len(fieldPaths) { - return false - } - - typeNameDescriptor := reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)) - if len(outerPaths) > 0 { - if paths[0] != messageProtoPath || paths[1] != outerPaths[0] { - return false - } - paths = paths[2:] - outerPaths = outerPaths[1:] - - for i, v := range outerPaths { - if paths[i*2] != nestedProtoPath || paths[i*2+1] != v { - return false - } - } - paths = paths[len(outerPaths)*2:] - - if typeName == "MessageType" { - typeName = "NestedType" - } - typeNameDescriptor = reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)) - } - - if paths[0] != protoPathIndex(typeNameDescriptor, typeName) || paths[1] != typeIndex { - return false - } - paths = paths[2:] - - for i, v := range fieldPaths { - if paths[i] != v { - return false - } - } - return true -} - -// protoPathIndex returns a path component for google.protobuf.descriptor.SourceCode_Location. -// -// Specifically, it returns an id as generated from descriptor proto which -// can be used to determine what type the id following it in the path is. -// For example, if we are trying to locate comments related to a field named -// `Address` in a message named `Person`, the path will be: -// -// [4, a, 2, b] -// -// While `a` gets determined by the order in which the messages appear in -// the proto file, and `b` is the field index specified in the proto -// file itself, the path actually needs to specify that `a` refers to a -// message and not, say, a service; and that `b` refers to a field and not -// an option. -// -// protoPathIndex figures out the values 4 and 2 in the above example. Because -// messages are top level objects, the value of 4 comes from field id for -// `MessageType` inside `google.protobuf.descriptor.FileDescriptor` message. -// This field has a message type `google.protobuf.descriptor.DescriptorProto`. -// And inside message `DescriptorProto`, there is a field named `Field` with id -// 2. -// -// Some code generators seem to be hardcoding these values; this method instead -// interprets them from `descriptor.proto`-derived Go source as necessary. -func protoPathIndex(descriptorType reflect.Type, what string) int32 { - field, ok := descriptorType.Elem().FieldByName(what) - if !ok { - panic(fmt.Errorf("could not find protobuf descriptor type id for %s", what)) - } - pbtag := field.Tag.Get("protobuf") - if pbtag == "" { - panic(fmt.Errorf("no Go tag 'protobuf' on protobuf descriptor for %s", what)) - } - path, err := strconv.Atoi(strings.Split(pbtag, ",")[1]) - if err != nil { - panic(fmt.Errorf("protobuf descriptor id for %s cannot be converted to a number: %s", what, err.Error())) - } - - return int32(path) -} - -// extractOperationOptionFromMethodDescriptor extracts the message of type -// swagger_options.Operation from a given proto method's descriptor. -func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescriptorProto) (*swagger_options.Operation, error) { - if meth.Options == nil { - return nil, nil - } - if !proto.HasExtension(meth.Options, swagger_options.E_Openapiv2Operation) { - return nil, nil - } - ext, err := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation) - if err != nil { - return nil, err - } - opts, ok := ext.(*swagger_options.Operation) - if !ok { - return nil, fmt.Errorf("extension is %T; want an Operation", ext) - } - return opts, nil -} - -// extractSchemaOptionFromMessageDescriptor extracts the message of type -// swagger_options.Schema from a given proto message's descriptor. -func extractSchemaOptionFromMessageDescriptor(msg *pbdescriptor.DescriptorProto) (*swagger_options.Schema, error) { - if msg.Options == nil { - return nil, nil - } - if !proto.HasExtension(msg.Options, swagger_options.E_Openapiv2Schema) { - return nil, nil - } - ext, err := proto.GetExtension(msg.Options, swagger_options.E_Openapiv2Schema) - if err != nil { - return nil, err - } - opts, ok := ext.(*swagger_options.Schema) - if !ok { - return nil, fmt.Errorf("extension is %T; want a Schema", ext) - } - return opts, nil -} - -// extractSwaggerOptionFromFileDescriptor extracts the message of type -// swagger_options.Swagger from a given proto method's descriptor. -func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) { - if file.Options == nil { - return nil, nil - } - if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) { - return nil, nil - } - ext, err := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger) - if err != nil { - return nil, err - } - opts, ok := ext.(*swagger_options.Swagger) - if !ok { - return nil, fmt.Errorf("extension is %T; want a Swagger object", ext) - } - return opts, nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template_test.go deleted file mode 100755 index e01bbc3..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template_test.go +++ /dev/null @@ -1,889 +0,0 @@ -package genswagger - -import ( - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule" - "fmt" -) - -func crossLinkFixture(f *descriptor.File) *descriptor.File { - for _, m := range f.Messages { - m.File = f - } - for _, svc := range f.Services { - svc.File = f - for _, m := range svc.Methods { - m.Service = svc - for _, b := range m.Bindings { - b.Method = m - for _, param := range b.PathParams { - param.Method = m - } - } - } - } - return f -} - -func TestMessageToQueryParameters(t *testing.T) { - type test struct { - MsgDescs []*protodescriptor.DescriptorProto - Message string - Params []swaggerParameterObject - } - - tests := []test{ - { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_DOUBLE.Enum(), - Number: proto.Int32(2), - }, - }, - }, - }, - Message: "ExampleMessage", - Params: []swaggerParameterObject{ - swaggerParameterObject{ - Name: "a", - In: "query", - Required: false, - Type: "string", - }, - swaggerParameterObject{ - Name: "b", - In: "query", - Required: false, - Type: "number", - Format: "double", - }, - }, - }, - { - MsgDescs: []*protodescriptor.DescriptorProto{ - &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.Nested"), - Number: proto.Int32(1), - }, - }, - }, - &protodescriptor.DescriptorProto{ - Name: proto.String("Nested"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("a"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("deep"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String(".example.Nested.DeepNested"), - Number: proto.Int32(2), - }, - }, - NestedType: []*protodescriptor.DescriptorProto{{ - Name: proto.String("DeepNested"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("b"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("c"), - Type: protodescriptor.FieldDescriptorProto_TYPE_ENUM.Enum(), - TypeName: proto.String(".example.Nested.DeepNested.DeepEnum"), - Number: proto.Int32(2), - }, - }, - EnumType: []*protodescriptor.EnumDescriptorProto{ - { - Name: proto.String("DeepEnum"), - Value: []*protodescriptor.EnumValueDescriptorProto{ - {Name: proto.String("FALSE"), Number: proto.Int32(0)}, - {Name: proto.String("TRUE"), Number: proto.Int32(1)}, - }, - }, - }, - }}, - }, - }, - Message: "ExampleMessage", - Params: []swaggerParameterObject{ - swaggerParameterObject{ - Name: "nested.a", - In: "query", - Required: false, - Type: "string", - }, - swaggerParameterObject{ - Name: "nested.deep.b", - In: "query", - Required: false, - Type: "string", - }, - swaggerParameterObject{ - Name: "nested.deep.c", - In: "query", - Required: false, - Type: "string", - Enum: []string{"FALSE", "TRUE"}, - Default: "FALSE", - }, - }, - }, - } - - for _, test := range tests { - reg := descriptor.NewRegistry() - msgs := []*descriptor.Message{} - for _, msgdesc := range test.MsgDescs { - msgs = append(msgs, &descriptor.Message{DescriptorProto: msgdesc}) - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - Dependency: []string{}, - MessageType: test.MsgDescs, - Service: []*protodescriptor.ServiceDescriptorProto{}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: msgs, - } - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}, - }) - - message, err := reg.LookupMsg("", ".example."+test.Message) - if err != nil { - t.Fatalf("failed to lookup message: %s", err) - } - params, err := messageToQueryParameters(message, reg, []descriptor.Parameter{}) - if err != nil { - t.Fatalf("failed to convert message to query parameters: %s", err) - } - if !reflect.DeepEqual(params, test.Params) { - t.Errorf("expected %v, got %v", test.Params, params) - } - } -} - -func TestApplyTemplateSimple(t *testing.T) { - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Example"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, - MessageType: []*protodescriptor.DescriptorProto{msgdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "GET", - Body: &descriptor.Body{FieldPath: nil}, - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - Template: "/v1/echo", // TODO(achew22): Figure out what this should really be - }, - }, - }, - }, - }, - }, - }, - } - result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: descriptor.NewRegistry()}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - if want, is, name := "2.0", result.Swagger, "Swagger"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) - } - if want, is, name := "", result.BasePath, "BasePath"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) - } - if want, is, name := []string{"http", "https"}, result.Schemes, "Schemes"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) - } - if want, is, name := []string{"application/json"}, result.Consumes, "Consumes"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) - } - if want, is, name := []string{"application/json"}, result.Produces, "Produces"; !reflect.DeepEqual(is, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, is, want) - } - - // If there was a failure, print out the input and the json result for debugging. - if t.Failed() { - t.Errorf("had: %s", file) - t.Errorf("got: %s", fmt.Sprint(result)) - } -} - -func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { - t.Skip() - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String("NestedMessage"), - Number: proto.Int32(1), - }, - }, - } - nesteddesc := &protodescriptor.DescriptorProto{ - Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), - Number: proto.Int32(2), - }, - }, - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Echo"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - ClientStreaming: proto.Bool(false), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - - meth.ServerStreaming = proto.Bool(false) - - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - nested := &descriptor.Message{ - DescriptorProto: nesteddesc, - } - - nestedField := &descriptor.Field{ - Message: msg, - FieldDescriptorProto: msg.GetField()[0], - } - intField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[0], - } - boolField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[1], - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg, nested}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "POST", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - Template: "/v1/echo", // TODO(achew): Figure out what this hsould really be - }, - PathParams: []descriptor.Parameter{ - { - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "int32", - Target: intField, - }, - }), - Target: intField, - }, - }, - Body: &descriptor.Body{ - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "bool", - Target: boolField, - }, - }), - }, - }, - }, - }, - }, - }, - }, - } - result, err := applyTemplate(param{File: crossLinkFixture(&file)}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - if want, got := "2.0", result.Swagger; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).Swagger = %s want to be %s", file, got, want) - } - if want, got := "", result.BasePath; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).BasePath = %s want to be %s", file, got, want) - } - if want, got := []string{"http", "https"}, result.Schemes; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).Schemes = %s want to be %s", file, got, want) - } - if want, got := []string{"application/json"}, result.Consumes; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).Consumes = %s want to be %s", file, got, want) - } - if want, got := []string{"application/json"}, result.Produces; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).Produces = %s want to be %s", file, got, want) - } - if want, got, name := "Generated for ExampleService.Echo - ", result.Paths["/v1/echo"].Post.Summary, "Paths[/v1/echo].Post.Summary"; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).%s = %s want to be %s", file, name, got, want) - } - - // If there was a failure, print out the input and the json result for debugging. - if t.Failed() { - t.Errorf("had: %s", file) - t.Errorf("got: %s", fmt.Sprint(result)) - } -} - -func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { - t.Skip() - msgdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("nested"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - TypeName: proto.String("NestedMessage"), - Number: proto.Int32(1), - }, - }, - } - nesteddesc := &protodescriptor.DescriptorProto{ - Name: proto.String("NestedMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("int32"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), - Number: proto.Int32(1), - }, - { - Name: proto.String("bool"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), - Number: proto.Int32(2), - }, - }, - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Echo"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("ExampleMessage"), - ClientStreaming: proto.Bool(true), - ServerStreaming: proto.Bool(true), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - - msg := &descriptor.Message{ - DescriptorProto: msgdesc, - } - nested := &descriptor.Message{ - DescriptorProto: nesteddesc, - } - - nestedField := &descriptor.Field{ - Message: msg, - FieldDescriptorProto: msg.GetField()[0], - } - intField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[0], - } - boolField := &descriptor.Field{ - Message: nested, - FieldDescriptorProto: nested.GetField()[1], - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{msg, nested}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: msg, - ResponseType: msg, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "POST", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - Template: "/v1/echo", // TODO(achew): Figure out what this hsould really be - }, - PathParams: []descriptor.Parameter{ - { - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "int32", - Target: intField, - }, - }), - Target: intField, - }, - }, - Body: &descriptor.Body{ - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "nested", - Target: nestedField, - }, - { - Name: "bool", - Target: boolField, - }, - }), - }, - }, - }, - }, - }, - }, - }, - } - _, err := applyTemplate(param{File: crossLinkFixture(&file)}) - if err == nil { - t.Errorf("applyTemplate(%#v) should have failed cause swagger doesn't support streaming", file) - return - } -} - -func TestApplyTemplateRequestWithUnusedReferences(t *testing.T) { - reqdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("ExampleMessage"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("string"), - Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Number: proto.Int32(1), - }, - }, - } - respdesc := &protodescriptor.DescriptorProto{ - Name: proto.String("EmptyMessage"), - } - meth := &protodescriptor.MethodDescriptorProto{ - Name: proto.String("Example"), - InputType: proto.String("ExampleMessage"), - OutputType: proto.String("EmptyMessage"), - ClientStreaming: proto.Bool(false), - ServerStreaming: proto.Bool(false), - } - svc := &protodescriptor.ServiceDescriptorProto{ - Name: proto.String("ExampleService"), - Method: []*protodescriptor.MethodDescriptorProto{meth}, - } - - req := &descriptor.Message{ - DescriptorProto: reqdesc, - } - resp := &descriptor.Message{ - DescriptorProto: respdesc, - } - stringField := &descriptor.Field{ - Message: req, - FieldDescriptorProto: req.GetField()[0], - } - file := descriptor.File{ - FileDescriptorProto: &protodescriptor.FileDescriptorProto{ - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - MessageType: []*protodescriptor.DescriptorProto{reqdesc, respdesc}, - Service: []*protodescriptor.ServiceDescriptorProto{svc}, - }, - GoPkg: descriptor.GoPackage{ - Path: "example.com/path/to/example/example.pb", - Name: "example_pb", - }, - Messages: []*descriptor.Message{req, resp}, - Services: []*descriptor.Service{ - { - ServiceDescriptorProto: svc, - Methods: []*descriptor.Method{ - { - MethodDescriptorProto: meth, - RequestType: req, - ResponseType: resp, - Bindings: []*descriptor.Binding{ - { - HTTPMethod: "GET", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - Template: "/v1/example", - }, - }, - { - HTTPMethod: "POST", - PathTmpl: httprule.Template{ - Version: 1, - OpCodes: []int{0, 0}, - Template: "/v1/example/{string}", - }, - PathParams: []descriptor.Parameter{ - { - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "string", - Target: stringField, - }, - }), - Target: stringField, - }, - }, - Body: &descriptor.Body{ - FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ - { - Name: "string", - Target: stringField, - }, - }), - }, - }, - }, - }, - }, - }, - }, - } - - reg := descriptor.NewRegistry() - reg.Load(&plugin.CodeGeneratorRequest{ProtoFile: []*protodescriptor.FileDescriptorProto{file.FileDescriptorProto}}) - result, err := applyTemplate(param{File: crossLinkFixture(&file), reg: reg}) - if err != nil { - t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) - return - } - - // Only EmptyMessage must be present, not ExampleMessage - if want, got, name := 1, len(result.Definitions), "len(Definitions)"; !reflect.DeepEqual(got, want) { - t.Errorf("applyTemplate(%#v).%s = %d want to be %d", file, name, got, want) - } - - // If there was a failure, print out the input and the json result for debugging. - if t.Failed() { - t.Errorf("had: %s", file) - t.Errorf("got: %s", fmt.Sprint(result)) - } -} - -func TestTemplateToSwaggerPath(t *testing.T) { - var tests = []struct { - input string - expected string - }{ - {"/test", "/test"}, - {"/{test}", "/{test}"}, - {"/{test=prefix/*}", "/{test}"}, - {"/{test=prefix/that/has/multiple/parts/to/it/*}", "/{test}"}, - {"/{test1}/{test2}", "/{test1}/{test2}"}, - {"/{test1}/{test2}/", "/{test1}/{test2}/"}, - } - - for _, data := range tests { - actual := templateToSwaggerPath(data.input) - if data.expected != actual { - t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) - } - } -} - -func TestResolveFullyQualifiedNameToSwaggerName(t *testing.T) { - var tests = []struct { - input string - output string - listOfFQMNs []string - }{ - { - ".a.b.C", - "C", - []string{ - ".a.b.C", - }, - }, - { - ".a.b.C", - "abC", - []string{ - ".a.C", - ".a.b.C", - }, - }, - { - ".a.b.C", - "abC", - []string{ - ".C", - ".a.C", - ".a.b.C", - }, - }, - } - - for _, data := range tests { - names := resolveFullyQualifiedNameToSwaggerNames(data.listOfFQMNs) - output := names[data.input] - if output != data.output { - t.Errorf("Expected fullyQualifiedNameToSwaggerName(%v) to be %s but got %s", - data.input, data.output, output) - } - } -} - -func TestFQMNtoSwaggerName(t *testing.T) { - var tests = []struct { - input string - expected string - }{ - {"/test", "/test"}, - {"/{test}", "/{test}"}, - {"/{test=prefix/*}", "/{test}"}, - {"/{test=prefix/that/has/multiple/parts/to/it/*}", "/{test}"}, - {"/{test1}/{test2}", "/{test1}/{test2}"}, - {"/{test1}/{test2}/", "/{test1}/{test2}/"}, - } - - for _, data := range tests { - actual := templateToSwaggerPath(data.input) - if data.expected != actual { - t.Errorf("Expected templateToSwaggerPath(%v) = %v, actual: %v", data.input, data.expected, actual) - } - } -} - -func TestSchemaOfField(t *testing.T) { - type test struct { - field *descriptor.Field - expected schemaCore - } - - tests := []test{ - { - field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ - Name: proto.String("primitive_field"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - }, - }, - expected: schemaCore{ - Type: "string", - }, - }, - { - field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ - Name: proto.String("repeated_primitive_field"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), - }, - }, - expected: schemaCore{ - Type: "array", - Items: &swaggerItemsObject{ - Type: "string", - }, - }, - }, - { - field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ - Name: proto.String("wrapped_field"), - TypeName: proto.String(".google.protobuf.StringValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - }, - }, - expected: schemaCore{ - Type: "string", - }, - }, - { - field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ - Name: proto.String("repeated_wrapped_field"), - TypeName: proto.String(".google.protobuf.StringValue"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - Label: protodescriptor.FieldDescriptorProto_LABEL_REPEATED.Enum(), - }, - }, - expected: schemaCore{ - Type: "array", - Items: &swaggerItemsObject{ - Type: "string", - }, - }, - }, - { - field: &descriptor.Field{ - FieldDescriptorProto: &protodescriptor.FieldDescriptorProto{ - Name: proto.String("message_field"), - TypeName: proto.String(".example.Message"), - Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), - }, - }, - expected: schemaCore{ - Ref: "#/definitions/exampleMessage", - }, - }, - } - - reg := descriptor.NewRegistry() - reg.Load(&plugin.CodeGeneratorRequest{ - ProtoFile: []*protodescriptor.FileDescriptorProto{ - { - SourceCodeInfo: &protodescriptor.SourceCodeInfo{}, - Name: proto.String("example.proto"), - Package: proto.String("example"), - Dependency: []string{}, - MessageType: []*protodescriptor.DescriptorProto{ - { - Name: proto.String("Message"), - Field: []*protodescriptor.FieldDescriptorProto{ - { - Name: proto.String("value"), - Type: protodescriptor.FieldDescriptorProto_TYPE_STRING.Enum(), - }, - }, - }, - }, - EnumType: []*protodescriptor.EnumDescriptorProto{ - { - Name: proto.String("Message"), - }, - }, - Service: []*protodescriptor.ServiceDescriptorProto{}, - }, - }, - }) - - for _, test := range tests { - actual := schemaOfField(test.field, reg) - if e, a := test.expected.Type, actual.Type; e != a { - t.Errorf("Expected schemaOfField(%v).Type = %s, actual: %s", test.field, e, a) - } - if e, a := test.expected.Ref, actual.Ref; e != a { - t.Errorf("Expected schemaOfField(%v).Ref = %s, actual: %s", test.field, e, a) - } - if e, a := test.expected.Items.getType(), actual.Items.getType(); e != a { - t.Errorf("Expected schemaOfField(%v).Items.Type = %v, actual.Type: %v", test.field, e, a) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go deleted file mode 100755 index 0c85d94..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go +++ /dev/null @@ -1,226 +0,0 @@ -package genswagger - -import ( - "bytes" - "encoding/json" - - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" -) - -type param struct { - *descriptor.File - reg *descriptor.Registry -} - -type binding struct { - *descriptor.Binding -} - -// http://swagger.io/specification/#infoObject -type swaggerInfoObject struct { - Title string `json:"title"` - Description string `json:"description,omitempty"` - TermsOfService string `json:"termsOfService,omitempty"` - Version string `json:"version"` - - Contact *swaggerContactObject `json:"contact,omitempty"` - License *swaggerLicenseObject `json:"license,omitempty"` -} - -// http://swagger.io/specification/#contactObject -type swaggerContactObject struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` - Email string `json:"email,omitempty"` -} - -// http://swagger.io/specification/#licenseObject -type swaggerLicenseObject struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` -} - -// http://swagger.io/specification/#externalDocumentationObject -type swaggerExternalDocumentationObject struct { - Description string `json:"description,omitempty"` - URL string `json:"url,omitempty"` -} - -// http://swagger.io/specification/#swaggerObject -type swaggerObject struct { - Swagger string `json:"swagger"` - Info swaggerInfoObject `json:"info"` - Host string `json:"host,omitempty"` - BasePath string `json:"basePath,omitempty"` - Schemes []string `json:"schemes"` - Consumes []string `json:"consumes"` - Produces []string `json:"produces"` - Paths swaggerPathsObject `json:"paths"` - Definitions swaggerDefinitionsObject `json:"definitions"` - SecurityDefinitions swaggerSecurityDefinitionsObject `json:"securityDefinitions,omitempty"` - Security []swaggerSecurityRequirementObject `json:"security,omitempty"` - ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` -} - -// http://swagger.io/specification/#securityDefinitionsObject -type swaggerSecurityDefinitionsObject map[string]swaggerSecuritySchemeObject - -// http://swagger.io/specification/#securitySchemeObject -type swaggerSecuritySchemeObject struct { - Type string `json:"type"` - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - In string `json:"in,omitempty"` - Flow string `json:"flow,omitempty"` - AuthorizationURL string `json:"authorizationUrl,omitempty"` - TokenURL string `json:"tokenUrl,omitempty"` - Scopes swaggerScopesObject `json:"scopes,omitempty"` -} - -// http://swagger.io/specification/#scopesObject -type swaggerScopesObject map[string]string - -// http://swagger.io/specification/#securityRequirementObject -type swaggerSecurityRequirementObject map[string][]string - -// http://swagger.io/specification/#pathsObject -type swaggerPathsObject map[string]swaggerPathItemObject - -// http://swagger.io/specification/#pathItemObject -type swaggerPathItemObject struct { - Get *swaggerOperationObject `json:"get,omitempty"` - Delete *swaggerOperationObject `json:"delete,omitempty"` - Post *swaggerOperationObject `json:"post,omitempty"` - Put *swaggerOperationObject `json:"put,omitempty"` - Patch *swaggerOperationObject `json:"patch,omitempty"` -} - -// http://swagger.io/specification/#operationObject -type swaggerOperationObject struct { - Summary string `json:"summary,omitempty"` - Description string `json:"description,omitempty"` - OperationID string `json:"operationId"` - Responses swaggerResponsesObject `json:"responses"` - Parameters swaggerParametersObject `json:"parameters,omitempty"` - Tags []string `json:"tags,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` - - Security []swaggerSecurityRequirementObject `json:"security,omitempty"` - ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` -} - -type swaggerParametersObject []swaggerParameterObject - -// http://swagger.io/specification/#parameterObject -type swaggerParameterObject struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - In string `json:"in,omitempty"` - Required bool `json:"required"` - Type string `json:"type,omitempty"` - Format string `json:"format,omitempty"` - Items *swaggerItemsObject `json:"items,omitempty"` - Enum []string `json:"enum,omitempty"` - Default string `json:"default,omitempty"` - - // Or you can explicitly refer to another type. If this is defined all - // other fields should be empty - Schema *swaggerSchemaObject `json:"schema,omitempty"` -} - -// core part of schema, which is common to itemsObject and schemaObject. -// http://swagger.io/specification/#itemsObject -type schemaCore struct { - Type string `json:"type,omitempty"` - Format string `json:"format,omitempty"` - Ref string `json:"$ref,omitempty"` - - Items *swaggerItemsObject `json:"items,omitempty"` - - // If the item is an enumeration include a list of all the *NAMES* of the - // enum values. I'm not sure how well this will work but assuming all enums - // start from 0 index it will be great. I don't think that is a good assumption. - Enum []string `json:"enum,omitempty"` - Default string `json:"default,omitempty"` -} - -type swaggerItemsObject schemaCore - -func (o *swaggerItemsObject) getType() string { - if o == nil { - return "" - } - return o.Type -} - -// http://swagger.io/specification/#responsesObject -type swaggerResponsesObject map[string]swaggerResponseObject - -// http://swagger.io/specification/#responseObject -type swaggerResponseObject struct { - Description string `json:"description"` - Schema swaggerSchemaObject `json:"schema"` -} - -type keyVal struct { - Key string - Value interface{} -} - -type swaggerSchemaObjectProperties []keyVal - -func (op swaggerSchemaObjectProperties) MarshalJSON() ([]byte, error) { - var buf bytes.Buffer - buf.WriteString("{") - for i, kv := range op { - if i != 0 { - buf.WriteString(",") - } - key, err := json.Marshal(kv.Key) - if err != nil { - return nil, err - } - buf.Write(key) - buf.WriteString(":") - val, err := json.Marshal(kv.Value) - if err != nil { - return nil, err - } - buf.Write(val) - } - - buf.WriteString("}") - return buf.Bytes(), nil -} - -// http://swagger.io/specification/#schemaObject -type swaggerSchemaObject struct { - schemaCore - // Properties can be recursively defined - Properties swaggerSchemaObjectProperties `json:"properties,omitempty"` - AdditionalProperties *swaggerSchemaObject `json:"additionalProperties,omitempty"` - - Description string `json:"description,omitempty"` - Title string `json:"title,omitempty"` - - ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"` -} - -// http://swagger.io/specification/#referenceObject -type swaggerReferenceObject struct { - Ref string `json:"$ref"` -} - -// http://swagger.io/specification/#definitionsObject -type swaggerDefinitionsObject map[string]swaggerSchemaObject - -// Internal type mapping from FQMN to descriptor.Message. Used as a set by the -// findServiceMessages function. -type messageMap map[string]*descriptor.Message - -// Internal type mapping from FQEN to descriptor.Enum. Used as a set by the -// findServiceMessages function. -type enumMap map[string]*descriptor.Enum - -// Internal type to store used references. -type refMap map[string]struct{} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go deleted file mode 100755 index 674af5c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go +++ /dev/null @@ -1,153 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - "strings" - - "github.com/golang/glog" - "github.com/golang/protobuf/proto" - plugin "github.com/golang/protobuf/protoc-gen-go/plugin" - "github.com/grpc-ecosystem/grpc-gateway/codegenerator" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" - "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger" -) - -var ( - importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files") - file = flag.String("file", "-", "where to load data from") - allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body") - grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format") - allowMerge = flag.Bool("allow_merge", false, "if set, generation one swagger file out of multiple protos") - mergeFileName = flag.String("merge_file_name", "apidocs", "target swagger file name prefix after merge") -) - -func main() { - flag.Parse() - defer glog.Flush() - - reg := descriptor.NewRegistry() - - glog.V(1).Info("Processing code generator request") - f := os.Stdin - if *file != "-" { - var err error - f, err = os.Open(*file) - if err != nil { - glog.Fatal(err) - } - } - glog.V(1).Info("Parsing code generator request") - req, err := codegenerator.ParseRequest(f) - if err != nil { - glog.Fatal(err) - } - glog.V(1).Info("Parsed code generator request") - pkgMap := make(map[string]string) - if req.Parameter != nil { - err := parseReqParam(req.GetParameter(), flag.CommandLine, pkgMap) - if err != nil { - glog.Fatalf("Error parsing flags: %v", err) - } - } - - reg.SetPrefix(*importPrefix) - reg.SetAllowDeleteBody(*allowDeleteBody) - reg.SetAllowMerge(*allowMerge) - reg.SetMergeFileName(*mergeFileName) - for k, v := range pkgMap { - reg.AddPkgMap(k, v) - } - - if *grpcAPIConfiguration != "" { - if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil { - emitError(err) - return - } - } - - g := genswagger.New(reg) - - if err := reg.Load(req); err != nil { - emitError(err) - return - } - - var targets []*descriptor.File - for _, target := range req.FileToGenerate { - f, err := reg.LookupFile(target) - if err != nil { - glog.Fatal(err) - } - targets = append(targets, f) - } - - out, err := g.Generate(targets) - glog.V(1).Info("Processed code generator request") - if err != nil { - emitError(err) - return - } - emitFiles(out) -} - -func emitFiles(out []*plugin.CodeGeneratorResponse_File) { - emitResp(&plugin.CodeGeneratorResponse{File: out}) -} - -func emitError(err error) { - emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())}) -} - -func emitResp(resp *plugin.CodeGeneratorResponse) { - buf, err := proto.Marshal(resp) - if err != nil { - glog.Fatal(err) - } - if _, err := os.Stdout.Write(buf); err != nil { - glog.Fatal(err) - } -} - -// parseReqParam parses a CodeGeneratorRequest parameter and adds the -// extracted values to the given FlagSet and pkgMap. Returns a non-nil -// error if setting a flag failed. -func parseReqParam(param string, f *flag.FlagSet, pkgMap map[string]string) error { - if param == "" { - return nil - } - for _, p := range strings.Split(param, ",") { - spec := strings.SplitN(p, "=", 2) - if len(spec) == 1 { - if spec[0] == "allow_delete_body" { - err := f.Set(spec[0], "true") - if err != nil { - return fmt.Errorf("Cannot set flag %s: %v", p, err) - } - continue - } - if spec[0] == "allow_merge" { - err := f.Set(spec[0], "true") - if err != nil { - return fmt.Errorf("Cannot set flag %s: %v", p, err) - } - continue - } - err := f.Set(spec[0], "") - if err != nil { - return fmt.Errorf("Cannot set flag %s: %v", p, err) - } - continue - } - name, value := spec[0], spec[1] - if strings.HasPrefix(name, "M") { - pkgMap[name[1:]] = value - continue - } - if err := f.Set(name, value); err != nil { - return fmt.Errorf("Cannot set flag %s: %v", p, err) - } - } - return nil -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main_test.go deleted file mode 100755 index 7bdca48..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package main - -import ( - "flag" - "reflect" - "testing" -) - -func TestParseReqParam(t *testing.T) { - - f := flag.CommandLine - - // this one must be first - with no leading clearFlags call it - // verifies our expectation of default values as we reset by - // clearFlags - pkgMap := make(map[string]string) - expected := map[string]string{} - err := parseReqParam("", f, pkgMap) - if err != nil { - t.Errorf("Test 0: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 0: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(false, false, "-", "", "apidocs", t, 0) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"} - err = parseReqParam("allow_delete_body,allow_merge,file=./foo.pb,import_prefix=/bar/baz,Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api", f, pkgMap) - if err != nil { - t.Errorf("Test 1: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 1: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(true, true, "./foo.pb", "/bar/baz", "apidocs", t, 1) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{"google/api/annotations.proto": "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api"} - err = parseReqParam("allow_delete_body=true,allow_merge=true,merge_file_name=test_name,file=./foo.pb,import_prefix=/bar/baz,Mgoogle/api/annotations.proto=github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api", f, pkgMap) - if err != nil { - t.Errorf("Test 2: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 2: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(true, true,"./foo.pb", "/bar/baz", "test_name", t, 2) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{"a/b/c.proto": "github.com/x/y/z", "f/g/h.proto": "github.com/1/2/3/"} - err = parseReqParam("allow_delete_body=false,allow_merge=false,Ma/b/c.proto=github.com/x/y/z,Mf/g/h.proto=github.com/1/2/3/", f, pkgMap) - if err != nil { - t.Errorf("Test 3: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 3: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(false, false,"stdin", "", "apidocs", t, 3) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{} - err = parseReqParam("", f, pkgMap) - if err != nil { - t.Errorf("Test 4: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 4: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(false, false, "stdin", "", "apidocs", t, 4) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{} - err = parseReqParam("unknown_param=17", f, pkgMap) - if err == nil { - t.Error("Test 5: expected parse error not returned") - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 5: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(false, false,"stdin", "", "apidocs", t, 5) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{} - err = parseReqParam("Mfoo", f, pkgMap) - if err == nil { - t.Error("Test 6: expected parse error not returned") - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 6: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(false, false,"stdin", "", "apidocs", t, 6) - - clearFlags() - pkgMap = make(map[string]string) - expected = map[string]string{} - err = parseReqParam("allow_delete_body,file,import_prefix,allow_merge,merge_file_name", f, pkgMap) - if err != nil { - t.Errorf("Test 7: unexpected parse error '%v'", err) - } - if !reflect.DeepEqual(pkgMap, expected) { - t.Errorf("Test 7: pkgMap parse error, expected '%v', got '%v'", expected, pkgMap) - } - checkFlags(true, true, "", "", "", t, 7) - -} - -func checkFlags(allowDeleteV, allowMergeV bool, fileV, importPathV, mergeFileNameV string, t *testing.T, tid int) { - if *importPrefix != importPathV { - t.Errorf("Test %v: import_prefix misparsed, expected '%v', got '%v'", tid, importPathV, *importPrefix) - } - if *file != fileV { - t.Errorf("Test %v: file misparsed, expected '%v', got '%v'", tid, fileV, *file) - } - if *allowDeleteBody != allowDeleteV { - t.Errorf("Test %v: allow_delete_body misparsed, expected '%v', got '%v'", tid, allowDeleteV, *allowDeleteBody) - } - if *allowMerge != allowMergeV { - t.Errorf("Test %v: allow_merge misparsed, expected '%v', got '%v'", tid, allowMergeV, *allowMerge) - } - if *mergeFileName != mergeFileNameV { - t.Errorf("Test %v: merge_file_name misparsed, expected '%v', got '%v'", tid, mergeFileNameV, *mergeFileName) - } -} - -func clearFlags() { - *importPrefix = "" - *file = "stdin" - *allowDeleteBody = false - *allowMerge = false - *mergeFileName = "apidocs" -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/BUILD.bazel deleted file mode 100755 index 476cb59..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/BUILD.bazel +++ /dev/null @@ -1,33 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") - -package(default_visibility = ["//visibility:public"]) - -proto_library( - name = "options_proto", - srcs = [ - "annotations.proto", - "openapiv2.proto", - ], - deps = [ - "@com_google_protobuf//:any_proto", - "@com_google_protobuf//:descriptor_proto", - ], -) - -go_proto_library( - name = "options_go_proto", - compilers = ["@io_bazel_rules_go//proto:go_grpc"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options", - proto = ":options_proto", - deps = [ - "@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library", - "@com_github_golang_protobuf//ptypes/any:go_default_library", - ], -) - -go_library( - name = "go_default_library", - embed = [":options_go_proto"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options", -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.pb.go deleted file mode 100755 index b8fffb6..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.pb.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: protoc-gen-swagger/options/annotations.proto - -package options // import "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -var E_Openapiv2Swagger = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.FileOptions)(nil), - ExtensionType: (*Swagger)(nil), - Field: 1042, - Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger", - Tag: "bytes,1042,opt,name=openapiv2_swagger,json=openapiv2Swagger", - Filename: "protoc-gen-swagger/options/annotations.proto", -} - -var E_Openapiv2Operation = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MethodOptions)(nil), - ExtensionType: (*Operation)(nil), - Field: 1042, - Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_operation", - Tag: "bytes,1042,opt,name=openapiv2_operation,json=openapiv2Operation", - Filename: "protoc-gen-swagger/options/annotations.proto", -} - -var E_Openapiv2Schema = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MessageOptions)(nil), - ExtensionType: (*Schema)(nil), - Field: 1042, - Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_schema", - Tag: "bytes,1042,opt,name=openapiv2_schema,json=openapiv2Schema", - Filename: "protoc-gen-swagger/options/annotations.proto", -} - -var E_Openapiv2Tag = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.ServiceOptions)(nil), - ExtensionType: (*Tag)(nil), - Field: 1042, - Name: "grpc.gateway.protoc_gen_swagger.options.openapiv2_tag", - Tag: "bytes,1042,opt,name=openapiv2_tag,json=openapiv2Tag", - Filename: "protoc-gen-swagger/options/annotations.proto", -} - -func init() { - proto.RegisterExtension(E_Openapiv2Swagger) - proto.RegisterExtension(E_Openapiv2Operation) - proto.RegisterExtension(E_Openapiv2Schema) - proto.RegisterExtension(E_Openapiv2Tag) -} - -func init() { - proto.RegisterFile("protoc-gen-swagger/options/annotations.proto", fileDescriptor_annotations_a3ffb1266b13d7a2) -} - -var fileDescriptor_annotations_a3ffb1266b13d7a2 = []byte{ - // 311 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0x41, 0x4b, 0x03, 0x31, - 0x10, 0x85, 0xe9, 0x45, 0x64, 0x55, 0xac, 0xeb, 0x45, 0x8a, 0x68, 0x6f, 0x8a, 0xb4, 0x89, 0xd4, - 0xdb, 0xde, 0x54, 0xf0, 0x26, 0x85, 0x6d, 0x4f, 0x5e, 0x4a, 0x9a, 0x8e, 0xd3, 0x40, 0x9b, 0x09, - 0x49, 0xda, 0x52, 0xe8, 0xd1, 0x5f, 0xe0, 0x2f, 0x16, 0x93, 0xed, 0x56, 0xd6, 0x2a, 0x7b, 0xdb, - 0x99, 0x9d, 0xf7, 0xbe, 0xc7, 0x23, 0x49, 0xc7, 0x58, 0xf2, 0x24, 0xbb, 0x08, 0xba, 0xeb, 0x56, - 0x02, 0x11, 0x2c, 0x27, 0xe3, 0x15, 0x69, 0xc7, 0x85, 0xd6, 0xe4, 0x45, 0xf8, 0x66, 0xe1, 0x2c, - 0xbd, 0x41, 0x6b, 0x24, 0x43, 0xe1, 0x61, 0x25, 0xd6, 0x71, 0x27, 0x47, 0x08, 0x7a, 0x54, 0x48, - 0x59, 0x21, 0x6d, 0xdd, 0xfd, 0x63, 0x4b, 0x06, 0xb4, 0x30, 0x6a, 0xd9, 0x8b, 0x06, 0xad, 0x36, - 0x12, 0xe1, 0x0c, 0x78, 0x98, 0xc6, 0x8b, 0x77, 0x3e, 0x01, 0x27, 0xad, 0x32, 0x9e, 0x6c, 0xbc, - 0xc8, 0x36, 0xc9, 0x59, 0x29, 0xda, 0xa2, 0xd2, 0x4b, 0x16, 0x75, 0x6c, 0xab, 0x63, 0x2f, 0x6a, - 0x06, 0xfd, 0x08, 0xb9, 0xf8, 0x3c, 0x6c, 0x37, 0x6e, 0x8f, 0x7a, 0xf7, 0xac, 0x66, 0x62, 0x36, - 0x88, 0x73, 0xde, 0x2c, 0x49, 0xc5, 0x26, 0xfb, 0x68, 0x24, 0xe7, 0x3b, 0x3c, 0x19, 0xb0, 0xa1, - 0x93, 0xf4, 0xea, 0x57, 0x80, 0x57, 0xf0, 0x53, 0x9a, 0x54, 0x22, 0xf4, 0x6a, 0x47, 0xe8, 0x6f, - 0xad, 0xf3, 0xb4, 0xe4, 0x95, 0xbb, 0x6c, 0x93, 0x34, 0x7f, 0x94, 0x20, 0xa7, 0x30, 0x17, 0xe9, - 0xf5, 0x9e, 0x08, 0xce, 0x09, 0xac, 0xd6, 0xc0, 0xeb, 0xd7, 0x10, 0x8c, 0xf3, 0xd3, 0x5d, 0x0b, - 0x61, 0x91, 0xb9, 0xe4, 0x64, 0x47, 0xf7, 0x02, 0xf7, 0xa0, 0x07, 0x60, 0x97, 0x4a, 0x56, 0xd1, - 0x9d, 0xda, 0xe8, 0xa1, 0xc0, 0xfc, 0xb8, 0x84, 0x0c, 0x05, 0x3e, 0x3d, 0xbf, 0x3d, 0xa2, 0xf2, - 0xd3, 0xc5, 0x98, 0x49, 0x9a, 0xf3, 0x6f, 0x9f, 0x2e, 0x48, 0x72, 0x6b, 0xe7, 0xa1, 0x18, 0x0b, - 0x5b, 0xfe, 0xf7, 0x73, 0x1b, 0x1f, 0x84, 0x7f, 0x0f, 0x5f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x80, - 0x7f, 0xc1, 0x6a, 0xea, 0x02, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.proto deleted file mode 100755 index 8746192..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/annotations.proto +++ /dev/null @@ -1,37 +0,0 @@ -syntax = "proto3"; - -package grpc.gateway.protoc_gen_swagger.options; - -option go_package = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"; - -import "protoc-gen-swagger/options/openapiv2.proto"; -import "google/protobuf/descriptor.proto"; - -extend google.protobuf.FileOptions { - // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. - // - // All IDs are the same, as assigned. It is okay that they are the same, as they extend - // different descriptor messages. - Swagger openapiv2_swagger = 1042; -} -extend google.protobuf.MethodOptions { - // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. - // - // All IDs are the same, as assigned. It is okay that they are the same, as they extend - // different descriptor messages. - Operation openapiv2_operation = 1042; -} -extend google.protobuf.MessageOptions { - // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. - // - // All IDs are the same, as assigned. It is okay that they are the same, as they extend - // different descriptor messages. - Schema openapiv2_schema = 1042; -} -extend google.protobuf.ServiceOptions { - // ID assigned by protobuf-global-extension-registry@google.com for grpc-gateway project. - // - // All IDs are the same, as assigned. It is okay that they are the same, as they extend - // different descriptor messages. - Tag openapiv2_tag = 1042; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.pb.go deleted file mode 100755 index be2342b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.pb.go +++ /dev/null @@ -1,1376 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: protoc-gen-swagger/options/openapiv2.proto - -package options // import "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Swagger_SwaggerScheme int32 - -const ( - Swagger_UNKNOWN Swagger_SwaggerScheme = 0 - Swagger_HTTP Swagger_SwaggerScheme = 1 - Swagger_HTTPS Swagger_SwaggerScheme = 2 - Swagger_WS Swagger_SwaggerScheme = 3 - Swagger_WSS Swagger_SwaggerScheme = 4 -) - -var Swagger_SwaggerScheme_name = map[int32]string{ - 0: "UNKNOWN", - 1: "HTTP", - 2: "HTTPS", - 3: "WS", - 4: "WSS", -} -var Swagger_SwaggerScheme_value = map[string]int32{ - "UNKNOWN": 0, - "HTTP": 1, - "HTTPS": 2, - "WS": 3, - "WSS": 4, -} - -func (x Swagger_SwaggerScheme) String() string { - return proto.EnumName(Swagger_SwaggerScheme_name, int32(x)) -} -func (Swagger_SwaggerScheme) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{0, 0} -} - -type JSONSchema_JSONSchemaSimpleTypes int32 - -const ( - JSONSchema_UNKNOWN JSONSchema_JSONSchemaSimpleTypes = 0 - JSONSchema_ARRAY JSONSchema_JSONSchemaSimpleTypes = 1 - JSONSchema_BOOLEAN JSONSchema_JSONSchemaSimpleTypes = 2 - JSONSchema_INTEGER JSONSchema_JSONSchemaSimpleTypes = 3 - JSONSchema_NULL JSONSchema_JSONSchemaSimpleTypes = 4 - JSONSchema_NUMBER JSONSchema_JSONSchemaSimpleTypes = 5 - JSONSchema_OBJECT JSONSchema_JSONSchemaSimpleTypes = 6 - JSONSchema_STRING JSONSchema_JSONSchemaSimpleTypes = 7 -) - -var JSONSchema_JSONSchemaSimpleTypes_name = map[int32]string{ - 0: "UNKNOWN", - 1: "ARRAY", - 2: "BOOLEAN", - 3: "INTEGER", - 4: "NULL", - 5: "NUMBER", - 6: "OBJECT", - 7: "STRING", -} -var JSONSchema_JSONSchemaSimpleTypes_value = map[string]int32{ - "UNKNOWN": 0, - "ARRAY": 1, - "BOOLEAN": 2, - "INTEGER": 3, - "NULL": 4, - "NUMBER": 5, - "OBJECT": 6, - "STRING": 7, -} - -func (x JSONSchema_JSONSchemaSimpleTypes) String() string { - return proto.EnumName(JSONSchema_JSONSchemaSimpleTypes_name, int32(x)) -} -func (JSONSchema_JSONSchemaSimpleTypes) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{6, 0} -} - -// Required. The type of the security scheme. Valid values are "basic", -// "apiKey" or "oauth2". -type SecurityScheme_Type int32 - -const ( - SecurityScheme_TYPE_INVALID SecurityScheme_Type = 0 - SecurityScheme_TYPE_BASIC SecurityScheme_Type = 1 - SecurityScheme_TYPE_API_KEY SecurityScheme_Type = 2 - SecurityScheme_TYPE_OAUTH2 SecurityScheme_Type = 3 -) - -var SecurityScheme_Type_name = map[int32]string{ - 0: "TYPE_INVALID", - 1: "TYPE_BASIC", - 2: "TYPE_API_KEY", - 3: "TYPE_OAUTH2", -} -var SecurityScheme_Type_value = map[string]int32{ - "TYPE_INVALID": 0, - "TYPE_BASIC": 1, - "TYPE_API_KEY": 2, - "TYPE_OAUTH2": 3, -} - -func (x SecurityScheme_Type) String() string { - return proto.EnumName(SecurityScheme_Type_name, int32(x)) -} -func (SecurityScheme_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{9, 0} -} - -// Required. The location of the API key. Valid values are "query" or "header". -type SecurityScheme_In int32 - -const ( - SecurityScheme_IN_INVALID SecurityScheme_In = 0 - SecurityScheme_IN_QUERY SecurityScheme_In = 1 - SecurityScheme_IN_HEADER SecurityScheme_In = 2 -) - -var SecurityScheme_In_name = map[int32]string{ - 0: "IN_INVALID", - 1: "IN_QUERY", - 2: "IN_HEADER", -} -var SecurityScheme_In_value = map[string]int32{ - "IN_INVALID": 0, - "IN_QUERY": 1, - "IN_HEADER": 2, -} - -func (x SecurityScheme_In) String() string { - return proto.EnumName(SecurityScheme_In_name, int32(x)) -} -func (SecurityScheme_In) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{9, 1} -} - -// Required. The flow used by the OAuth2 security scheme. Valid values are -// "implicit", "password", "application" or "accessCode". -type SecurityScheme_Flow int32 - -const ( - SecurityScheme_FLOW_INVALID SecurityScheme_Flow = 0 - SecurityScheme_FLOW_IMPLICIT SecurityScheme_Flow = 1 - SecurityScheme_FLOW_PASSWORD SecurityScheme_Flow = 2 - SecurityScheme_FLOW_APPLICATION SecurityScheme_Flow = 3 - SecurityScheme_FLOW_ACCESS_CODE SecurityScheme_Flow = 4 -) - -var SecurityScheme_Flow_name = map[int32]string{ - 0: "FLOW_INVALID", - 1: "FLOW_IMPLICIT", - 2: "FLOW_PASSWORD", - 3: "FLOW_APPLICATION", - 4: "FLOW_ACCESS_CODE", -} -var SecurityScheme_Flow_value = map[string]int32{ - "FLOW_INVALID": 0, - "FLOW_IMPLICIT": 1, - "FLOW_PASSWORD": 2, - "FLOW_APPLICATION": 3, - "FLOW_ACCESS_CODE": 4, -} - -func (x SecurityScheme_Flow) String() string { - return proto.EnumName(SecurityScheme_Flow_name, int32(x)) -} -func (SecurityScheme_Flow) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{9, 2} -} - -// `Swagger` is a representation of OpenAPI v2 specification's Swagger object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject -// -// TODO(ivucica): document fields -type Swagger struct { - Swagger string `protobuf:"bytes,1,opt,name=swagger" json:"swagger,omitempty"` - Info *Info `protobuf:"bytes,2,opt,name=info" json:"info,omitempty"` - Host string `protobuf:"bytes,3,opt,name=host" json:"host,omitempty"` - BasePath string `protobuf:"bytes,4,opt,name=base_path,json=basePath" json:"base_path,omitempty"` - Schemes []Swagger_SwaggerScheme `protobuf:"varint,5,rep,packed,name=schemes,enum=grpc.gateway.protoc_gen_swagger.options.Swagger_SwaggerScheme" json:"schemes,omitempty"` - Consumes []string `protobuf:"bytes,6,rep,name=consumes" json:"consumes,omitempty"` - Produces []string `protobuf:"bytes,7,rep,name=produces" json:"produces,omitempty"` - SecurityDefinitions *SecurityDefinitions `protobuf:"bytes,11,opt,name=security_definitions,json=securityDefinitions" json:"security_definitions,omitempty"` - Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security" json:"security,omitempty"` - ExternalDocs *ExternalDocumentation `protobuf:"bytes,14,opt,name=external_docs,json=externalDocs" json:"external_docs,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Swagger) Reset() { *m = Swagger{} } -func (m *Swagger) String() string { return proto.CompactTextString(m) } -func (*Swagger) ProtoMessage() {} -func (*Swagger) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{0} -} -func (m *Swagger) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Swagger.Unmarshal(m, b) -} -func (m *Swagger) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Swagger.Marshal(b, m, deterministic) -} -func (dst *Swagger) XXX_Merge(src proto.Message) { - xxx_messageInfo_Swagger.Merge(dst, src) -} -func (m *Swagger) XXX_Size() int { - return xxx_messageInfo_Swagger.Size(m) -} -func (m *Swagger) XXX_DiscardUnknown() { - xxx_messageInfo_Swagger.DiscardUnknown(m) -} - -var xxx_messageInfo_Swagger proto.InternalMessageInfo - -func (m *Swagger) GetSwagger() string { - if m != nil { - return m.Swagger - } - return "" -} - -func (m *Swagger) GetInfo() *Info { - if m != nil { - return m.Info - } - return nil -} - -func (m *Swagger) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *Swagger) GetBasePath() string { - if m != nil { - return m.BasePath - } - return "" -} - -func (m *Swagger) GetSchemes() []Swagger_SwaggerScheme { - if m != nil { - return m.Schemes - } - return nil -} - -func (m *Swagger) GetConsumes() []string { - if m != nil { - return m.Consumes - } - return nil -} - -func (m *Swagger) GetProduces() []string { - if m != nil { - return m.Produces - } - return nil -} - -func (m *Swagger) GetSecurityDefinitions() *SecurityDefinitions { - if m != nil { - return m.SecurityDefinitions - } - return nil -} - -func (m *Swagger) GetSecurity() []*SecurityRequirement { - if m != nil { - return m.Security - } - return nil -} - -func (m *Swagger) GetExternalDocs() *ExternalDocumentation { - if m != nil { - return m.ExternalDocs - } - return nil -} - -// `Operation` is a representation of OpenAPI v2 specification's Operation object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject -// -// TODO(ivucica): document fields -type Operation struct { - Tags []string `protobuf:"bytes,1,rep,name=tags" json:"tags,omitempty"` - Summary string `protobuf:"bytes,2,opt,name=summary" json:"summary,omitempty"` - Description string `protobuf:"bytes,3,opt,name=description" json:"description,omitempty"` - ExternalDocs *ExternalDocumentation `protobuf:"bytes,4,opt,name=external_docs,json=externalDocs" json:"external_docs,omitempty"` - OperationId string `protobuf:"bytes,5,opt,name=operation_id,json=operationId" json:"operation_id,omitempty"` - Consumes []string `protobuf:"bytes,6,rep,name=consumes" json:"consumes,omitempty"` - Produces []string `protobuf:"bytes,7,rep,name=produces" json:"produces,omitempty"` - Schemes []string `protobuf:"bytes,10,rep,name=schemes" json:"schemes,omitempty"` - Deprecated bool `protobuf:"varint,11,opt,name=deprecated" json:"deprecated,omitempty"` - Security []*SecurityRequirement `protobuf:"bytes,12,rep,name=security" json:"security,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Operation) Reset() { *m = Operation{} } -func (m *Operation) String() string { return proto.CompactTextString(m) } -func (*Operation) ProtoMessage() {} -func (*Operation) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{1} -} -func (m *Operation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Operation.Unmarshal(m, b) -} -func (m *Operation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Operation.Marshal(b, m, deterministic) -} -func (dst *Operation) XXX_Merge(src proto.Message) { - xxx_messageInfo_Operation.Merge(dst, src) -} -func (m *Operation) XXX_Size() int { - return xxx_messageInfo_Operation.Size(m) -} -func (m *Operation) XXX_DiscardUnknown() { - xxx_messageInfo_Operation.DiscardUnknown(m) -} - -var xxx_messageInfo_Operation proto.InternalMessageInfo - -func (m *Operation) GetTags() []string { - if m != nil { - return m.Tags - } - return nil -} - -func (m *Operation) GetSummary() string { - if m != nil { - return m.Summary - } - return "" -} - -func (m *Operation) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Operation) GetExternalDocs() *ExternalDocumentation { - if m != nil { - return m.ExternalDocs - } - return nil -} - -func (m *Operation) GetOperationId() string { - if m != nil { - return m.OperationId - } - return "" -} - -func (m *Operation) GetConsumes() []string { - if m != nil { - return m.Consumes - } - return nil -} - -func (m *Operation) GetProduces() []string { - if m != nil { - return m.Produces - } - return nil -} - -func (m *Operation) GetSchemes() []string { - if m != nil { - return m.Schemes - } - return nil -} - -func (m *Operation) GetDeprecated() bool { - if m != nil { - return m.Deprecated - } - return false -} - -func (m *Operation) GetSecurity() []*SecurityRequirement { - if m != nil { - return m.Security - } - return nil -} - -// `Info` is a representation of OpenAPI v2 specification's Info object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject -// -// TODO(ivucica): document fields -type Info struct { - Title string `protobuf:"bytes,1,opt,name=title" json:"title,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` - TermsOfService string `protobuf:"bytes,3,opt,name=terms_of_service,json=termsOfService" json:"terms_of_service,omitempty"` - Contact *Contact `protobuf:"bytes,4,opt,name=contact" json:"contact,omitempty"` - Version string `protobuf:"bytes,6,opt,name=version" json:"version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Info) Reset() { *m = Info{} } -func (m *Info) String() string { return proto.CompactTextString(m) } -func (*Info) ProtoMessage() {} -func (*Info) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{2} -} -func (m *Info) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Info.Unmarshal(m, b) -} -func (m *Info) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Info.Marshal(b, m, deterministic) -} -func (dst *Info) XXX_Merge(src proto.Message) { - xxx_messageInfo_Info.Merge(dst, src) -} -func (m *Info) XXX_Size() int { - return xxx_messageInfo_Info.Size(m) -} -func (m *Info) XXX_DiscardUnknown() { - xxx_messageInfo_Info.DiscardUnknown(m) -} - -var xxx_messageInfo_Info proto.InternalMessageInfo - -func (m *Info) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *Info) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Info) GetTermsOfService() string { - if m != nil { - return m.TermsOfService - } - return "" -} - -func (m *Info) GetContact() *Contact { - if m != nil { - return m.Contact - } - return nil -} - -func (m *Info) GetVersion() string { - if m != nil { - return m.Version - } - return "" -} - -// `Contact` is a representation of OpenAPI v2 specification's Contact object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject -// -// TODO(ivucica): document fields -type Contact struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Url string `protobuf:"bytes,2,opt,name=url" json:"url,omitempty"` - Email string `protobuf:"bytes,3,opt,name=email" json:"email,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Contact) Reset() { *m = Contact{} } -func (m *Contact) String() string { return proto.CompactTextString(m) } -func (*Contact) ProtoMessage() {} -func (*Contact) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{3} -} -func (m *Contact) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Contact.Unmarshal(m, b) -} -func (m *Contact) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Contact.Marshal(b, m, deterministic) -} -func (dst *Contact) XXX_Merge(src proto.Message) { - xxx_messageInfo_Contact.Merge(dst, src) -} -func (m *Contact) XXX_Size() int { - return xxx_messageInfo_Contact.Size(m) -} -func (m *Contact) XXX_DiscardUnknown() { - xxx_messageInfo_Contact.DiscardUnknown(m) -} - -var xxx_messageInfo_Contact proto.InternalMessageInfo - -func (m *Contact) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Contact) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -func (m *Contact) GetEmail() string { - if m != nil { - return m.Email - } - return "" -} - -// `ExternalDocumentation` is a representation of OpenAPI v2 specification's -// ExternalDocumentation object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject -// -// TODO(ivucica): document fields -type ExternalDocumentation struct { - Description string `protobuf:"bytes,1,opt,name=description" json:"description,omitempty"` - Url string `protobuf:"bytes,2,opt,name=url" json:"url,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExternalDocumentation) Reset() { *m = ExternalDocumentation{} } -func (m *ExternalDocumentation) String() string { return proto.CompactTextString(m) } -func (*ExternalDocumentation) ProtoMessage() {} -func (*ExternalDocumentation) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{4} -} -func (m *ExternalDocumentation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExternalDocumentation.Unmarshal(m, b) -} -func (m *ExternalDocumentation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExternalDocumentation.Marshal(b, m, deterministic) -} -func (dst *ExternalDocumentation) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExternalDocumentation.Merge(dst, src) -} -func (m *ExternalDocumentation) XXX_Size() int { - return xxx_messageInfo_ExternalDocumentation.Size(m) -} -func (m *ExternalDocumentation) XXX_DiscardUnknown() { - xxx_messageInfo_ExternalDocumentation.DiscardUnknown(m) -} - -var xxx_messageInfo_ExternalDocumentation proto.InternalMessageInfo - -func (m *ExternalDocumentation) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *ExternalDocumentation) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -// `Schema` is a representation of OpenAPI v2 specification's Schema object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject -// -// TODO(ivucica): document fields -type Schema struct { - JsonSchema *JSONSchema `protobuf:"bytes,1,opt,name=json_schema,json=jsonSchema" json:"json_schema,omitempty"` - Discriminator string `protobuf:"bytes,2,opt,name=discriminator" json:"discriminator,omitempty"` - ReadOnly bool `protobuf:"varint,3,opt,name=read_only,json=readOnly" json:"read_only,omitempty"` - ExternalDocs *ExternalDocumentation `protobuf:"bytes,5,opt,name=external_docs,json=externalDocs" json:"external_docs,omitempty"` - Example *any.Any `protobuf:"bytes,6,opt,name=example" json:"example,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Schema) Reset() { *m = Schema{} } -func (m *Schema) String() string { return proto.CompactTextString(m) } -func (*Schema) ProtoMessage() {} -func (*Schema) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{5} -} -func (m *Schema) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Schema.Unmarshal(m, b) -} -func (m *Schema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Schema.Marshal(b, m, deterministic) -} -func (dst *Schema) XXX_Merge(src proto.Message) { - xxx_messageInfo_Schema.Merge(dst, src) -} -func (m *Schema) XXX_Size() int { - return xxx_messageInfo_Schema.Size(m) -} -func (m *Schema) XXX_DiscardUnknown() { - xxx_messageInfo_Schema.DiscardUnknown(m) -} - -var xxx_messageInfo_Schema proto.InternalMessageInfo - -func (m *Schema) GetJsonSchema() *JSONSchema { - if m != nil { - return m.JsonSchema - } - return nil -} - -func (m *Schema) GetDiscriminator() string { - if m != nil { - return m.Discriminator - } - return "" -} - -func (m *Schema) GetReadOnly() bool { - if m != nil { - return m.ReadOnly - } - return false -} - -func (m *Schema) GetExternalDocs() *ExternalDocumentation { - if m != nil { - return m.ExternalDocs - } - return nil -} - -func (m *Schema) GetExample() *any.Any { - if m != nil { - return m.Example - } - return nil -} - -// `JSONSchema` represents properties from JSON Schema taken, and as used, in -// the OpenAPI v2 spec. -// -// This includes changes made by OpenAPI v2. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject -// -// See also: https://cswr.github.io/JsonSchema/spec/basic_types/, -// https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json -// -// TODO(ivucica): document fields -type JSONSchema struct { - Title string `protobuf:"bytes,5,opt,name=title" json:"title,omitempty"` - Description string `protobuf:"bytes,6,opt,name=description" json:"description,omitempty"` - Default string `protobuf:"bytes,7,opt,name=default" json:"default,omitempty"` - MultipleOf float64 `protobuf:"fixed64,10,opt,name=multiple_of,json=multipleOf" json:"multiple_of,omitempty"` - Maximum float64 `protobuf:"fixed64,11,opt,name=maximum" json:"maximum,omitempty"` - ExclusiveMaximum bool `protobuf:"varint,12,opt,name=exclusive_maximum,json=exclusiveMaximum" json:"exclusive_maximum,omitempty"` - Minimum float64 `protobuf:"fixed64,13,opt,name=minimum" json:"minimum,omitempty"` - ExclusiveMinimum bool `protobuf:"varint,14,opt,name=exclusive_minimum,json=exclusiveMinimum" json:"exclusive_minimum,omitempty"` - MaxLength uint64 `protobuf:"varint,15,opt,name=max_length,json=maxLength" json:"max_length,omitempty"` - MinLength uint64 `protobuf:"varint,16,opt,name=min_length,json=minLength" json:"min_length,omitempty"` - Pattern string `protobuf:"bytes,17,opt,name=pattern" json:"pattern,omitempty"` - MaxItems uint64 `protobuf:"varint,20,opt,name=max_items,json=maxItems" json:"max_items,omitempty"` - MinItems uint64 `protobuf:"varint,21,opt,name=min_items,json=minItems" json:"min_items,omitempty"` - UniqueItems bool `protobuf:"varint,22,opt,name=unique_items,json=uniqueItems" json:"unique_items,omitempty"` - MaxProperties uint64 `protobuf:"varint,24,opt,name=max_properties,json=maxProperties" json:"max_properties,omitempty"` - MinProperties uint64 `protobuf:"varint,25,opt,name=min_properties,json=minProperties" json:"min_properties,omitempty"` - Required []string `protobuf:"bytes,26,rep,name=required" json:"required,omitempty"` - // Items in 'array' must be unique. - Array []string `protobuf:"bytes,34,rep,name=array" json:"array,omitempty"` - Type []JSONSchema_JSONSchemaSimpleTypes `protobuf:"varint,35,rep,packed,name=type,enum=grpc.gateway.protoc_gen_swagger.options.JSONSchema_JSONSchemaSimpleTypes" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *JSONSchema) Reset() { *m = JSONSchema{} } -func (m *JSONSchema) String() string { return proto.CompactTextString(m) } -func (*JSONSchema) ProtoMessage() {} -func (*JSONSchema) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{6} -} -func (m *JSONSchema) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_JSONSchema.Unmarshal(m, b) -} -func (m *JSONSchema) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_JSONSchema.Marshal(b, m, deterministic) -} -func (dst *JSONSchema) XXX_Merge(src proto.Message) { - xxx_messageInfo_JSONSchema.Merge(dst, src) -} -func (m *JSONSchema) XXX_Size() int { - return xxx_messageInfo_JSONSchema.Size(m) -} -func (m *JSONSchema) XXX_DiscardUnknown() { - xxx_messageInfo_JSONSchema.DiscardUnknown(m) -} - -var xxx_messageInfo_JSONSchema proto.InternalMessageInfo - -func (m *JSONSchema) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *JSONSchema) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *JSONSchema) GetDefault() string { - if m != nil { - return m.Default - } - return "" -} - -func (m *JSONSchema) GetMultipleOf() float64 { - if m != nil { - return m.MultipleOf - } - return 0 -} - -func (m *JSONSchema) GetMaximum() float64 { - if m != nil { - return m.Maximum - } - return 0 -} - -func (m *JSONSchema) GetExclusiveMaximum() bool { - if m != nil { - return m.ExclusiveMaximum - } - return false -} - -func (m *JSONSchema) GetMinimum() float64 { - if m != nil { - return m.Minimum - } - return 0 -} - -func (m *JSONSchema) GetExclusiveMinimum() bool { - if m != nil { - return m.ExclusiveMinimum - } - return false -} - -func (m *JSONSchema) GetMaxLength() uint64 { - if m != nil { - return m.MaxLength - } - return 0 -} - -func (m *JSONSchema) GetMinLength() uint64 { - if m != nil { - return m.MinLength - } - return 0 -} - -func (m *JSONSchema) GetPattern() string { - if m != nil { - return m.Pattern - } - return "" -} - -func (m *JSONSchema) GetMaxItems() uint64 { - if m != nil { - return m.MaxItems - } - return 0 -} - -func (m *JSONSchema) GetMinItems() uint64 { - if m != nil { - return m.MinItems - } - return 0 -} - -func (m *JSONSchema) GetUniqueItems() bool { - if m != nil { - return m.UniqueItems - } - return false -} - -func (m *JSONSchema) GetMaxProperties() uint64 { - if m != nil { - return m.MaxProperties - } - return 0 -} - -func (m *JSONSchema) GetMinProperties() uint64 { - if m != nil { - return m.MinProperties - } - return 0 -} - -func (m *JSONSchema) GetRequired() []string { - if m != nil { - return m.Required - } - return nil -} - -func (m *JSONSchema) GetArray() []string { - if m != nil { - return m.Array - } - return nil -} - -func (m *JSONSchema) GetType() []JSONSchema_JSONSchemaSimpleTypes { - if m != nil { - return m.Type - } - return nil -} - -// `Tag` is a representation of OpenAPI v2 specification's Tag object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject -// -// TODO(ivucica): document fields -type Tag struct { - // TODO(ivucica): Description should be extracted from comments on the proto - // service object. - Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` - ExternalDocs *ExternalDocumentation `protobuf:"bytes,3,opt,name=external_docs,json=externalDocs" json:"external_docs,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Tag) Reset() { *m = Tag{} } -func (m *Tag) String() string { return proto.CompactTextString(m) } -func (*Tag) ProtoMessage() {} -func (*Tag) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{7} -} -func (m *Tag) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Tag.Unmarshal(m, b) -} -func (m *Tag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Tag.Marshal(b, m, deterministic) -} -func (dst *Tag) XXX_Merge(src proto.Message) { - xxx_messageInfo_Tag.Merge(dst, src) -} -func (m *Tag) XXX_Size() int { - return xxx_messageInfo_Tag.Size(m) -} -func (m *Tag) XXX_DiscardUnknown() { - xxx_messageInfo_Tag.DiscardUnknown(m) -} - -var xxx_messageInfo_Tag proto.InternalMessageInfo - -func (m *Tag) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Tag) GetExternalDocs() *ExternalDocumentation { - if m != nil { - return m.ExternalDocs - } - return nil -} - -// `SecurityDefinitions` is a representation of OpenAPI v2 specification's -// Security Definitions object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject -// -// A declaration of the security schemes available to be used in the -// specification. This does not enforce the security schemes on the operations -// and only serves to provide the relevant details for each scheme. -type SecurityDefinitions struct { - // A single security scheme definition, mapping a "name" to the scheme it defines. - Security map[string]*SecurityScheme `protobuf:"bytes,1,rep,name=security" json:"security,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SecurityDefinitions) Reset() { *m = SecurityDefinitions{} } -func (m *SecurityDefinitions) String() string { return proto.CompactTextString(m) } -func (*SecurityDefinitions) ProtoMessage() {} -func (*SecurityDefinitions) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{8} -} -func (m *SecurityDefinitions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SecurityDefinitions.Unmarshal(m, b) -} -func (m *SecurityDefinitions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SecurityDefinitions.Marshal(b, m, deterministic) -} -func (dst *SecurityDefinitions) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecurityDefinitions.Merge(dst, src) -} -func (m *SecurityDefinitions) XXX_Size() int { - return xxx_messageInfo_SecurityDefinitions.Size(m) -} -func (m *SecurityDefinitions) XXX_DiscardUnknown() { - xxx_messageInfo_SecurityDefinitions.DiscardUnknown(m) -} - -var xxx_messageInfo_SecurityDefinitions proto.InternalMessageInfo - -func (m *SecurityDefinitions) GetSecurity() map[string]*SecurityScheme { - if m != nil { - return m.Security - } - return nil -} - -// `SecurityScheme` is a representation of OpenAPI v2 specification's -// Security Scheme object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject -// -// Allows the definition of a security scheme that can be used by the -// operations. Supported schemes are basic authentication, an API key (either as -// a header or as a query parameter) and OAuth2's common flows (implicit, -// password, application and access code). -type SecurityScheme struct { - // Required. The type of the security scheme. Valid values are "basic", - // "apiKey" or "oauth2". - Type SecurityScheme_Type `protobuf:"varint,1,opt,name=type,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Type" json:"type,omitempty"` - // A short description for security scheme. - Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` - // Required. The name of the header or query parameter to be used. - // - // Valid for apiKey. - Name string `protobuf:"bytes,3,opt,name=name" json:"name,omitempty"` - // Required. The location of the API key. Valid values are "query" or "header". - // - // Valid for apiKey. - In SecurityScheme_In `protobuf:"varint,4,opt,name=in,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_In" json:"in,omitempty"` - // Required. The flow used by the OAuth2 security scheme. Valid values are - // "implicit", "password", "application" or "accessCode". - // - // Valid for oauth2. - Flow SecurityScheme_Flow `protobuf:"varint,5,opt,name=flow,enum=grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Flow" json:"flow,omitempty"` - // Required. The authorization URL to be used for this flow. This SHOULD be in - // the form of a URL. - // - // Valid for oauth2/implicit and oauth2/accessCode. - AuthorizationUrl string `protobuf:"bytes,6,opt,name=authorization_url,json=authorizationUrl" json:"authorization_url,omitempty"` - // Required. The token URL to be used for this flow. This SHOULD be in the - // form of a URL. - // - // Valid for oauth2/password, oauth2/application and oauth2/accessCode. - TokenUrl string `protobuf:"bytes,7,opt,name=token_url,json=tokenUrl" json:"token_url,omitempty"` - // Required. The available scopes for the OAuth2 security scheme. - // - // Valid for oauth2. - Scopes *Scopes `protobuf:"bytes,8,opt,name=scopes" json:"scopes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SecurityScheme) Reset() { *m = SecurityScheme{} } -func (m *SecurityScheme) String() string { return proto.CompactTextString(m) } -func (*SecurityScheme) ProtoMessage() {} -func (*SecurityScheme) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{9} -} -func (m *SecurityScheme) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SecurityScheme.Unmarshal(m, b) -} -func (m *SecurityScheme) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SecurityScheme.Marshal(b, m, deterministic) -} -func (dst *SecurityScheme) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecurityScheme.Merge(dst, src) -} -func (m *SecurityScheme) XXX_Size() int { - return xxx_messageInfo_SecurityScheme.Size(m) -} -func (m *SecurityScheme) XXX_DiscardUnknown() { - xxx_messageInfo_SecurityScheme.DiscardUnknown(m) -} - -var xxx_messageInfo_SecurityScheme proto.InternalMessageInfo - -func (m *SecurityScheme) GetType() SecurityScheme_Type { - if m != nil { - return m.Type - } - return SecurityScheme_TYPE_INVALID -} - -func (m *SecurityScheme) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *SecurityScheme) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *SecurityScheme) GetIn() SecurityScheme_In { - if m != nil { - return m.In - } - return SecurityScheme_IN_INVALID -} - -func (m *SecurityScheme) GetFlow() SecurityScheme_Flow { - if m != nil { - return m.Flow - } - return SecurityScheme_FLOW_INVALID -} - -func (m *SecurityScheme) GetAuthorizationUrl() string { - if m != nil { - return m.AuthorizationUrl - } - return "" -} - -func (m *SecurityScheme) GetTokenUrl() string { - if m != nil { - return m.TokenUrl - } - return "" -} - -func (m *SecurityScheme) GetScopes() *Scopes { - if m != nil { - return m.Scopes - } - return nil -} - -// `SecurityRequirement` is a representation of OpenAPI v2 specification's -// Security Requirement object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject -// -// Lists the required security schemes to execute this operation. The object can -// have multiple security schemes declared in it which are all required (that -// is, there is a logical AND between the schemes). -// -// The name used for each property MUST correspond to a security scheme -// declared in the Security Definitions. -type SecurityRequirement struct { - // Each name must correspond to a security scheme which is declared in - // the Security Definitions. If the security scheme is of type "oauth2", - // then the value is a list of scope names required for the execution. - // For other security scheme types, the array MUST be empty. - SecurityRequirement map[string]*SecurityRequirement_SecurityRequirementValue `protobuf:"bytes,1,rep,name=security_requirement,json=securityRequirement" json:"security_requirement,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SecurityRequirement) Reset() { *m = SecurityRequirement{} } -func (m *SecurityRequirement) String() string { return proto.CompactTextString(m) } -func (*SecurityRequirement) ProtoMessage() {} -func (*SecurityRequirement) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{10} -} -func (m *SecurityRequirement) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SecurityRequirement.Unmarshal(m, b) -} -func (m *SecurityRequirement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SecurityRequirement.Marshal(b, m, deterministic) -} -func (dst *SecurityRequirement) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecurityRequirement.Merge(dst, src) -} -func (m *SecurityRequirement) XXX_Size() int { - return xxx_messageInfo_SecurityRequirement.Size(m) -} -func (m *SecurityRequirement) XXX_DiscardUnknown() { - xxx_messageInfo_SecurityRequirement.DiscardUnknown(m) -} - -var xxx_messageInfo_SecurityRequirement proto.InternalMessageInfo - -func (m *SecurityRequirement) GetSecurityRequirement() map[string]*SecurityRequirement_SecurityRequirementValue { - if m != nil { - return m.SecurityRequirement - } - return nil -} - -// If the security scheme is of type "oauth2", then the value is a list of -// scope names required for the execution. For other security scheme types, -// the array MUST be empty. -type SecurityRequirement_SecurityRequirementValue struct { - Scope []string `protobuf:"bytes,1,rep,name=scope" json:"scope,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SecurityRequirement_SecurityRequirementValue) Reset() { - *m = SecurityRequirement_SecurityRequirementValue{} -} -func (m *SecurityRequirement_SecurityRequirementValue) String() string { - return proto.CompactTextString(m) -} -func (*SecurityRequirement_SecurityRequirementValue) ProtoMessage() {} -func (*SecurityRequirement_SecurityRequirementValue) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{10, 0} -} -func (m *SecurityRequirement_SecurityRequirementValue) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Unmarshal(m, b) -} -func (m *SecurityRequirement_SecurityRequirementValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Marshal(b, m, deterministic) -} -func (dst *SecurityRequirement_SecurityRequirementValue) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Merge(dst, src) -} -func (m *SecurityRequirement_SecurityRequirementValue) XXX_Size() int { - return xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.Size(m) -} -func (m *SecurityRequirement_SecurityRequirementValue) XXX_DiscardUnknown() { - xxx_messageInfo_SecurityRequirement_SecurityRequirementValue.DiscardUnknown(m) -} - -var xxx_messageInfo_SecurityRequirement_SecurityRequirementValue proto.InternalMessageInfo - -func (m *SecurityRequirement_SecurityRequirementValue) GetScope() []string { - if m != nil { - return m.Scope - } - return nil -} - -// `Scopes` is a representation of OpenAPI v2 specification's Scopes object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject -// -// Lists the available scopes for an OAuth2 security scheme. -type Scopes struct { - // Maps between a name of a scope to a short description of it (as the value - // of the property). - Scope map[string]string `protobuf:"bytes,1,rep,name=scope" json:"scope,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Scopes) Reset() { *m = Scopes{} } -func (m *Scopes) String() string { return proto.CompactTextString(m) } -func (*Scopes) ProtoMessage() {} -func (*Scopes) Descriptor() ([]byte, []int) { - return fileDescriptor_openapiv2_4346354ad6fc20e0, []int{11} -} -func (m *Scopes) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Scopes.Unmarshal(m, b) -} -func (m *Scopes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Scopes.Marshal(b, m, deterministic) -} -func (dst *Scopes) XXX_Merge(src proto.Message) { - xxx_messageInfo_Scopes.Merge(dst, src) -} -func (m *Scopes) XXX_Size() int { - return xxx_messageInfo_Scopes.Size(m) -} -func (m *Scopes) XXX_DiscardUnknown() { - xxx_messageInfo_Scopes.DiscardUnknown(m) -} - -var xxx_messageInfo_Scopes proto.InternalMessageInfo - -func (m *Scopes) GetScope() map[string]string { - if m != nil { - return m.Scope - } - return nil -} - -func init() { - proto.RegisterType((*Swagger)(nil), "grpc.gateway.protoc_gen_swagger.options.Swagger") - proto.RegisterType((*Operation)(nil), "grpc.gateway.protoc_gen_swagger.options.Operation") - proto.RegisterType((*Info)(nil), "grpc.gateway.protoc_gen_swagger.options.Info") - proto.RegisterType((*Contact)(nil), "grpc.gateway.protoc_gen_swagger.options.Contact") - proto.RegisterType((*ExternalDocumentation)(nil), "grpc.gateway.protoc_gen_swagger.options.ExternalDocumentation") - proto.RegisterType((*Schema)(nil), "grpc.gateway.protoc_gen_swagger.options.Schema") - proto.RegisterType((*JSONSchema)(nil), "grpc.gateway.protoc_gen_swagger.options.JSONSchema") - proto.RegisterType((*Tag)(nil), "grpc.gateway.protoc_gen_swagger.options.Tag") - proto.RegisterType((*SecurityDefinitions)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityDefinitions") - proto.RegisterMapType((map[string]*SecurityScheme)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityDefinitions.SecurityEntry") - proto.RegisterType((*SecurityScheme)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityScheme") - proto.RegisterType((*SecurityRequirement)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement") - proto.RegisterMapType((map[string]*SecurityRequirement_SecurityRequirementValue)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement.SecurityRequirementEntry") - proto.RegisterType((*SecurityRequirement_SecurityRequirementValue)(nil), "grpc.gateway.protoc_gen_swagger.options.SecurityRequirement.SecurityRequirementValue") - proto.RegisterType((*Scopes)(nil), "grpc.gateway.protoc_gen_swagger.options.Scopes") - proto.RegisterMapType((map[string]string)(nil), "grpc.gateway.protoc_gen_swagger.options.Scopes.ScopeEntry") - proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.Swagger_SwaggerScheme", Swagger_SwaggerScheme_name, Swagger_SwaggerScheme_value) - proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.JSONSchema_JSONSchemaSimpleTypes", JSONSchema_JSONSchemaSimpleTypes_name, JSONSchema_JSONSchemaSimpleTypes_value) - proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Type", SecurityScheme_Type_name, SecurityScheme_Type_value) - proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_In", SecurityScheme_In_name, SecurityScheme_In_value) - proto.RegisterEnum("grpc.gateway.protoc_gen_swagger.options.SecurityScheme_Flow", SecurityScheme_Flow_name, SecurityScheme_Flow_value) -} - -func init() { - proto.RegisterFile("protoc-gen-swagger/options/openapiv2.proto", fileDescriptor_openapiv2_4346354ad6fc20e0) -} - -var fileDescriptor_openapiv2_4346354ad6fc20e0 = []byte{ - // 1664 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x58, 0x5b, 0x73, 0xdb, 0xc6, - 0x15, 0x0e, 0xc8, 0x25, 0x09, 0x1e, 0x4a, 0xcc, 0x7a, 0x2d, 0xb7, 0x88, 0x12, 0xbb, 0x0a, 0x9a, - 0x4e, 0x35, 0xf6, 0x98, 0x4a, 0x95, 0x87, 0x66, 0x32, 0x9d, 0xce, 0x50, 0x12, 0x63, 0x03, 0x96, - 0x49, 0x16, 0xa4, 0xa2, 0xb8, 0x33, 0x1d, 0xcc, 0x1a, 0x5c, 0x52, 0x88, 0x71, 0x61, 0x70, 0x91, - 0xc4, 0xfe, 0x82, 0x3e, 0x77, 0xfa, 0xda, 0x9f, 0xd1, 0xa7, 0xf6, 0x67, 0xf4, 0x97, 0xb4, 0x6f, - 0x7d, 0xea, 0xec, 0x05, 0x24, 0x74, 0x49, 0x86, 0x91, 0xed, 0x27, 0xee, 0xf9, 0xce, 0x65, 0xf7, - 0x5c, 0xf6, 0x9c, 0x05, 0xe1, 0xf1, 0x3c, 0x89, 0xb3, 0xd8, 0x7b, 0x3a, 0x63, 0xd1, 0xd3, 0xf4, - 0x82, 0xce, 0x66, 0x2c, 0xd9, 0x8b, 0xe7, 0x99, 0x1f, 0x47, 0xe9, 0x5e, 0x3c, 0x67, 0x11, 0x9d, - 0xfb, 0xe7, 0xfb, 0x1d, 0x21, 0x44, 0x7e, 0x3d, 0x4b, 0xe6, 0x5e, 0x67, 0x46, 0x33, 0x76, 0x41, - 0x17, 0x12, 0xf3, 0xdc, 0x19, 0x8b, 0x5c, 0xa5, 0xd8, 0x51, 0x8a, 0xdb, 0x1f, 0xcd, 0xe2, 0x78, - 0x16, 0xb0, 0x3d, 0x21, 0xf2, 0x3a, 0x9f, 0xee, 0xd1, 0x48, 0xc9, 0x9b, 0xff, 0xa8, 0x41, 0x63, - 0x24, 0xc5, 0x89, 0x01, 0x0d, 0xa5, 0x69, 0x68, 0x3b, 0xda, 0x6e, 0xd3, 0x29, 0x48, 0xd2, 0x05, - 0xe4, 0x47, 0xd3, 0xd8, 0xa8, 0xec, 0x68, 0xbb, 0xad, 0xfd, 0xa7, 0x9d, 0x35, 0x37, 0xee, 0x58, - 0xd1, 0x34, 0x76, 0x84, 0x2a, 0x21, 0x80, 0xce, 0xe2, 0x34, 0x33, 0xaa, 0xc2, 0xb2, 0x58, 0x93, - 0x8f, 0xa1, 0xf9, 0x9a, 0xa6, 0xcc, 0x9d, 0xd3, 0xec, 0xcc, 0x40, 0x82, 0xa1, 0x73, 0x60, 0x48, - 0xb3, 0x33, 0xf2, 0x2d, 0x34, 0x52, 0xef, 0x8c, 0x85, 0x2c, 0x35, 0x6a, 0x3b, 0xd5, 0xdd, 0xf6, - 0xfe, 0xef, 0xd7, 0xde, 0x56, 0x39, 0x54, 0xfc, 0x8e, 0x84, 0x19, 0xa7, 0x30, 0x47, 0xb6, 0x41, - 0xf7, 0xe2, 0x28, 0xcd, 0xb9, 0xe9, 0xfa, 0x4e, 0x95, 0xef, 0x5a, 0xd0, 0x9c, 0x37, 0x4f, 0xe2, - 0x49, 0xee, 0xb1, 0xd4, 0x68, 0x48, 0x5e, 0x41, 0x93, 0x18, 0xb6, 0x52, 0xe6, 0xe5, 0x89, 0x9f, - 0x2d, 0xdc, 0x09, 0x9b, 0xfa, 0x91, 0x2f, 0xb6, 0x33, 0x5a, 0x22, 0x2a, 0xbf, 0x5b, 0xff, 0x78, - 0xca, 0xc8, 0xd1, 0xca, 0x86, 0x73, 0x3f, 0xbd, 0x09, 0x92, 0x6f, 0x41, 0x2f, 0x60, 0x63, 0x63, - 0xa7, 0x7a, 0xa7, 0x4d, 0x1c, 0xf6, 0x7d, 0xee, 0x27, 0x2c, 0x64, 0x51, 0xe6, 0x2c, 0xad, 0x11, - 0x0f, 0x36, 0xd9, 0x65, 0xc6, 0x92, 0x88, 0x06, 0xee, 0x24, 0xf6, 0x52, 0xa3, 0x2d, 0x7c, 0x58, - 0x3f, 0xc4, 0x3d, 0xa5, 0x7d, 0x14, 0x7b, 0x39, 0xb7, 0x4d, 0x39, 0xec, 0x6c, 0xb0, 0x15, 0x9c, - 0x9a, 0x07, 0xb0, 0x79, 0x25, 0x03, 0xa4, 0x05, 0x8d, 0x93, 0xfe, 0x8b, 0xfe, 0xe0, 0xb4, 0x8f, - 0x3f, 0x20, 0x3a, 0xa0, 0xe7, 0xe3, 0xf1, 0x10, 0x6b, 0xa4, 0x09, 0x35, 0xbe, 0x1a, 0xe1, 0x0a, - 0xa9, 0x43, 0xe5, 0x74, 0x84, 0xab, 0xa4, 0x01, 0xd5, 0xd3, 0xd1, 0x08, 0x23, 0x1b, 0xe9, 0x3a, - 0x6e, 0xda, 0x48, 0x6f, 0x62, 0xb0, 0x91, 0x0e, 0xb8, 0x65, 0x23, 0x7d, 0x13, 0xb7, 0xcd, 0x7f, - 0x56, 0xa1, 0x39, 0x98, 0xb3, 0x44, 0xec, 0xcb, 0x8b, 0x2b, 0xa3, 0xb3, 0xd4, 0xd0, 0x44, 0xc6, - 0xc4, 0x5a, 0x54, 0x73, 0x1e, 0x86, 0x34, 0x59, 0x88, 0xb2, 0xe5, 0xd5, 0x2c, 0x49, 0xb2, 0x03, - 0xad, 0x09, 0x4b, 0xbd, 0xc4, 0x17, 0xbe, 0xa8, 0x8a, 0x2c, 0x43, 0x37, 0xc3, 0x83, 0xde, 0x7d, - 0x78, 0xc8, 0xa7, 0xb0, 0x11, 0x17, 0x1e, 0xb8, 0xfe, 0xc4, 0xa8, 0xc9, 0x73, 0x2c, 0x31, 0x6b, - 0x72, 0xe7, 0x4a, 0x35, 0x56, 0x77, 0x07, 0x04, 0x6b, 0x59, 0xfb, 0x8f, 0x00, 0x26, 0x6c, 0x9e, - 0x30, 0x8f, 0x66, 0x6c, 0x22, 0x2a, 0x57, 0x77, 0x4a, 0xc8, 0xfb, 0x2b, 0xb9, 0x72, 0x26, 0xcd, - 0x7f, 0x6b, 0x80, 0x78, 0x6f, 0x20, 0x5b, 0x50, 0xcb, 0xfc, 0x2c, 0x60, 0xaa, 0xe1, 0x48, 0xe2, - 0x7a, 0x82, 0x2a, 0x37, 0x13, 0xb4, 0x0b, 0x38, 0x63, 0x49, 0x98, 0xba, 0xf1, 0xd4, 0x4d, 0x59, - 0x72, 0xee, 0x7b, 0x4c, 0xe5, 0xb1, 0x2d, 0xf0, 0xc1, 0x74, 0x24, 0x51, 0x62, 0x43, 0xc3, 0x8b, - 0xa3, 0x8c, 0x7a, 0x99, 0x4a, 0xe2, 0xe7, 0x6b, 0xfb, 0x73, 0x28, 0xf5, 0x9c, 0xc2, 0x00, 0x0f, - 0xeb, 0x39, 0x4b, 0x52, 0x7e, 0xa6, 0xba, 0x2c, 0x29, 0x45, 0xda, 0x48, 0xaf, 0xe1, 0xba, 0xd9, - 0x83, 0x86, 0xd2, 0xe1, 0x15, 0x19, 0xd1, 0xb0, 0xf0, 0x4b, 0xac, 0x09, 0x86, 0x6a, 0x9e, 0x04, - 0xca, 0x1d, 0xbe, 0xe4, 0xee, 0xb3, 0x90, 0xfa, 0x81, 0x3a, 0xbb, 0x24, 0xcc, 0x17, 0xf0, 0xe0, - 0xd6, 0xfa, 0xb9, 0x1e, 0x17, 0xed, 0x66, 0x5c, 0x6e, 0x6c, 0x61, 0xfe, 0xab, 0x02, 0x75, 0x71, - 0xfd, 0x28, 0x19, 0x43, 0xeb, 0xbb, 0x34, 0x8e, 0x5c, 0x51, 0x0b, 0x54, 0xa8, 0xb7, 0xf6, 0xbf, - 0x58, 0x3b, 0x1c, 0xf6, 0x68, 0xd0, 0x97, 0x96, 0x1c, 0xe0, 0x76, 0x94, 0xd5, 0xcf, 0x60, 0x73, - 0xe2, 0xf3, 0x13, 0x84, 0x7e, 0x44, 0xb3, 0x38, 0x51, 0x9b, 0x5f, 0x05, 0x79, 0xab, 0x4f, 0x18, - 0x9d, 0xb8, 0x71, 0x14, 0x2c, 0x84, 0xb7, 0xba, 0xa3, 0x73, 0x60, 0x10, 0x05, 0xb7, 0x74, 0xa3, - 0xda, 0x7b, 0xb8, 0x6e, 0x1d, 0x68, 0xb0, 0x4b, 0x1a, 0xce, 0x03, 0x26, 0x92, 0xd7, 0xda, 0xdf, - 0xea, 0xc8, 0xb1, 0xd8, 0x29, 0xc6, 0x62, 0xa7, 0x1b, 0x2d, 0x9c, 0x42, 0xc8, 0x46, 0x3a, 0xc2, - 0x35, 0xf3, 0x7f, 0x75, 0x80, 0x95, 0xe3, 0xab, 0x7a, 0xad, 0xfd, 0x48, 0xbd, 0xd6, 0x6f, 0xe6, - 0xc5, 0x80, 0xc6, 0x84, 0x4d, 0x69, 0x1e, 0x64, 0x46, 0x43, 0x56, 0x8e, 0x22, 0xc9, 0x2f, 0xa0, - 0x15, 0xe6, 0x41, 0xe6, 0xcf, 0x03, 0xe6, 0xc6, 0x53, 0x03, 0x76, 0xb4, 0x5d, 0xcd, 0x81, 0x02, - 0x1a, 0x4c, 0xb9, 0x6a, 0x48, 0x2f, 0xfd, 0x30, 0x0f, 0xc5, 0x75, 0xd5, 0x9c, 0x82, 0x24, 0x4f, - 0xe0, 0x1e, 0xbb, 0xf4, 0x82, 0x3c, 0xf5, 0xcf, 0x99, 0x5b, 0xc8, 0x6c, 0x88, 0xd8, 0xe2, 0x25, - 0xe3, 0xa5, 0x12, 0xe6, 0x66, 0xfc, 0x48, 0x88, 0x6c, 0x2a, 0x33, 0x92, 0xbc, 0x66, 0x46, 0xc9, - 0xb4, 0xaf, 0x9b, 0x51, 0xc2, 0x0f, 0x01, 0x42, 0x7a, 0xe9, 0x06, 0x2c, 0x9a, 0x65, 0x67, 0xc6, - 0x87, 0x3b, 0xda, 0x2e, 0x72, 0x9a, 0x21, 0xbd, 0x3c, 0x16, 0x80, 0x60, 0xfb, 0x51, 0xc1, 0xc6, - 0x8a, 0xed, 0x47, 0x8a, 0x6d, 0x40, 0x63, 0x4e, 0x33, 0x9e, 0x14, 0xe3, 0x9e, 0x0c, 0x83, 0x22, - 0x79, 0x7d, 0x70, 0xbb, 0x7e, 0xc6, 0xc2, 0xd4, 0xd8, 0x12, 0x7a, 0x7a, 0x48, 0x2f, 0x2d, 0x4e, - 0x0b, 0xa6, 0x1f, 0x29, 0xe6, 0x03, 0xc5, 0xf4, 0x23, 0xc9, 0xfc, 0x14, 0x36, 0xf2, 0xc8, 0xff, - 0x3e, 0x67, 0x8a, 0xff, 0x33, 0x71, 0xf2, 0x96, 0xc4, 0xa4, 0xc8, 0xaf, 0xa0, 0xcd, 0x8d, 0xcf, - 0x13, 0xde, 0x5b, 0x33, 0x9f, 0xa5, 0x86, 0x21, 0x8c, 0x6c, 0x86, 0xf4, 0x72, 0xb8, 0x04, 0x85, - 0x98, 0x1f, 0x95, 0xc5, 0x3e, 0x52, 0x62, 0x7e, 0x54, 0x12, 0xdb, 0x06, 0x3d, 0x91, 0x1d, 0x6e, - 0x62, 0x6c, 0xcb, 0xc6, 0x5b, 0xd0, 0xbc, 0x3e, 0x68, 0x92, 0xd0, 0x85, 0x61, 0x0a, 0x86, 0x24, - 0xc8, 0x9f, 0x00, 0x65, 0x8b, 0x39, 0x33, 0x7e, 0x29, 0xde, 0x31, 0xd6, 0x1d, 0x6e, 0x5c, 0x69, - 0x39, 0xf2, 0x79, 0x79, 0x8e, 0x17, 0x73, 0x96, 0x3a, 0xc2, 0xac, 0x79, 0x01, 0x0f, 0x6e, 0x65, - 0x5f, 0x9d, 0xb7, 0x4d, 0xa8, 0x75, 0x1d, 0xa7, 0xfb, 0x0a, 0x6b, 0x1c, 0x3f, 0x18, 0x0c, 0x8e, - 0x7b, 0xdd, 0x3e, 0xae, 0x70, 0xc2, 0xea, 0x8f, 0x7b, 0xcf, 0x7a, 0x0e, 0xae, 0xf2, 0xa1, 0xdc, - 0x3f, 0x39, 0x3e, 0xc6, 0x88, 0x00, 0xd4, 0xfb, 0x27, 0x2f, 0x0f, 0x7a, 0x0e, 0xae, 0xf1, 0xf5, - 0xe0, 0xc0, 0xee, 0x1d, 0x8e, 0x71, 0x9d, 0xaf, 0x47, 0x63, 0xc7, 0xea, 0x3f, 0xc3, 0x0d, 0x1b, - 0xe9, 0x1a, 0xae, 0xd8, 0x48, 0xaf, 0xe0, 0xaa, 0x8d, 0xf4, 0xaa, 0x18, 0xd7, 0x08, 0xd7, 0xae, - 0x0d, 0x6d, 0x82, 0xef, 0xdb, 0x48, 0xbf, 0x8f, 0xb7, 0x6c, 0xa4, 0xff, 0x1c, 0x1b, 0x36, 0xd2, - 0x3f, 0xc6, 0x9f, 0xd8, 0x48, 0xff, 0x04, 0x3f, 0xb4, 0x91, 0xfe, 0x10, 0x3f, 0xb2, 0x91, 0xfe, - 0x08, 0x9b, 0x36, 0xd2, 0x3f, 0xc3, 0x8f, 0x6d, 0xa4, 0x3f, 0xc6, 0x4f, 0x6c, 0xa4, 0x3f, 0xc1, - 0x1d, 0xf3, 0xaf, 0x1a, 0x54, 0xc7, 0x74, 0xb6, 0xc6, 0x3c, 0xb8, 0xd1, 0x41, 0xaa, 0xef, 0xbe, - 0x83, 0x48, 0x77, 0xcd, 0xff, 0x6a, 0x70, 0xff, 0x96, 0x17, 0x1c, 0x99, 0x96, 0x26, 0xa7, 0x26, - 0x26, 0xa7, 0xfd, 0x36, 0x2f, 0xc2, 0x25, 0xd6, 0x8b, 0xb2, 0x64, 0xb1, 0x9a, 0xa3, 0xdb, 0x19, - 0x6c, 0x5e, 0x61, 0xf1, 0x9e, 0xff, 0x86, 0x2d, 0xd4, 0x34, 0xe0, 0x4b, 0xf2, 0x12, 0x6a, 0xe7, - 0x34, 0xc8, 0x99, 0x7a, 0xaf, 0xff, 0xf6, 0x27, 0x9f, 0x43, 0xbd, 0x98, 0xa5, 0x95, 0xaf, 0x2a, - 0x5f, 0x6a, 0xfc, 0x3b, 0xa1, 0x7d, 0x95, 0x4b, 0x86, 0xaa, 0xaa, 0xf9, 0xc6, 0xed, 0x3b, 0x3c, - 0x13, 0xa4, 0x99, 0x0e, 0x2f, 0x55, 0x59, 0xc8, 0x6b, 0xe4, 0xb9, 0x18, 0xab, 0xd5, 0xd2, 0x58, - 0xb5, 0xa1, 0xe2, 0x47, 0x62, 0xb8, 0xb7, 0xf7, 0xbf, 0xba, 0xeb, 0x29, 0xac, 0xc8, 0xa9, 0xf8, - 0x11, 0xf7, 0x69, 0x1a, 0xc4, 0x17, 0xa2, 0xbd, 0xbf, 0x85, 0x4f, 0x5f, 0x07, 0xf1, 0x85, 0x23, - 0x2c, 0xf1, 0xee, 0x4a, 0xf3, 0xec, 0x2c, 0x4e, 0xfc, 0x3f, 0xcb, 0x97, 0x1e, 0x9f, 0xcf, 0x72, - 0x42, 0xe0, 0x2b, 0x8c, 0x93, 0x24, 0xe0, 0x8d, 0x2e, 0x8b, 0xdf, 0x30, 0x29, 0x24, 0x07, 0x85, - 0x2e, 0x00, 0xce, 0x7c, 0x06, 0xf5, 0xd4, 0x8b, 0xe7, 0x2c, 0x35, 0x74, 0x91, 0xd6, 0xbd, 0xf5, - 0x4f, 0x27, 0xd4, 0x1c, 0xa5, 0x6e, 0xbe, 0x00, 0xc4, 0x83, 0x4e, 0x30, 0x6c, 0x8c, 0x5f, 0x0d, - 0x7b, 0xae, 0xd5, 0xff, 0xa6, 0x7b, 0x6c, 0x1d, 0xe1, 0x0f, 0x48, 0x1b, 0x40, 0x20, 0x07, 0xdd, - 0x91, 0x75, 0x88, 0xb5, 0xa5, 0x44, 0x77, 0x68, 0xb9, 0x2f, 0x7a, 0xaf, 0x70, 0x85, 0x7c, 0x08, - 0x2d, 0x81, 0x0c, 0xba, 0x27, 0xe3, 0xe7, 0xfb, 0xb8, 0x6a, 0xfe, 0x06, 0x2a, 0x56, 0xc4, 0x15, - 0xad, 0x7e, 0xc9, 0xd0, 0x06, 0xe8, 0x56, 0xdf, 0xfd, 0xc3, 0x49, 0xcf, 0xe1, 0xfd, 0x66, 0x13, - 0x9a, 0x56, 0xdf, 0x7d, 0xde, 0xeb, 0x1e, 0xf5, 0x1c, 0x5c, 0x31, 0xbf, 0x03, 0xc4, 0x03, 0xc4, - 0xad, 0x7f, 0x7d, 0x3c, 0x38, 0x2d, 0xa9, 0xdd, 0x83, 0x4d, 0x89, 0xbc, 0x1c, 0x1e, 0x5b, 0x87, - 0xd6, 0x18, 0x6b, 0x4b, 0x68, 0xd8, 0x1d, 0x8d, 0x4e, 0x07, 0xce, 0x11, 0xae, 0x90, 0x2d, 0xc0, - 0x02, 0xea, 0x0e, 0xb9, 0x54, 0x77, 0x6c, 0x0d, 0xfa, 0xb8, 0xba, 0x42, 0x0f, 0x0f, 0x7b, 0xa3, - 0x91, 0x7b, 0x38, 0x38, 0xea, 0x61, 0x64, 0xfe, 0xa7, 0xb2, 0xba, 0xad, 0xa5, 0x77, 0x29, 0xf9, - 0x8b, 0x56, 0xfa, 0x98, 0x4b, 0x56, 0x0c, 0x75, 0x75, 0x4f, 0xde, 0xe6, 0xd1, 0x7b, 0x1b, 0x26, - 0x6f, 0xf1, 0xf2, 0x2b, 0xaf, 0xc4, 0xd9, 0xfe, 0x1c, 0x8c, 0x5b, 0x14, 0xbe, 0xe1, 0x57, 0x8f, - 0xcf, 0x13, 0x91, 0x34, 0xf5, 0x65, 0x23, 0x89, 0xed, 0xbf, 0x6b, 0xb7, 0xaa, 0xfc, 0x50, 0x3b, - 0x78, 0x73, 0xb5, 0x1d, 0xbc, 0x73, 0xdf, 0xc4, 0x51, 0xcb, 0xcd, 0xe2, 0x6f, 0x1a, 0x7f, 0x73, - 0xf2, 0x5a, 0x23, 0xc3, 0xb2, 0x03, 0xad, 0x9f, 0x72, 0x3f, 0x85, 0xbe, 0xfc, 0x91, 0xc1, 0x53, - 0xce, 0x7f, 0x09, 0xb0, 0x02, 0x6f, 0xf1, 0x76, 0xab, 0xec, 0x6d, 0xb3, 0x74, 0xac, 0x83, 0xc3, - 0x3f, 0x76, 0x67, 0x7e, 0x76, 0x96, 0xbf, 0xee, 0x78, 0x71, 0xb8, 0xc7, 0x0f, 0xf2, 0x94, 0x79, - 0x71, 0xba, 0x48, 0x33, 0xa6, 0x48, 0x75, 0xae, 0xbd, 0x1f, 0xfe, 0x13, 0xe6, 0x75, 0x5d, 0xf0, - 0xbe, 0xf8, 0x7f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0xb7, 0xe4, 0x3d, 0xa9, 0x11, 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.proto deleted file mode 100755 index b3b9b89..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options/openapiv2.proto +++ /dev/null @@ -1,338 +0,0 @@ -syntax = "proto3"; - -package grpc.gateway.protoc_gen_swagger.options; - -option go_package = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"; - -import "google/protobuf/any.proto"; - -// `Swagger` is a representation of OpenAPI v2 specification's Swagger object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject -// -// TODO(ivucica): document fields -message Swagger { - string swagger = 1; - Info info = 2; - string host = 3; - string base_path = 4; - enum SwaggerScheme { - UNKNOWN = 0; - HTTP = 1; - HTTPS = 2; - WS = 3; - WSS = 4; - } - repeated SwaggerScheme schemes = 5; - repeated string consumes = 6; - repeated string produces = 7; - // field 8 is reserved for 'paths'. - reserved 8; - // field 9 is reserved for 'definitions', which at this time are already - // exposed as and customizable as proto messages. - reserved 9; - // field 10 is reserved for 'responses'. - reserved 10; - SecurityDefinitions security_definitions = 11; - repeated SecurityRequirement security = 12; - // field 13 is reserved for 'tags', which are supposed to be exposed as and - // customizable as proto services. TODO(ivucica): add processing of proto - // service objects into OpenAPI v2 Tag objects. - reserved 13; - ExternalDocumentation external_docs = 14; -} - -// `Operation` is a representation of OpenAPI v2 specification's Operation object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject -// -// TODO(ivucica): document fields -message Operation { - repeated string tags = 1; - string summary = 2; - string description = 3; - ExternalDocumentation external_docs = 4; - string operation_id = 5; - repeated string consumes = 6; - repeated string produces = 7; - // field 8 is reserved for 'parameters'. - reserved 8; - // field 9 is reserved for 'responses'. - reserved 9; - repeated string schemes = 10; - bool deprecated = 11; - repeated SecurityRequirement security = 12; -} - -// `Info` is a representation of OpenAPI v2 specification's Info object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject -// -// TODO(ivucica): document fields -message Info { - string title = 1; - string description = 2; - string terms_of_service = 3; - Contact contact = 4; - // field 5 is reserved for 'license'. - reserved 5; - string version = 6; -} - -// `Contact` is a representation of OpenAPI v2 specification's Contact object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject -// -// TODO(ivucica): document fields -message Contact { - string name = 1; - string url = 2; - string email = 3; -} - -// `ExternalDocumentation` is a representation of OpenAPI v2 specification's -// ExternalDocumentation object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject -// -// TODO(ivucica): document fields -message ExternalDocumentation { - string description = 1; - string url = 2; -} - -// `Schema` is a representation of OpenAPI v2 specification's Schema object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject -// -// TODO(ivucica): document fields -message Schema { - JSONSchema json_schema = 1; - string discriminator = 2; - bool read_only = 3; - // field 4 is reserved for 'xml'. - reserved 4; - ExternalDocumentation external_docs = 5; - google.protobuf.Any example = 6; -} - -// `JSONSchema` represents properties from JSON Schema taken, and as used, in -// the OpenAPI v2 spec. -// -// This includes changes made by OpenAPI v2. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject -// -// See also: https://cswr.github.io/JsonSchema/spec/basic_types/, -// https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json -// -// TODO(ivucica): document fields -message JSONSchema { - // field 1 is reserved for '$id', omitted from OpenAPI v2. - reserved 1; - // field 2 is reserved for '$schema', omitted from OpenAPI v2. - reserved 2; - // field 3 is reserved for '$ref', although it is unclear how it would be used. - reserved 3; - // field 4 is reserved for '$comment', omitted from OpenAPI v2. - reserved 4; - string title = 5; - string description = 6; - string default = 7; - // field 8 is reserved for 'readOnly', which has an OpenAPI v2-specific meaning and is defined there. - reserved 8; - // field 9 is reserved for 'examples', which is omitted from OpenAPI v2 in favor of 'example' field. - reserved 9; - double multiple_of = 10; - double maximum = 11; - bool exclusive_maximum = 12; - double minimum = 13; - bool exclusive_minimum = 14; - uint64 max_length = 15; - uint64 min_length = 16; - string pattern = 17; - // field 18 is reserved for 'additionalItems', omitted from OpenAPI v2. - reserved 18; - // field 19 is reserved for 'items', but in OpenAPI-specific way. TODO(ivucica): add 'items'? - reserved 19; - uint64 max_items = 20; - uint64 min_items = 21; - bool unique_items = 22; - // field 23 is reserved for 'contains', omitted from OpenAPI v2. - reserved 23; - uint64 max_properties = 24; - uint64 min_properties = 25; - repeated string required = 26; - // field 27 is reserved for 'additionalProperties', but in OpenAPI-specific way. TODO(ivucica): add 'additionalProperties'? - reserved 27; - // field 28 is reserved for 'definitions', omitted from OpenAPI v2. - reserved 28; - // field 29 is reserved for 'properties', but in OpenAPI-specific way. TODO(ivucica): add 'additionalProperties'? - reserved 29; - // following fields are reserved, as the properties have been omitted from OpenAPI v2: - // patternProperties, dependencies, propertyNames, const - reserved 30 to 33; - // Items in 'array' must be unique. - repeated string array = 34; - - enum JSONSchemaSimpleTypes { - UNKNOWN = 0; - ARRAY = 1; - BOOLEAN = 2; - INTEGER = 3; - NULL = 4; - NUMBER = 5; - OBJECT = 6; - STRING = 7; - } - - repeated JSONSchemaSimpleTypes type = 35; - // following fields are reserved, as the properties have been omitted from OpenAPI v2: - // format, contentMediaType, contentEncoding, if, then, else - reserved 36 to 41; - // field 42 is reserved for 'allOf', but in OpenAPI-specific way. TODO(ivucica): add 'allOf'? - reserved 42; - // following fields are reserved, as the properties have been omitted from OpenAPI v2: - // anyOf, oneOf, not - reserved 43 to 45; -} - -// `Tag` is a representation of OpenAPI v2 specification's Tag object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject -// -// TODO(ivucica): document fields -message Tag { - // field 1 is reserved for 'name'. In our generator, this is (to be) extracted - // from the name of proto service, and thus not exposed to the user, as - // changing tag object's name would break the link to the references to the - // tag in individual operation specifications. - // - // TODO(ivucica): Add 'name' property. Use it to allow override of the name of - // global Tag object, then use that name to reference the tag throughout the - // Swagger file. - reserved 1; - // TODO(ivucica): Description should be extracted from comments on the proto - // service object. - string description = 2; - ExternalDocumentation external_docs = 3; -} - -// `SecurityDefinitions` is a representation of OpenAPI v2 specification's -// Security Definitions object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject -// -// A declaration of the security schemes available to be used in the -// specification. This does not enforce the security schemes on the operations -// and only serves to provide the relevant details for each scheme. -message SecurityDefinitions { - // A single security scheme definition, mapping a "name" to the scheme it defines. - map security = 1; -} - -// `SecurityScheme` is a representation of OpenAPI v2 specification's -// Security Scheme object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject -// -// Allows the definition of a security scheme that can be used by the -// operations. Supported schemes are basic authentication, an API key (either as -// a header or as a query parameter) and OAuth2's common flows (implicit, -// password, application and access code). -message SecurityScheme { - // Required. The type of the security scheme. Valid values are "basic", - // "apiKey" or "oauth2". - enum Type { - TYPE_INVALID = 0; - TYPE_BASIC = 1; - TYPE_API_KEY = 2; - TYPE_OAUTH2 = 3; - } - - // Required. The location of the API key. Valid values are "query" or "header". - enum In { - IN_INVALID = 0; - IN_QUERY = 1; - IN_HEADER = 2; - } - - // Required. The flow used by the OAuth2 security scheme. Valid values are - // "implicit", "password", "application" or "accessCode". - enum Flow { - FLOW_INVALID = 0; - FLOW_IMPLICIT = 1; - FLOW_PASSWORD = 2; - FLOW_APPLICATION = 3; - FLOW_ACCESS_CODE = 4; - } - - // Required. The type of the security scheme. Valid values are "basic", - // "apiKey" or "oauth2". - Type type = 1; - // A short description for security scheme. - string description = 2; - // Required. The name of the header or query parameter to be used. - // - // Valid for apiKey. - string name = 3; - // Required. The location of the API key. Valid values are "query" or "header". - // - // Valid for apiKey. - In in = 4; - // Required. The flow used by the OAuth2 security scheme. Valid values are - // "implicit", "password", "application" or "accessCode". - // - // Valid for oauth2. - Flow flow = 5; - // Required. The authorization URL to be used for this flow. This SHOULD be in - // the form of a URL. - // - // Valid for oauth2/implicit and oauth2/accessCode. - string authorization_url = 6; - // Required. The token URL to be used for this flow. This SHOULD be in the - // form of a URL. - // - // Valid for oauth2/password, oauth2/application and oauth2/accessCode. - string token_url = 7; - // Required. The available scopes for the OAuth2 security scheme. - // - // Valid for oauth2. - Scopes scopes = 8; -} - -// `SecurityRequirement` is a representation of OpenAPI v2 specification's -// Security Requirement object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject -// -// Lists the required security schemes to execute this operation. The object can -// have multiple security schemes declared in it which are all required (that -// is, there is a logical AND between the schemes). -// -// The name used for each property MUST correspond to a security scheme -// declared in the Security Definitions. -message SecurityRequirement { - // If the security scheme is of type "oauth2", then the value is a list of - // scope names required for the execution. For other security scheme types, - // the array MUST be empty. - message SecurityRequirementValue { - repeated string scope = 1; - } - // Each name must correspond to a security scheme which is declared in - // the Security Definitions. If the security scheme is of type "oauth2", - // then the value is a list of scope names required for the execution. - // For other security scheme types, the array MUST be empty. - map security_requirement = 1; -} - -// `Scopes` is a representation of OpenAPI v2 specification's Scopes object. -// -// See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject -// -// Lists the available scopes for an OAuth2 security scheme. -message Scopes { - // Maps between a name of a scope to a short description of it (as the value - // of the property). - map scope = 1; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/repositories.bzl b/examples/github.com/grpc-ecosystem/grpc-gateway/repositories.bzl deleted file mode 100755 index 959b20c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/repositories.bzl +++ /dev/null @@ -1,49 +0,0 @@ -GOOGLEAPIS_GOOGLE_API_BUILD_CONTENTS = """ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") - -package(default_visibility = ["//visibility:public"]) - -proto_library( - name = "api_proto", - srcs = [ - "annotations.proto", - "http.proto", - ], - deps = ["@com_google_protobuf//:descriptor_proto"], -) - -go_proto_library( - name = "api_go_proto", - importpath = "google.golang.org/genproto/googleapis/api/annotations", - proto = ":api_proto", - deps = ["@com_github_golang_protobuf//protoc-gen-go/descriptor:go_default_library"], -) - -go_library( - name = "go_default_library", - embed = [":api_go_proto"], - importpath = "google.golang.org/genproto/googleapis/api/annotations", -) -""" - -def _googleapis_repository_impl(ctx): - googleapis_commit = "e1c0c726290a55065c0c46a62dacc9372939973b" - ctx.download_and_extract( - url = "https://github.com/googleapis/googleapis/archive/{commit}.tar.gz".format( - commit = googleapis_commit, - ), - sha256 = "9508971cb4a7c0fe03bc1bfafbd0abc9654c80b4c70e360a6c534938d06d8fb9", - stripPrefix = "googleapis-{}".format(googleapis_commit), - ) - - ctx.file("google/api/BUILD.bazel", GOOGLEAPIS_GOOGLE_API_BUILD_CONTENTS) - - -_googleapis_repository = repository_rule( - implementation = _googleapis_repository_impl, -) - - -def repositories(): - _googleapis_repository(name = "com_github_googleapis_googleapis") diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel deleted file mode 100755 index e04db4f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel +++ /dev/null @@ -1,82 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "context.go", - "convert.go", - "doc.go", - "errors.go", - "handler.go", - "marshal_json.go", - "marshal_jsonpb.go", - "marshal_proto.go", - "marshaler.go", - "marshaler_registry.go", - "mux.go", - "pattern.go", - "proto2_convert.go", - "proto_errors.go", - "query.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime", - deps = [ - "//runtime/internal:go_default_library", - "//utilities:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//ptypes:go_default_library", - "@com_github_golang_protobuf//ptypes/any:go_default_library", - "@com_github_golang_protobuf//ptypes/duration:go_default_library", - "@com_github_golang_protobuf//ptypes/timestamp:go_default_library", - "@org_golang_google_grpc//codes:go_default_library", - "@org_golang_google_grpc//grpclog:go_default_library", - "@org_golang_google_grpc//metadata:go_default_library", - "@org_golang_google_grpc//status:go_default_library", - ], -) - -go_test( - name = "go_default_test", - size = "small", - srcs = ["pattern_test.go"], - embed = [":go_default_library"], - deps = ["//utilities:go_default_library"], -) - -go_test( - name = "go_default_xtest", - size = "small", - srcs = [ - "context_test.go", - "errors_test.go", - "handler_test.go", - "marshal_json_test.go", - "marshal_jsonpb_test.go", - "marshal_proto_test.go", - "marshaler_registry_test.go", - "mux_test.go", - "query_test.go", - ], - deps = [ - ":go_default_library", - "//examples/proto/examplepb:go_default_library", - "//runtime/internal:go_default_library", - "//utilities:go_default_library", - "@com_github_golang_protobuf//jsonpb:go_default_library", - "@com_github_golang_protobuf//proto:go_default_library", - "@com_github_golang_protobuf//ptypes:go_default_library", - "@com_github_golang_protobuf//ptypes/duration:go_default_library", - "@com_github_golang_protobuf//ptypes/empty:go_default_library", - "@com_github_golang_protobuf//ptypes/struct:go_default_library", - "@com_github_golang_protobuf//ptypes/timestamp:go_default_library", - "@com_github_golang_protobuf//ptypes/wrappers:go_default_library", - "@org_golang_google_genproto//protobuf/field_mask:go_default_library", - "@org_golang_google_grpc//:go_default_library", - "@org_golang_google_grpc//codes:go_default_library", - "@org_golang_google_grpc//metadata:go_default_library", - "@org_golang_google_grpc//status:go_default_library", - ], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go deleted file mode 100755 index a745074..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go +++ /dev/null @@ -1,187 +0,0 @@ -package runtime - -import ( - "fmt" - "net" - "net/http" - "strconv" - "strings" - "time" - - "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// MetadataHeaderPrefix is the http prefix that represents custom metadata -// parameters to or from a gRPC call. -const MetadataHeaderPrefix = "Grpc-Metadata-" - -// MetadataPrefix is the prefix for grpc-gateway supplied custom metadata fields. -const MetadataPrefix = "grpcgateway-" - -// MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to -// HTTP headers in a response handled by grpc-gateway -const MetadataTrailerPrefix = "Grpc-Trailer-" - -const metadataGrpcTimeout = "Grpc-Timeout" - -const xForwardedFor = "X-Forwarded-For" -const xForwardedHost = "X-Forwarded-Host" - -var ( - // DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound - // header isn't present. If the value is 0 the sent `context` will not have a timeout. - DefaultContextTimeout = 0 * time.Second -) - -/* -AnnotateContext adds context information such as metadata from the request. - -At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", -except that the forwarded destination is not another HTTP service but rather -a gRPC service. -*/ -func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { - var pairs []string - timeout := DefaultContextTimeout - if tm := req.Header.Get(metadataGrpcTimeout); tm != "" { - var err error - timeout, err = timeoutDecode(tm) - if err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) - } - } - - for key, vals := range req.Header { - for _, val := range vals { - // For backwards-compatibility, pass through 'authorization' header with no prefix. - if strings.ToLower(key) == "authorization" { - pairs = append(pairs, "authorization", val) - } - if h, ok := mux.incomingHeaderMatcher(key); ok { - pairs = append(pairs, h, val) - } - } - } - if host := req.Header.Get(xForwardedHost); host != "" { - pairs = append(pairs, strings.ToLower(xForwardedHost), host) - } else if req.Host != "" { - pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) - } - - if addr := req.RemoteAddr; addr != "" { - if remoteIP, _, err := net.SplitHostPort(addr); err == nil { - if fwd := req.Header.Get(xForwardedFor); fwd == "" { - pairs = append(pairs, strings.ToLower(xForwardedFor), remoteIP) - } else { - pairs = append(pairs, strings.ToLower(xForwardedFor), fmt.Sprintf("%s, %s", fwd, remoteIP)) - } - } else { - grpclog.Printf("invalid remote addr: %s", addr) - } - } - - if timeout != 0 { - ctx, _ = context.WithTimeout(ctx, timeout) - } - if len(pairs) == 0 { - return ctx, nil - } - md := metadata.Pairs(pairs...) - for _, mda := range mux.metadataAnnotators { - md = metadata.Join(md, mda(ctx, req)) - } - return metadata.NewOutgoingContext(ctx, md), nil -} - -// ServerMetadata consists of metadata sent from gRPC server. -type ServerMetadata struct { - HeaderMD metadata.MD - TrailerMD metadata.MD -} - -type serverMetadataKey struct{} - -// NewServerMetadataContext creates a new context with ServerMetadata -func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context { - return context.WithValue(ctx, serverMetadataKey{}, md) -} - -// ServerMetadataFromContext returns the ServerMetadata in ctx -func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool) { - md, ok = ctx.Value(serverMetadataKey{}).(ServerMetadata) - return -} - -func timeoutDecode(s string) (time.Duration, error) { - size := len(s) - if size < 2 { - return 0, fmt.Errorf("timeout string is too short: %q", s) - } - d, ok := timeoutUnitToDuration(s[size-1]) - if !ok { - return 0, fmt.Errorf("timeout unit is not recognized: %q", s) - } - t, err := strconv.ParseInt(s[:size-1], 10, 64) - if err != nil { - return 0, err - } - return d * time.Duration(t), nil -} - -func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) { - switch u { - case 'H': - return time.Hour, true - case 'M': - return time.Minute, true - case 'S': - return time.Second, true - case 'm': - return time.Millisecond, true - case 'u': - return time.Microsecond, true - case 'n': - return time.Nanosecond, true - default: - } - return -} - -// isPermanentHTTPHeader checks whether hdr belongs to the list of -// permenant request headers maintained by IANA. -// http://www.iana.org/assignments/message-headers/message-headers.xml -func isPermanentHTTPHeader(hdr string) bool { - switch hdr { - case - "Accept", - "Accept-Charset", - "Accept-Language", - "Accept-Ranges", - "Authorization", - "Cache-Control", - "Content-Type", - "Cookie", - "Date", - "Expect", - "From", - "Host", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Schedule-Tag-Match", - "If-Unmodified-Since", - "Max-Forwards", - "Origin", - "Pragma", - "Referer", - "User-Agent", - "Via", - "Warning": - return true - } - return false -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go deleted file mode 100755 index e78a037..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/context_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package runtime_test - -import ( - "net/http" - "reflect" - "testing" - "time" - - "context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc/metadata" -) - -const ( - emptyForwardMetaCount = 1 -) - -func TestAnnotateContext_WorksWithEmpty(t *testing.T) { - ctx := context.Background() - - request, err := http.NewRequest("GET", "http://www.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) - } - request.Header.Add("Some-Irrelevant-Header", "some value") - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if !ok || len(md) != emptyForwardMetaCount { - t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount, md) - } -} - -func TestAnnotateContext_ForwardsGrpcMetadata(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://www.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err) - } - request.Header.Add("Some-Irrelevant-Header", "some value") - request.Header.Add("Grpc-Metadata-FooBar", "Value1") - request.Header.Add("Grpc-Metadata-Foo-BAZ", "Value2") - request.Header.Add("Grpc-Metadata-foo-bAz", "Value3") - request.Header.Add("Authorization", "Token 1234567890") - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if got, want := len(md), emptyForwardMetaCount+4; !ok || got != want { - t.Errorf("metadata items in context = %d want %d: %v", got, want, md) - } - if got, want := md["foobar"], []string{"Value1"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-foobar"] = %q; want %q`, got, want) - } - if got, want := md["foo-baz"], []string{"Value2", "Value3"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-foo-baz"] = %q want %q`, got, want) - } - if got, want := md["grpcgateway-authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["grpcgateway-authorization"] = %q want %q`, got, want) - } - if got, want := md["authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["authorization"] = %q want %q`, got, want) - } -} - -func TestAnnotateContext_XForwardedFor(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://bar.foo.example.com", nil) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://bar.foo.example.com", err) - } - request.Header.Add("X-Forwarded-For", "192.0.2.100") // client - request.RemoteAddr = "192.0.2.200:12345" // proxy - - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - md, ok := metadata.FromOutgoingContext(annotated) - if !ok || len(md) != emptyForwardMetaCount+1 { - t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md) - } - if got, want := md["x-forwarded-host"], []string{"bar.foo.example.com"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["host"] = %v; want %v`, got, want) - } - // Note: it must be in order client, proxy1, proxy2 - if got, want := md["x-forwarded-for"], []string{"192.0.2.100, 192.0.2.200"}; !reflect.DeepEqual(got, want) { - t.Errorf(`md["x-forwarded-for"] = %v want %v`, got, want) - } -} - -func TestAnnotateContext_SupportsTimeouts(t *testing.T) { - ctx := context.Background() - request, err := http.NewRequest("GET", "http://example.com", nil) - if err != nil { - t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) - } - annotated, err := runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - if _, ok := annotated.Deadline(); ok { - // no deadline by default - t.Errorf("annotated.Deadline() = _, true; want _, false") - } - - const acceptableError = 50 * time.Millisecond - runtime.DefaultContextTimeout = 10 * time.Second - annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - deadline, ok := annotated.Deadline() - if !ok { - t.Errorf("annotated.Deadline() = _, false; want _, true") - } - if got, want := deadline.Sub(time.Now()), runtime.DefaultContextTimeout; got-want > acceptableError || got-want < -acceptableError { - t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v", got, want, acceptableError) - } - - for _, spec := range []struct { - timeout string - want time.Duration - }{ - { - timeout: "17H", - want: 17 * time.Hour, - }, - { - timeout: "19M", - want: 19 * time.Minute, - }, - { - timeout: "23S", - want: 23 * time.Second, - }, - { - timeout: "1009m", - want: 1009 * time.Millisecond, - }, - { - timeout: "1000003u", - want: 1000003 * time.Microsecond, - }, - { - timeout: "100000007n", - want: 100000007 * time.Nanosecond, - }, - } { - request.Header.Set("Grpc-Timeout", spec.timeout) - annotated, err = runtime.AnnotateContext(ctx, runtime.NewServeMux(), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - deadline, ok := annotated.Deadline() - if !ok { - t.Errorf("annotated.Deadline() = _, false; want _, true; timeout = %q", spec.timeout) - } - if got, want := deadline.Sub(time.Now()), spec.want; got-want > acceptableError || got-want < -acceptableError { - t.Errorf("deadline.Sub(time.Now()) = %v; want %v; with error %v; timeout= %q", got, want, acceptableError, spec.timeout) - } - } -} -func TestAnnotateContext_SupportsCustomAnnotators(t *testing.T) { - md1 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"foo": "bar"}) } - md2 := func(context.Context, *http.Request) metadata.MD { return metadata.New(map[string]string{"baz": "qux"}) } - expected := metadata.New(map[string]string{"foo": "bar", "baz": "qux"}) - request, err := http.NewRequest("GET", "http://example.com", nil) - if err != nil { - t.Fatalf(`http.NewRequest("GET", "http://example.com", nil failed with %v; want success`, err) - } - annotated, err := runtime.AnnotateContext(context.Background(), runtime.NewServeMux(runtime.WithMetadata(md1), runtime.WithMetadata(md2)), request) - if err != nil { - t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err) - return - } - actual, _ := metadata.FromOutgoingContext(annotated) - for key, e := range expected { - if a, ok := actual[key]; !ok || !reflect.DeepEqual(e, a) { - t.Errorf("metadata.MD[%s] = %v; want %v", key, a, e) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go deleted file mode 100755 index 903ae23..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go +++ /dev/null @@ -1,87 +0,0 @@ -package runtime - -import ( - "encoding/base64" - "strconv" - - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/timestamp" -) - -// String just returns the given string. -// It is just for compatibility to other types. -func String(val string) (string, error) { - return val, nil -} - -// Bool converts the given string representation of a boolean value into bool. -func Bool(val string) (bool, error) { - return strconv.ParseBool(val) -} - -// Float64 converts the given string representation into representation of a floating point number into float64. -func Float64(val string) (float64, error) { - return strconv.ParseFloat(val, 64) -} - -// Float32 converts the given string representation of a floating point number into float32. -func Float32(val string) (float32, error) { - f, err := strconv.ParseFloat(val, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// Int64 converts the given string representation of an integer into int64. -func Int64(val string) (int64, error) { - return strconv.ParseInt(val, 0, 64) -} - -// Int32 converts the given string representation of an integer into int32. -func Int32(val string) (int32, error) { - i, err := strconv.ParseInt(val, 0, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// Uint64 converts the given string representation of an integer into uint64. -func Uint64(val string) (uint64, error) { - return strconv.ParseUint(val, 0, 64) -} - -// Uint32 converts the given string representation of an integer into uint32. -func Uint32(val string) (uint32, error) { - i, err := strconv.ParseUint(val, 0, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// Bytes converts the given string representation of a byte sequence into a slice of bytes -// A bytes sequence is encoded in URL-safe base64 without padding -func Bytes(val string) ([]byte, error) { - b, err := base64.StdEncoding.DecodeString(val) - if err != nil { - return nil, err - } - return b, nil -} - -// Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. -func Timestamp(val string) (*timestamp.Timestamp, error) { - var r *timestamp.Timestamp - err := jsonpb.UnmarshalString(val, r) - return r, err -} - -// Duration converts the given string into a timestamp.Duration. -func Duration(val string) (*duration.Duration, error) { - var r *duration.Duration - err := jsonpb.UnmarshalString(val, r) - return r, err -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go deleted file mode 100755 index b6e5ddf..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package runtime contains runtime helper functions used by -servers which protoc-gen-grpc-gateway generates. -*/ -package runtime diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go deleted file mode 100755 index 0e2bdf4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go +++ /dev/null @@ -1,142 +0,0 @@ -package runtime - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/any" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. -// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto -func HTTPStatusFromCode(code codes.Code) int { - switch code { - case codes.OK: - return http.StatusOK - case codes.Canceled: - return http.StatusRequestTimeout - case codes.Unknown: - return http.StatusInternalServerError - case codes.InvalidArgument: - return http.StatusBadRequest - case codes.DeadlineExceeded: - return http.StatusGatewayTimeout - case codes.NotFound: - return http.StatusNotFound - case codes.AlreadyExists: - return http.StatusConflict - case codes.PermissionDenied: - return http.StatusForbidden - case codes.Unauthenticated: - return http.StatusUnauthorized - case codes.ResourceExhausted: - return http.StatusTooManyRequests - case codes.FailedPrecondition: - return http.StatusPreconditionFailed - case codes.Aborted: - return http.StatusConflict - case codes.OutOfRange: - return http.StatusBadRequest - case codes.Unimplemented: - return http.StatusNotImplemented - case codes.Internal: - return http.StatusInternalServerError - case codes.Unavailable: - return http.StatusServiceUnavailable - case codes.DataLoss: - return http.StatusInternalServerError - } - - grpclog.Printf("Unknown gRPC error code: %v", code) - return http.StatusInternalServerError -} - -var ( - // HTTPError replies to the request with the error. - // You can set a custom function to this variable to customize error format. - HTTPError = DefaultHTTPError - // OtherErrorHandler handles the following error used by the gateway: StatusMethodNotAllowed StatusNotFound and StatusBadRequest - OtherErrorHandler = DefaultOtherErrorHandler -) - -type errorBody struct { - Error string `protobuf:"bytes,1,name=error" json:"error"` - Code int32 `protobuf:"varint,2,name=code" json:"code"` - Details []*any.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"` -} - -// Make this also conform to proto.Message for builtin JSONPb Marshaler -func (e *errorBody) Reset() { *e = errorBody{} } -func (e *errorBody) String() string { return proto.CompactTextString(e) } -func (*errorBody) ProtoMessage() {} - -// DefaultHTTPError is the default implementation of HTTPError. -// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. -// If otherwise, it replies with http.StatusInternalServerError. -// -// The response body returned by this function is a JSON object, -// which contains a member whose key is "error" and whose value is err.Error(). -func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) { - const fallback = `{"error": "failed to marshal error message"}` - - w.Header().Del("Trailer") - w.Header().Set("Content-Type", marshaler.ContentType()) - - s, ok := status.FromError(err) - if !ok { - s = status.New(codes.Unknown, err.Error()) - } - - body := &errorBody{ - Error: s.Message(), - Code: int32(s.Code()), - } - - for _, detail := range s.Details() { - if det, ok := detail.(proto.Message); ok { - a, err := ptypes.MarshalAny(det) - if err != nil { - grpclog.Printf("Failed to marshal any: %v", err) - } else { - body.Details = append(body.Details, a) - } - } - } - - buf, merr := marshaler.Marshal(body) - if merr != nil { - grpclog.Printf("Failed to marshal error message %q: %v", body, merr) - w.WriteHeader(http.StatusInternalServerError) - if _, err := io.WriteString(w, fallback); err != nil { - grpclog.Printf("Failed to write response: %v", err) - } - return - } - - md, ok := ServerMetadataFromContext(ctx) - if !ok { - grpclog.Printf("Failed to extract ServerMetadata from context") - } - - handleForwardResponseServerMetadata(w, mux, md) - handleForwardResponseTrailerHeader(w, md) - st := HTTPStatusFromCode(s.Code()) - w.WriteHeader(st) - if _, err := w.Write(buf); err != nil { - grpclog.Printf("Failed to write response: %v", err) - } - - handleForwardResponseTrailer(w, md) -} - -// DefaultOtherErrorHandler is the default implementation of OtherErrorHandler. -// It simply writes a string representation of the given error into "w". -func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) { - http.Error(w, msg, code) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go deleted file mode 100755 index 2c7ecf1..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/errors_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package runtime_test - -import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "context" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func TestDefaultHTTPError(t *testing.T) { - ctx := context.Background() - - for _, spec := range []struct { - err error - status int - msg string - }{ - { - err: fmt.Errorf("example error"), - status: http.StatusInternalServerError, - msg: "example error", - }, - { - err: status.Error(codes.NotFound, "no such resource"), - status: http.StatusNotFound, - msg: "no such resource", - }, - } { - w := httptest.NewRecorder() - req, _ := http.NewRequest("", "", nil) // Pass in an empty request to match the signature - runtime.DefaultHTTPError(ctx, &runtime.ServeMux{}, &runtime.JSONBuiltin{}, w, req, spec.err) - - if got, want := w.Header().Get("Content-Type"), "application/json"; got != want { - t.Errorf(`w.Header().Get("Content-Type") = %q; want %q; on spec.err=%v`, got, want, spec.err) - } - if got, want := w.Code, spec.status; got != want { - t.Errorf("w.Code = %d; want %d", got, want) - } - - body := make(map[string]interface{}) - if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { - t.Errorf("json.Unmarshal(%q, &body) failed with %v; want success", w.Body.Bytes(), err) - continue - } - - if got, want := body["error"].(string), spec.msg; !strings.Contains(got, want) { - t.Errorf(`body["error"] = %q; want %q; on spec.err=%v`, got, want, spec.err) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go deleted file mode 100755 index 1b3c650..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go +++ /dev/null @@ -1,195 +0,0 @@ -package runtime - -import ( - "fmt" - "io" - "net/http" - "net/textproto" - - "context" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/any" - "github.com/grpc-ecosystem/grpc-gateway/runtime/internal" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// ForwardResponseStream forwards the stream from gRPC server to REST client. -func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { - f, ok := w.(http.Flusher) - if !ok { - grpclog.Printf("Flush not supported in %T", w) - http.Error(w, "unexpected type of web server", http.StatusInternalServerError) - return - } - - md, ok := ServerMetadataFromContext(ctx) - if !ok { - grpclog.Printf("Failed to extract ServerMetadata from context") - http.Error(w, "unexpected error", http.StatusInternalServerError) - return - } - handleForwardResponseServerMetadata(w, mux, md) - - w.Header().Set("Transfer-Encoding", "chunked") - w.Header().Set("Content-Type", marshaler.ContentType()) - if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { - HTTPError(ctx, mux, marshaler, w, req, err) - return - } - - var delimiter []byte - if d, ok := marshaler.(Delimited); ok { - delimiter = d.Delimiter() - } else { - delimiter = []byte("\n") - } - - var wroteHeader bool - for { - resp, err := recv() - if err == io.EOF { - return - } - if err != nil { - handleForwardResponseStreamError(wroteHeader, marshaler, w, err) - return - } - if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { - handleForwardResponseStreamError(wroteHeader, marshaler, w, err) - return - } - - buf, err := marshaler.Marshal(streamChunk(resp, nil)) - if err != nil { - grpclog.Printf("Failed to marshal response chunk: %v", err) - handleForwardResponseStreamError(wroteHeader, marshaler, w, err) - return - } - if _, err = w.Write(buf); err != nil { - grpclog.Printf("Failed to send response chunk: %v", err) - return - } - wroteHeader = true - if _, err = w.Write(delimiter); err != nil { - grpclog.Printf("Failed to send delimiter chunk: %v", err) - return - } - f.Flush() - } -} - -func handleForwardResponseServerMetadata(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { - for k, vs := range md.HeaderMD { - if h, ok := mux.outgoingHeaderMatcher(k); ok { - for _, v := range vs { - w.Header().Add(h, v) - } - } - } -} - -func handleForwardResponseTrailerHeader(w http.ResponseWriter, md ServerMetadata) { - for k := range md.TrailerMD { - tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", MetadataTrailerPrefix, k)) - w.Header().Add("Trailer", tKey) - } -} - -func handleForwardResponseTrailer(w http.ResponseWriter, md ServerMetadata) { - for k, vs := range md.TrailerMD { - tKey := fmt.Sprintf("%s%s", MetadataTrailerPrefix, k) - for _, v := range vs { - w.Header().Add(tKey, v) - } - } -} - -// ForwardResponseMessage forwards the message "resp" from gRPC server to REST client. -func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { - md, ok := ServerMetadataFromContext(ctx) - if !ok { - grpclog.Printf("Failed to extract ServerMetadata from context") - } - - handleForwardResponseServerMetadata(w, mux, md) - handleForwardResponseTrailerHeader(w, md) - w.Header().Set("Content-Type", marshaler.ContentType()) - if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { - HTTPError(ctx, mux, marshaler, w, req, err) - return - } - - buf, err := marshaler.Marshal(resp) - if err != nil { - grpclog.Printf("Marshal error: %v", err) - HTTPError(ctx, mux, marshaler, w, req, err) - return - } - - if _, err = w.Write(buf); err != nil { - grpclog.Printf("Failed to write response: %v", err) - } - - handleForwardResponseTrailer(w, md) -} - -func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { - if len(opts) == 0 { - return nil - } - for _, opt := range opts { - if err := opt(ctx, w, resp); err != nil { - grpclog.Printf("Error handling ForwardResponseOptions: %v", err) - return err - } - } - return nil -} - -func handleForwardResponseStreamError(wroteHeader bool, marshaler Marshaler, w http.ResponseWriter, err error) { - buf, merr := marshaler.Marshal(streamChunk(nil, err)) - if merr != nil { - grpclog.Printf("Failed to marshal an error: %v", merr) - return - } - if !wroteHeader { - s, ok := status.FromError(err) - if !ok { - s = status.New(codes.Unknown, err.Error()) - } - w.WriteHeader(HTTPStatusFromCode(s.Code())) - } - if _, werr := w.Write(buf); werr != nil { - grpclog.Printf("Failed to notify error to client: %v", werr) - return - } -} - -func streamChunk(result proto.Message, err error) map[string]proto.Message { - if err != nil { - grpcCode := codes.Unknown - grpcMessage := err.Error() - var grpcDetails []*any.Any - if s, ok := status.FromError(err); ok { - grpcCode = s.Code() - grpcMessage = s.Message() - grpcDetails = s.Proto().GetDetails() - } - httpCode := HTTPStatusFromCode(grpcCode) - return map[string]proto.Message{ - "error": &internal.StreamError{ - GrpcCode: int32(grpcCode), - HttpCode: int32(httpCode), - Message: grpcMessage, - HttpStatus: http.StatusText(httpCode), - Details: grpcDetails, - }, - } - } - if result == nil { - return streamChunk(nil, fmt.Errorf("empty response")) - } - return map[string]proto.Message{"result": result} -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go deleted file mode 100755 index 6a712a4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/handler_test.go +++ /dev/null @@ -1,228 +0,0 @@ -package runtime_test - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "context" - "github.com/golang/protobuf/proto" - pb "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/runtime/internal" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func TestForwardResponseStream(t *testing.T) { - type msg struct { - pb proto.Message - err error - } - tests := []struct { - name string - msgs []msg - statusCode int - }{{ - name: "encoding", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {&pb.SimpleMessage{Id: "Two"}, nil}, - }, - statusCode: http.StatusOK, - }, { - name: "empty", - statusCode: http.StatusOK, - }, { - name: "error", - msgs: []msg{{nil, grpc.Errorf(codes.OutOfRange, "400")}}, - statusCode: http.StatusBadRequest, - }, { - name: "stream_error", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {nil, grpc.Errorf(codes.OutOfRange, "400")}, - }, - statusCode: http.StatusOK, - }} - - newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { - var count int - return func() (proto.Message, error) { - if count == len(msgs) { - return nil, io.EOF - } else if count > len(msgs) { - t.Errorf("recv() called %d times for %d messages", count, len(msgs)) - } - count++ - msg := msgs[count-1] - return msg.pb, msg.err - } - } - ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) - marshaler := &runtime.JSONPb{} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - recv := newTestRecv(t, tt.msgs) - req := httptest.NewRequest("GET", "http://example.com/foo", nil) - resp := httptest.NewRecorder() - - runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) - - w := resp.Result() - if w.StatusCode != tt.statusCode { - t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) - } - if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { - t.Errorf("ForwardResponseStream missing header chunked") - } - body, err := ioutil.ReadAll(w.Body) - if err != nil { - t.Errorf("Failed to read response body with %v", err) - } - w.Body.Close() - - var want []byte - for i, msg := range tt.msgs { - if msg.err != nil { - if i == 0 { - // Skip non-stream errors - t.Skip("checking error encodings") - } - st, _ := status.FromError(msg.err) - httpCode := runtime.HTTPStatusFromCode(st.Code()) - b, err := marshaler.Marshal(map[string]proto.Message{ - "error": &internal.StreamError{ - GrpcCode: int32(st.Code()), - HttpCode: int32(httpCode), - Message: st.Message(), - HttpStatus: http.StatusText(httpCode), - Details: st.Proto().GetDetails(), - }, - }) - if err != nil { - t.Errorf("marshaler.Marshal() failed %v", err) - } - errBytes := body[len(want):] - if string(errBytes) != string(b) { - t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", errBytes, b) - } - - return - } - b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb}) - if err != nil { - t.Errorf("marshaler.Marshal() failed %v", err) - } - want = append(want, b...) - want = append(want, marshaler.Delimiter()...) - } - - if string(body) != string(want) { - t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) - } - }) - } -} - -// A custom marshaler implementation, that doesn't implement the delimited interface -type CustomMarshaler struct { - m *runtime.JSONPb -} - -func (c *CustomMarshaler) Marshal(v interface{}) ([]byte, error) { return c.m.Marshal(v) } -func (c *CustomMarshaler) Unmarshal(data []byte, v interface{}) error { return c.m.Unmarshal(data, v) } -func (c *CustomMarshaler) NewDecoder(r io.Reader) runtime.Decoder { return c.m.NewDecoder(r) } -func (c *CustomMarshaler) NewEncoder(w io.Writer) runtime.Encoder { return c.m.NewEncoder(w) } -func (c *CustomMarshaler) ContentType() string { return c.m.ContentType() } - -func TestForwardResponseStreamCustomMarshaler(t *testing.T) { - type msg struct { - pb proto.Message - err error - } - tests := []struct { - name string - msgs []msg - statusCode int - }{{ - name: "encoding", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {&pb.SimpleMessage{Id: "Two"}, nil}, - }, - statusCode: http.StatusOK, - }, { - name: "empty", - statusCode: http.StatusOK, - }, { - name: "error", - msgs: []msg{{nil, grpc.Errorf(codes.OutOfRange, "400")}}, - statusCode: http.StatusBadRequest, - }, { - name: "stream_error", - msgs: []msg{ - {&pb.SimpleMessage{Id: "One"}, nil}, - {nil, grpc.Errorf(codes.OutOfRange, "400")}, - }, - statusCode: http.StatusOK, - }} - - newTestRecv := func(t *testing.T, msgs []msg) func() (proto.Message, error) { - var count int - return func() (proto.Message, error) { - if count == len(msgs) { - return nil, io.EOF - } else if count > len(msgs) { - t.Errorf("recv() called %d times for %d messages", count, len(msgs)) - } - count++ - msg := msgs[count-1] - return msg.pb, msg.err - } - } - ctx := runtime.NewServerMetadataContext(context.Background(), runtime.ServerMetadata{}) - marshaler := &CustomMarshaler{&runtime.JSONPb{}} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - recv := newTestRecv(t, tt.msgs) - req := httptest.NewRequest("GET", "http://example.com/foo", nil) - resp := httptest.NewRecorder() - - runtime.ForwardResponseStream(ctx, runtime.NewServeMux(), marshaler, resp, req, recv) - - w := resp.Result() - if w.StatusCode != tt.statusCode { - t.Errorf("StatusCode %d want %d", w.StatusCode, tt.statusCode) - } - if h := w.Header.Get("Transfer-Encoding"); h != "chunked" { - t.Errorf("ForwardResponseStream missing header chunked") - } - body, err := ioutil.ReadAll(w.Body) - if err != nil { - t.Errorf("Failed to read response body with %v", err) - } - w.Body.Close() - - var want []byte - for _, msg := range tt.msgs { - if msg.err != nil { - t.Skip("checking erorr encodings") - } - b, err := marshaler.Marshal(map[string]proto.Message{"result": msg.pb}) - if err != nil { - t.Errorf("marshaler.Marshal() failed %v", err) - } - want = append(want, b...) - want = append(want, "\n"...) - } - - if string(body) != string(want) { - t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want) - } - }) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/BUILD.bazel deleted file mode 100755 index 937e660..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/BUILD.bazel +++ /dev/null @@ -1,23 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") - -package(default_visibility = ["//runtime:__subpackages__"]) - -proto_library( - name = "internal_proto", - srcs = ["stream_chunk.proto"], - deps = ["@com_google_protobuf//:any_proto"], -) - -go_proto_library( - name = "internal_go_proto", - importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal", - proto = ":internal_proto", - deps = ["@com_github_golang_protobuf//ptypes/any:go_default_library"], -) - -go_library( - name = "go_default_library", - embed = [":internal_go_proto"], - importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime/internal", -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.pb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.pb.go deleted file mode 100755 index a06c722..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.pb.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: runtime/internal/stream_chunk.proto - -package internal - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// StreamError is a response type which is returned when -// streaming rpc returns an error. -type StreamError struct { - GrpcCode int32 `protobuf:"varint,1,opt,name=grpc_code,json=grpcCode" json:"grpc_code,omitempty"` - HttpCode int32 `protobuf:"varint,2,opt,name=http_code,json=httpCode" json:"http_code,omitempty"` - Message string `protobuf:"bytes,3,opt,name=message" json:"message,omitempty"` - HttpStatus string `protobuf:"bytes,4,opt,name=http_status,json=httpStatus" json:"http_status,omitempty"` - Details []*any.Any `protobuf:"bytes,5,rep,name=details" json:"details,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamError) Reset() { *m = StreamError{} } -func (m *StreamError) String() string { return proto.CompactTextString(m) } -func (*StreamError) ProtoMessage() {} -func (*StreamError) Descriptor() ([]byte, []int) { - return fileDescriptor_stream_chunk_6adb10b40700458b, []int{0} -} -func (m *StreamError) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamError.Unmarshal(m, b) -} -func (m *StreamError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamError.Marshal(b, m, deterministic) -} -func (dst *StreamError) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamError.Merge(dst, src) -} -func (m *StreamError) XXX_Size() int { - return xxx_messageInfo_StreamError.Size(m) -} -func (m *StreamError) XXX_DiscardUnknown() { - xxx_messageInfo_StreamError.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamError proto.InternalMessageInfo - -func (m *StreamError) GetGrpcCode() int32 { - if m != nil { - return m.GrpcCode - } - return 0 -} - -func (m *StreamError) GetHttpCode() int32 { - if m != nil { - return m.HttpCode - } - return 0 -} - -func (m *StreamError) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *StreamError) GetHttpStatus() string { - if m != nil { - return m.HttpStatus - } - return "" -} - -func (m *StreamError) GetDetails() []*any.Any { - if m != nil { - return m.Details - } - return nil -} - -func init() { - proto.RegisterType((*StreamError)(nil), "grpc.gateway.runtime.StreamError") -} - -func init() { - proto.RegisterFile("runtime/internal/stream_chunk.proto", fileDescriptor_stream_chunk_6adb10b40700458b) -} - -var fileDescriptor_stream_chunk_6adb10b40700458b = []byte{ - // 226 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x34, 0x90, 0xc1, 0x4e, 0x84, 0x30, - 0x10, 0x86, 0x83, 0xeb, 0xba, 0xbb, 0xc3, 0x8d, 0xec, 0xa1, 0xea, 0x41, 0xa2, 0x17, 0x4e, 0x25, - 0xd1, 0x27, 0x50, 0xe3, 0x0b, 0xb0, 0x37, 0x2f, 0x9b, 0x59, 0x18, 0x0b, 0x11, 0x5a, 0x32, 0x1d, - 0x62, 0x78, 0x2d, 0x9f, 0xd0, 0xb4, 0xc8, 0xb1, 0xdf, 0xf7, 0xff, 0x93, 0x3f, 0x85, 0x27, 0x9e, - 0xac, 0x74, 0x03, 0x95, 0x9d, 0x15, 0x62, 0x8b, 0x7d, 0xe9, 0x85, 0x09, 0x87, 0x73, 0xdd, 0x4e, - 0xf6, 0x5b, 0x8f, 0xec, 0xc4, 0x65, 0x47, 0xc3, 0x63, 0xad, 0x0d, 0x0a, 0xfd, 0xe0, 0xac, 0xff, - 0x1b, 0x77, 0xb7, 0xc6, 0x39, 0xd3, 0x53, 0x19, 0x33, 0x97, 0xe9, 0xab, 0x44, 0x3b, 0x2f, 0x85, - 0xc7, 0xdf, 0x04, 0xd2, 0x53, 0xbc, 0xf3, 0xc1, 0xec, 0x38, 0xbb, 0x87, 0x43, 0x38, 0x71, 0xae, - 0x5d, 0x43, 0x2a, 0xc9, 0x93, 0x62, 0x5b, 0xed, 0x03, 0x78, 0x77, 0x0d, 0x05, 0xd9, 0x8a, 0x8c, - 0x8b, 0xbc, 0x5a, 0x64, 0x00, 0x51, 0x2a, 0xd8, 0x0d, 0xe4, 0x3d, 0x1a, 0x52, 0x9b, 0x3c, 0x29, - 0x0e, 0xd5, 0xfa, 0xcc, 0x1e, 0x20, 0x8d, 0x35, 0x2f, 0x28, 0x93, 0x57, 0xd7, 0xd1, 0x42, 0x40, - 0xa7, 0x48, 0x32, 0x0d, 0xbb, 0x86, 0x04, 0xbb, 0xde, 0xab, 0x6d, 0xbe, 0x29, 0xd2, 0xe7, 0xa3, - 0x5e, 0x16, 0xeb, 0x75, 0xb1, 0x7e, 0xb5, 0x73, 0xb5, 0x86, 0xde, 0xe0, 0x73, 0xbf, 0x7e, 0xc2, - 0xe5, 0x26, 0x46, 0x5e, 0xfe, 0x02, 0x00, 0x00, 0xff, 0xff, 0x16, 0x75, 0x92, 0x08, 0x1f, 0x01, - 0x00, 0x00, -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto deleted file mode 100755 index 55f42ce..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/internal/stream_chunk.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; -package grpc.gateway.runtime; -option go_package = "internal"; - -import "google/protobuf/any.proto"; - -// StreamError is a response type which is returned when -// streaming rpc returns an error. -message StreamError { - int32 grpc_code = 1; - int32 http_code = 2; - string message = 3; - string http_status = 4; - repeated google.protobuf.Any details = 5; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go deleted file mode 100755 index f9d3a58..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go +++ /dev/null @@ -1,45 +0,0 @@ -package runtime - -import ( - "encoding/json" - "io" -) - -// JSONBuiltin is a Marshaler which marshals/unmarshals into/from JSON -// with the standard "encoding/json" package of Golang. -// Although it is generally faster for simple proto messages than JSONPb, -// it does not support advanced features of protobuf, e.g. map, oneof, .... -// -// The NewEncoder and NewDecoder types return *json.Encoder and -// *json.Decoder respectively. -type JSONBuiltin struct{} - -// ContentType always Returns "application/json". -func (*JSONBuiltin) ContentType() string { - return "application/json" -} - -// Marshal marshals "v" into JSON -func (j *JSONBuiltin) Marshal(v interface{}) ([]byte, error) { - return json.Marshal(v) -} - -// Unmarshal unmarshals JSON data into "v". -func (j *JSONBuiltin) Unmarshal(data []byte, v interface{}) error { - return json.Unmarshal(data, v) -} - -// NewDecoder returns a Decoder which reads JSON stream from "r". -func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder { - return json.NewDecoder(r) -} - -// NewEncoder returns an Encoder which writes JSON stream into "w". -func (j *JSONBuiltin) NewEncoder(w io.Writer) Encoder { - return json.NewEncoder(w) -} - -// Delimiter for newline encoded JSON streams. -func (j *JSONBuiltin) Delimiter() []byte { - return []byte("\n") -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go deleted file mode 100755 index 1d226d5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package runtime_test - -import ( - "bytes" - "encoding/json" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" - structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestJSONBuiltinMarshal(t *testing.T) { - var m runtime.JSONBuiltin - msg := examplepb.SimpleMessage{ - Id: "foo", - } - - buf, err := m.Marshal(&msg) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", &msg, err) - } - - var got examplepb.SimpleMessage - if err := json.Unmarshal(buf, &got); err != nil { - t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf, err) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want %v", &got, &want) - } -} - -func TestJSONBuiltinMarshalField(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - buf, err := m.Marshal(fixt.data) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) - } - if got, want := string(buf), fixt.json; got != want { - t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinMarshalFieldKnownErrors(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinKnownErrors { - buf, err := m.Marshal(fixt.data) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success", fixt.data, err) - } - if got, want := string(buf), fixt.json; got == want { - t.Errorf("surprisingly got = %q; as want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinsnmarshal(t *testing.T) { - var ( - m runtime.JSONBuiltin - got examplepb.SimpleMessage - - data = []byte(`{"id": "foo"}`) - ) - if err := m.Unmarshal(data, &got); err != nil { - t.Errorf("m.Unmarshal(%q, &got) failed with %v; want success", data, err) - } - - want := examplepb.SimpleMessage{ - Id: "foo", - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v", &got, &want) - } -} - -func TestJSONBuiltinUnmarshalField(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - dest := alloc(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { - t.Errorf("m.Unmarshal(%q, dest) failed with %v; want success", fixt.json, err) - } - - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("got = %#v; want = %#v; input = %q", got, want, fixt.json) - } - } -} - -func alloc(t reflect.Type) reflect.Value { - if t == nil { - return reflect.ValueOf(new(interface{})) - } else { - return reflect.New(t) - } -} - -func TestJSONBuiltinUnmarshalFieldKnownErrors(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinKnownErrors { - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err == nil { - t.Errorf("m.Unmarshal(%q, dest) succeeded; want ane error", fixt.json) - } - } -} - -func TestJSONBuiltinEncoder(t *testing.T) { - var m runtime.JSONBuiltin - msg := examplepb.SimpleMessage{ - Id: "foo", - } - - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(&msg); err != nil { - t.Errorf("enc.Encode(%v) failed with %v; want success", &msg, err) - } - - var got examplepb.SimpleMessage - if err := json.Unmarshal(buf.Bytes(), &got); err != nil { - t.Errorf("json.Unmarshal(%q, &got) failed with %v; want success", buf.String(), err) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want %v", &got, &want) - } -} - -func TestJSONBuiltinEncoderFields(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(fixt.data); err != nil { - t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) - } - - if got, want := buf.String(), fixt.json+"\n"; got != want { - t.Errorf("got = %q; want %q; data = %#v", got, want, fixt.data) - } - } -} - -func TestJSONBuiltinDecoder(t *testing.T) { - var ( - m runtime.JSONBuiltin - got examplepb.SimpleMessage - - data = `{"id": "foo"}` - ) - r := strings.NewReader(data) - dec := m.NewDecoder(r) - if err := dec.Decode(&got); err != nil { - t.Errorf("m.Unmarshal(&got) failed with %v; want success", err) - } - - want := examplepb.SimpleMessage{ - Id: "foo", - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v", &got, &want) - } -} - -func TestJSONBuiltinDecoderFields(t *testing.T) { - var m runtime.JSONBuiltin - for _, fixt := range builtinFieldFixtures { - r := strings.NewReader(fixt.json) - dec := m.NewDecoder(r) - dest := alloc(reflect.TypeOf(fixt.data)) - if err := dec.Decode(dest.Interface()); err != nil { - t.Errorf("dec.Decode(dest) failed with %v; want success; data = %q", err, fixt.json) - } - - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v; input = %q", got, want, fixt.json) - } - } -} - -var ( - builtinFieldFixtures = []struct { - data interface{} - json string - }{ - {data: "", json: `""`}, - {data: proto.String(""), json: `""`}, - {data: "foo", json: `"foo"`}, - {data: proto.String("foo"), json: `"foo"`}, - {data: int32(-1), json: "-1"}, - {data: proto.Int32(-1), json: "-1"}, - {data: int64(-1), json: "-1"}, - {data: proto.Int64(-1), json: "-1"}, - {data: uint32(123), json: "123"}, - {data: proto.Uint32(123), json: "123"}, - {data: uint64(123), json: "123"}, - {data: proto.Uint64(123), json: "123"}, - {data: float32(-1.5), json: "-1.5"}, - {data: proto.Float32(-1.5), json: "-1.5"}, - {data: float64(-1.5), json: "-1.5"}, - {data: proto.Float64(-1.5), json: "-1.5"}, - {data: true, json: "true"}, - {data: proto.Bool(true), json: "true"}, - {data: (*string)(nil), json: "null"}, - {data: new(empty.Empty), json: "{}"}, - {data: examplepb.NumericEnum_ONE, json: "1"}, - {data: nil, json: "null"}, - {data: (*string)(nil), json: "null"}, - {data: []interface{}{nil, "foo", -1.0, 1.234, true}, json: `[null,"foo",-1,1.234,true]`}, - { - data: map[string]interface{}{"bar": nil, "baz": -1.0, "fiz": 1.234, "foo": true}, - json: `{"bar":null,"baz":-1,"fiz":1.234,"foo":true}`, - }, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: "1", - }, - } - builtinKnownErrors = []struct { - data interface{} - json string - }{ - {data: examplepb.NumericEnum_ONE, json: "ONE"}, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: "ONE", - }, - { - data: &examplepb.ABitOfEverything_OneofString{OneofString: "abc"}, - json: `"abc"`, - }, - { - data: ×tamp.Timestamp{ - Seconds: 1462875553, - Nanos: 123000000, - }, - json: `"2016-05-10T10:19:13.123Z"`, - }, - { - data: &wrappers.Int32Value{Value: 123}, - json: "123", - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_StringValue{ - StringValue: "abc", - }, - }, - json: `"abc"`, - }, - } -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go deleted file mode 100755 index f56072a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go +++ /dev/null @@ -1,203 +0,0 @@ -package runtime - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "reflect" - - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" -) - -// JSONPb is a Marshaler which marshals/unmarshals into/from JSON -// with the "github.com/golang/protobuf/jsonpb". -// It supports fully functionality of protobuf unlike JSONBuiltin. -// -// The NewDecoder method returns a DecoderWrapper, so the underlying -// *json.Decoder methods can be used. -type JSONPb jsonpb.Marshaler - -// ContentType always returns "application/json". -func (*JSONPb) ContentType() string { - return "application/json" -} - -// Marshal marshals "v" into JSON. -func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { - if _, ok := v.(proto.Message); !ok { - return j.marshalNonProtoField(v) - } - - var buf bytes.Buffer - if err := j.marshalTo(&buf, v); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { - p, ok := v.(proto.Message) - if !ok { - buf, err := j.marshalNonProtoField(v) - if err != nil { - return err - } - _, err = w.Write(buf) - return err - } - return (*jsonpb.Marshaler)(j).Marshal(w, p) -} - -// marshalNonProto marshals a non-message field of a protobuf message. -// This function does not correctly marshals arbitrary data structure into JSON, -// but it is only capable of marshaling non-message field values of protobuf, -// i.e. primitive types, enums; pointers to primitives or enums; maps from -// integer/string types to primitives/enums/pointers to messages. -func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { - if v == nil { - return []byte("null"), nil - } - rv := reflect.ValueOf(v) - for rv.Kind() == reflect.Ptr { - if rv.IsNil() { - return []byte("null"), nil - } - rv = rv.Elem() - } - - if rv.Kind() == reflect.Map { - m := make(map[string]*json.RawMessage) - for _, k := range rv.MapKeys() { - buf, err := j.Marshal(rv.MapIndex(k).Interface()) - if err != nil { - return nil, err - } - m[fmt.Sprintf("%v", k.Interface())] = (*json.RawMessage)(&buf) - } - if j.Indent != "" { - return json.MarshalIndent(m, "", j.Indent) - } - return json.Marshal(m) - } - if enum, ok := rv.Interface().(protoEnum); ok && !j.EnumsAsInts { - return json.Marshal(enum.String()) - } - return json.Marshal(rv.Interface()) -} - -// Unmarshal unmarshals JSON "data" into "v" -func (j *JSONPb) Unmarshal(data []byte, v interface{}) error { - return unmarshalJSONPb(data, v) -} - -// NewDecoder returns a Decoder which reads JSON stream from "r". -func (j *JSONPb) NewDecoder(r io.Reader) Decoder { - d := json.NewDecoder(r) - return DecoderWrapper{Decoder: d} -} - -// DecoderWrapper is a wrapper around a *json.Decoder that adds -// support for protos to the Decode method. -type DecoderWrapper struct { - *json.Decoder -} - -// Decode wraps the embedded decoder's Decode method to support -// protos using a jsonpb.Unmarshaler. -func (d DecoderWrapper) Decode(v interface{}) error { - return decodeJSONPb(d.Decoder, v) -} - -// NewEncoder returns an Encoder which writes JSON stream into "w". -func (j *JSONPb) NewEncoder(w io.Writer) Encoder { - return EncoderFunc(func(v interface{}) error { return j.marshalTo(w, v) }) -} - -func unmarshalJSONPb(data []byte, v interface{}) error { - d := json.NewDecoder(bytes.NewReader(data)) - return decodeJSONPb(d, v) -} - -func decodeJSONPb(d *json.Decoder, v interface{}) error { - p, ok := v.(proto.Message) - if !ok { - return decodeNonProtoField(d, v) - } - unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true} - return unmarshaler.UnmarshalNext(d, p) -} - -func decodeNonProtoField(d *json.Decoder, v interface{}) error { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr { - return fmt.Errorf("%T is not a pointer", v) - } - for rv.Kind() == reflect.Ptr { - if rv.IsNil() { - rv.Set(reflect.New(rv.Type().Elem())) - } - if rv.Type().ConvertibleTo(typeProtoMessage) { - unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true} - return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message)) - } - rv = rv.Elem() - } - if rv.Kind() == reflect.Map { - if rv.IsNil() { - rv.Set(reflect.MakeMap(rv.Type())) - } - conv, ok := convFromType[rv.Type().Key().Kind()] - if !ok { - return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) - } - - m := make(map[string]*json.RawMessage) - if err := d.Decode(&m); err != nil { - return err - } - for k, v := range m { - result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) - if err := result[1].Interface(); err != nil { - return err.(error) - } - bk := result[0] - bv := reflect.New(rv.Type().Elem()) - if err := unmarshalJSONPb([]byte(*v), bv.Interface()); err != nil { - return err - } - rv.SetMapIndex(bk, bv.Elem()) - } - return nil - } - if _, ok := rv.Interface().(protoEnum); ok { - var repr interface{} - if err := d.Decode(&repr); err != nil { - return err - } - switch repr.(type) { - case string: - // TODO(yugui) Should use proto.StructProperties? - return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) - case float64: - rv.Set(reflect.ValueOf(int32(repr.(float64))).Convert(rv.Type())) - return nil - default: - return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) - } - } - return d.Decode(v) -} - -type protoEnum interface { - fmt.Stringer - EnumDescriptor() ([]byte, []int) -} - -var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem() - -// Delimiter for newline encoded JSON streams. -func (j *JSONPb) Delimiter() []byte { - return []byte("\n") -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go deleted file mode 100755 index 0c3d01b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb_test.go +++ /dev/null @@ -1,616 +0,0 @@ -package runtime_test - -import ( - "bytes" - "reflect" - "strings" - "testing" - - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/duration" - "github.com/golang/protobuf/ptypes/empty" - structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestJSONPbMarshal(t *testing.T) { - msg := examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: []string{}, - MappedStringValue: map[string]string{}, - MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, - RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) - }{ - { - verifier: func(json string) { - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } - if !strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = false; want true`, json) - } - if want := "uint64Value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - enumsAsInts: true, - verifier: func(json string) { - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - }, - }, - { - emitDefaults: true, - verifier: func(json string) { - if want := `"sfixed32Value"`; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - indent: "\t\t", - verifier: func(json string) { - if want := "\t\t\"amount\":"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - origName: true, - verifier: func(json string) { - if want := "uint64_value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - } { - m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, - } - buf, err := m.Marshal(&msg) - if err != nil { - t.Errorf("m.Marshal(%v) failed with %v; want success; spec=%v", &msg, err, spec) - } - - var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(string(buf), &got); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", string(buf), err, spec) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) - } - if spec.verifier != nil { - spec.verifier(string(buf)) - } - } -} - -func TestJSONPbMarshalFields(t *testing.T) { - var m runtime.JSONPb - m.EnumsAsInts = true // builtin fixtures include an enum, expected to be marshaled as int - for _, spec := range builtinFieldFixtures { - buf, err := m.Marshal(spec.data) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", spec.data, err) - } - if got, want := string(buf), spec.json; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", spec.data, got, want) - } - } - - m.EnumsAsInts = false - buf, err := m.Marshal(examplepb.NumericEnum_ONE) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) - } - if got, want := string(buf), `"ONE"`; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) - } -} - -func TestJSONPbUnmarshal(t *testing.T) { - var ( - m runtime.JSONPb - got examplepb.ABitOfEverything - ) - for i, data := range []string{ - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": "18446744073709551615", - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": 1, - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - } { - if err := m.Unmarshal([]byte(data), &got); err != nil { - t.Errorf("case %d: m.Unmarshal(%q, &got) failed with %v; want success", i, data, err) - } - - want := examplepb.ABitOfEverything{ - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - if !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want = %v", i, &got, &want) - } - } -} - -func TestJSONPbUnmarshalFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - if fixt.skipUnmarshal { - continue - } - - dest := reflect.New(reflect.TypeOf(fixt.data)) - if err := m.Unmarshal([]byte(fixt.json), dest.Interface()); err != nil { - t.Errorf("m.Unmarshal(%q, %T) failed with %v; want success", fixt.json, dest.Interface(), err) - } - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) - } - } -} - -func TestJSONPbEncoder(t *testing.T) { - msg := examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: []string{}, - MappedStringValue: map[string]string{}, - MappedNestedValue: map[string]*examplepb.ABitOfEverything_Nested{}, - RepeatedEnumValue: []examplepb.NumericEnum{}, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - - for i, spec := range []struct { - enumsAsInts, emitDefaults bool - indent string - origName bool - verifier func(json string) - }{ - { - verifier: func(json string) { - if strings.ContainsAny(json, " \t\r\n") { - t.Errorf("strings.ContainsAny(%q, %q) = true; want false", json, " \t\r\n") - } - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - if want := "uint64Value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - enumsAsInts: true, - verifier: func(json string) { - if strings.Contains(json, "ONE") { - t.Errorf(`strings.Contains(%q, "ONE") = true; want false`, json) - } - }, - }, - { - emitDefaults: true, - verifier: func(json string) { - if want := `"sfixed32Value"`; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - indent: "\t\t", - verifier: func(json string) { - if want := "\t\t\"amount\":"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - { - origName: true, - verifier: func(json string) { - if want := "uint64_value"; !strings.Contains(json, want) { - t.Errorf(`strings.Contains(%q, %q) = false; want true`, json, want) - } - }, - }, - } { - m := runtime.JSONPb{ - EnumsAsInts: spec.enumsAsInts, - EmitDefaults: spec.emitDefaults, - Indent: spec.indent, - OrigName: spec.origName, - } - - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(&msg); err != nil { - t.Errorf("enc.Encode(%v) failed with %v; want success; spec=%v", &msg, err, spec) - } - - var got examplepb.ABitOfEverything - if err := jsonpb.UnmarshalString(buf.String(), &got); err != nil { - t.Errorf("jsonpb.UnmarshalString(%q, &got) failed with %v; want success; spec=%v", buf.String(), err, spec) - } - if want := msg; !reflect.DeepEqual(got, want) { - t.Errorf("case %d: got = %v; want %v; spec=%v", i, &got, &want, spec) - } - if spec.verifier != nil { - spec.verifier(buf.String()) - } - } -} - -func TestJSONPbEncoderFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - var buf bytes.Buffer - enc := m.NewEncoder(&buf) - if err := enc.Encode(fixt.data); err != nil { - t.Errorf("enc.Encode(%#v) failed with %v; want success", fixt.data, err) - } - if got, want := buf.String(), fixt.json; got != want { - t.Errorf("enc.Encode(%#v) = %q; want %q", fixt.data, got, want) - } - } - - m.EnumsAsInts = true - buf, err := m.Marshal(examplepb.NumericEnum_ONE) - if err != nil { - t.Errorf("m.Marshal(%#v) failed with %v; want success", examplepb.NumericEnum_ONE, err) - } - if got, want := string(buf), "1"; got != want { - t.Errorf("m.Marshal(%#v) = %q; want %q", examplepb.NumericEnum_ONE, got, want) - } -} - -func TestJSONPbDecoder(t *testing.T) { - var ( - m runtime.JSONPb - got examplepb.ABitOfEverything - ) - for _, data := range []string{ - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": "18446744073709551615", - "enumValue": "ONE", - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - `{ - "uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - "nested": [ - {"name": "foo", "amount": 12345} - ], - "uint64Value": 18446744073709551615, - "enumValue": 1, - "oneofString": "bar", - "mapValue": { - "a": 1, - "b": 0 - } - }`, - } { - r := strings.NewReader(data) - dec := m.NewDecoder(r) - if err := dec.Decode(&got); err != nil { - t.Errorf("m.Unmarshal(&got) failed with %v; want success; data=%q", err, data) - } - - want := examplepb.ABitOfEverything{ - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got = %v; want = %v; data = %v", &got, &want, data) - } - } -} - -func TestJSONPbDecoderFields(t *testing.T) { - var m runtime.JSONPb - for _, fixt := range fieldFixtures { - if fixt.skipUnmarshal { - continue - } - - dest := reflect.New(reflect.TypeOf(fixt.data)) - dec := m.NewDecoder(strings.NewReader(fixt.json)) - if err := dec.Decode(dest.Interface()); err != nil { - t.Errorf("dec.Decode(%T) failed with %v; want success; input = %q", dest.Interface(), err, fixt.json) - } - if got, want := dest.Elem().Interface(), fixt.data; !reflect.DeepEqual(got, want) { - t.Errorf("dest = %#v; want %#v; input = %v", got, want, fixt.json) - } - } -} - -var ( - fieldFixtures = []struct { - data interface{} - json string - skipUnmarshal bool - }{ - {data: int32(1), json: "1"}, - {data: proto.Int32(1), json: "1"}, - {data: int64(1), json: "1"}, - {data: proto.Int64(1), json: "1"}, - {data: uint32(1), json: "1"}, - {data: proto.Uint32(1), json: "1"}, - {data: uint64(1), json: "1"}, - {data: proto.Uint64(1), json: "1"}, - {data: "abc", json: `"abc"`}, - {data: proto.String("abc"), json: `"abc"`}, - {data: float32(1.5), json: "1.5"}, - {data: proto.Float32(1.5), json: "1.5"}, - {data: float64(1.5), json: "1.5"}, - {data: proto.Float64(1.5), json: "1.5"}, - {data: true, json: "true"}, - {data: false, json: "false"}, - {data: (*string)(nil), json: "null"}, - { - data: examplepb.NumericEnum_ONE, - json: `"ONE"`, - // TODO(yugui) support unmarshaling of symbolic enum - skipUnmarshal: true, - }, - { - data: (*examplepb.NumericEnum)(proto.Int32(int32(examplepb.NumericEnum_ONE))), - json: `"ONE"`, - // TODO(yugui) support unmarshaling of symbolic enum - skipUnmarshal: true, - }, - - { - data: map[string]int32{ - "foo": 1, - }, - json: `{"foo":1}`, - }, - { - data: map[string]*examplepb.SimpleMessage{ - "foo": {Id: "bar"}, - }, - json: `{"foo":{"id":"bar"}}`, - }, - { - data: map[int32]*examplepb.SimpleMessage{ - 1: {Id: "foo"}, - }, - json: `{"1":{"id":"foo"}}`, - }, - { - data: map[bool]*examplepb.SimpleMessage{ - true: {Id: "foo"}, - }, - json: `{"true":{"id":"foo"}}`, - }, - { - data: &duration.Duration{ - Seconds: 123, - Nanos: 456000000, - }, - json: `"123.456s"`, - }, - { - data: ×tamp.Timestamp{ - Seconds: 1462875553, - Nanos: 123000000, - }, - json: `"2016-05-10T10:19:13.123Z"`, - }, - { - data: new(empty.Empty), - json: "{}", - }, - - // TODO(yugui) Enable unmarshaling of the following examples - // once jsonpb supports them. - { - data: &structpb.Value{ - Kind: new(structpb.Value_NullValue), - }, - json: "null", - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_NumberValue{ - NumberValue: 123.4, - }, - }, - json: "123.4", - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_StringValue{ - StringValue: "abc", - }, - }, - json: `"abc"`, - skipUnmarshal: true, - }, - { - data: &structpb.Value{ - Kind: &structpb.Value_BoolValue{ - BoolValue: true, - }, - }, - json: "true", - skipUnmarshal: true, - }, - { - data: &structpb.Struct{ - Fields: map[string]*structpb.Value{ - "foo_bar": { - Kind: &structpb.Value_BoolValue{ - BoolValue: true, - }, - }, - }, - }, - json: `{"foo_bar":true}`, - skipUnmarshal: true, - }, - - { - data: &wrappers.BoolValue{Value: true}, - json: "true", - }, - { - data: &wrappers.DoubleValue{Value: 123.456}, - json: "123.456", - }, - { - data: &wrappers.FloatValue{Value: 123.456}, - json: "123.456", - }, - { - data: &wrappers.Int32Value{Value: -123}, - json: "-123", - }, - { - data: &wrappers.Int64Value{Value: -123}, - json: `"-123"`, - }, - { - data: &wrappers.UInt32Value{Value: 123}, - json: "123", - }, - { - data: &wrappers.UInt64Value{Value: 123}, - json: `"123"`, - }, - // TODO(yugui) Add other well-known types once jsonpb supports them - } -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go deleted file mode 100755 index f65d1a2..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go +++ /dev/null @@ -1,62 +0,0 @@ -package runtime - -import ( - "io" - - "errors" - "github.com/golang/protobuf/proto" - "io/ioutil" -) - -// ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes -type ProtoMarshaller struct{} - -// ContentType always returns "application/octet-stream". -func (*ProtoMarshaller) ContentType() string { - return "application/octet-stream" -} - -// Marshal marshals "value" into Proto -func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) { - message, ok := value.(proto.Message) - if !ok { - return nil, errors.New("unable to marshal non proto field") - } - return proto.Marshal(message) -} - -// Unmarshal unmarshals proto "data" into "value" -func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error { - message, ok := value.(proto.Message) - if !ok { - return errors.New("unable to unmarshal non proto field") - } - return proto.Unmarshal(data, message) -} - -// NewDecoder returns a Decoder which reads proto stream from "reader". -func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder { - return DecoderFunc(func(value interface{}) error { - buffer, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - return marshaller.Unmarshal(buffer, value) - }) -} - -// NewEncoder returns an Encoder which writes proto stream into "writer". -func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder { - return EncoderFunc(func(value interface{}) error { - buffer, err := marshaller.Marshal(value) - if err != nil { - return err - } - _, err = writer.Write(buffer) - if err != nil { - return err - } - - return nil - }) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go deleted file mode 100755 index 1da30b8..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package runtime_test - -import ( - "bytes" - "testing" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/grpc-ecosystem/grpc-gateway/examples/proto/examplepb" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -var message = &examplepb.ABitOfEverything{ - SingleNested: &examplepb.ABitOfEverything_Nested{}, - RepeatedStringValue: nil, - MappedStringValue: nil, - MappedNestedValue: nil, - RepeatedEnumValue: nil, - TimestampValue: ×tamp.Timestamp{}, - Uuid: "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7", - Nested: []*examplepb.ABitOfEverything_Nested{ - { - Name: "foo", - Amount: 12345, - }, - }, - Uint64Value: 0xFFFFFFFFFFFFFFFF, - EnumValue: examplepb.NumericEnum_ONE, - OneofValue: &examplepb.ABitOfEverything_OneofString{ - OneofString: "bar", - }, - MapValue: map[string]examplepb.NumericEnum{ - "a": examplepb.NumericEnum_ONE, - "b": examplepb.NumericEnum_ZERO, - }, -} - -func TestProtoMarshalUnmarshal(t *testing.T) { - marshaller := runtime.ProtoMarshaller{} - - // Marshal - buffer, err := marshaller.Marshal(message) - if err != nil { - t.Fatalf("Marshalling returned error: %s", err.Error()) - } - - // Unmarshal - unmarshalled := &examplepb.ABitOfEverything{} - err = marshaller.Unmarshal(buffer, unmarshalled) - if err != nil { - t.Fatalf("Unmarshalling returned error: %s", err.Error()) - } - - if !proto.Equal(unmarshalled, message) { - t.Errorf( - "Unmarshalled didn't match original message: (original = %v) != (unmarshalled = %v)", - unmarshalled, - message, - ) - } -} - -func TestProtoEncoderDecodert(t *testing.T) { - marshaller := runtime.ProtoMarshaller{} - - var buf bytes.Buffer - - encoder := marshaller.NewEncoder(&buf) - decoder := marshaller.NewDecoder(&buf) - - // Encode - err := encoder.Encode(message) - if err != nil { - t.Fatalf("Encoding returned error: %s", err.Error()) - } - - // Decode - unencoded := &examplepb.ABitOfEverything{} - err = decoder.Decode(unencoded) - if err != nil { - t.Fatalf("Unmarshalling returned error: %s", err.Error()) - } - - if !proto.Equal(unencoded, message) { - t.Errorf( - "Unencoded didn't match original message: (original = %v) != (unencoded = %v)", - unencoded, - message, - ) - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go deleted file mode 100755 index 98fe6e8..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go +++ /dev/null @@ -1,48 +0,0 @@ -package runtime - -import ( - "io" -) - -// Marshaler defines a conversion between byte sequence and gRPC payloads / fields. -type Marshaler interface { - // Marshal marshals "v" into byte sequence. - Marshal(v interface{}) ([]byte, error) - // Unmarshal unmarshals "data" into "v". - // "v" must be a pointer value. - Unmarshal(data []byte, v interface{}) error - // NewDecoder returns a Decoder which reads byte sequence from "r". - NewDecoder(r io.Reader) Decoder - // NewEncoder returns an Encoder which writes bytes sequence into "w". - NewEncoder(w io.Writer) Encoder - // ContentType returns the Content-Type which this marshaler is responsible for. - ContentType() string -} - -// Decoder decodes a byte sequence -type Decoder interface { - Decode(v interface{}) error -} - -// Encoder encodes gRPC payloads / fields into byte sequence. -type Encoder interface { - Encode(v interface{}) error -} - -// DecoderFunc adapts an decoder function into Decoder. -type DecoderFunc func(v interface{}) error - -// Decode delegates invocations to the underlying function itself. -func (f DecoderFunc) Decode(v interface{}) error { return f(v) } - -// EncoderFunc adapts an encoder function into Encoder -type EncoderFunc func(v interface{}) error - -// Encode delegates invocations to the underlying function itself. -func (f EncoderFunc) Encode(v interface{}) error { return f(v) } - -// Delimited defines the streaming delimiter. -type Delimited interface { - // Delimiter returns the record seperator for the stream. - Delimiter() []byte -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go deleted file mode 100755 index 5cc53ae..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go +++ /dev/null @@ -1,91 +0,0 @@ -package runtime - -import ( - "errors" - "net/http" -) - -// MIMEWildcard is the fallback MIME type used for requests which do not match -// a registered MIME type. -const MIMEWildcard = "*" - -var ( - acceptHeader = http.CanonicalHeaderKey("Accept") - contentTypeHeader = http.CanonicalHeaderKey("Content-Type") - - defaultMarshaler = &JSONPb{OrigName: true} -) - -// MarshalerForRequest returns the inbound/outbound marshalers for this request. -// It checks the registry on the ServeMux for the MIME type set by the Content-Type header. -// If it isn't set (or the request Content-Type is empty), checks for "*". -// If there are multiple Content-Type headers set, choose the first one that it can -// exactly match in the registry. -// Otherwise, it follows the above logic for "*"/InboundMarshaler/OutboundMarshaler. -func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, outbound Marshaler) { - for _, acceptVal := range r.Header[acceptHeader] { - if m, ok := mux.marshalers.mimeMap[acceptVal]; ok { - outbound = m - break - } - } - - for _, contentTypeVal := range r.Header[contentTypeHeader] { - if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok { - inbound = m - break - } - } - - if inbound == nil { - inbound = mux.marshalers.mimeMap[MIMEWildcard] - } - if outbound == nil { - outbound = inbound - } - - return inbound, outbound -} - -// marshalerRegistry is a mapping from MIME types to Marshalers. -type marshalerRegistry struct { - mimeMap map[string]Marshaler -} - -// add adds a marshaler for a case-sensitive MIME type string ("*" to match any -// MIME type). -func (m marshalerRegistry) add(mime string, marshaler Marshaler) error { - if len(mime) == 0 { - return errors.New("empty MIME type") - } - - m.mimeMap[mime] = marshaler - - return nil -} - -// makeMarshalerMIMERegistry returns a new registry of marshalers. -// It allows for a mapping of case-sensitive Content-Type MIME type string to runtime.Marshaler interfaces. -// -// For example, you could allow the client to specify the use of the runtime.JSONPb marshaler -// with a "application/jsonpb" Content-Type and the use of the runtime.JSONBuiltin marshaler -// with a "application/json" Content-Type. -// "*" can be used to match any Content-Type. -// This can be attached to a ServerMux with the marshaler option. -func makeMarshalerMIMERegistry() marshalerRegistry { - return marshalerRegistry{ - mimeMap: map[string]Marshaler{ - MIMEWildcard: defaultMarshaler, - }, - } -} - -// WithMarshalerOption returns a ServeMuxOption which associates inbound and outbound -// Marshalers to a MIME type in mux. -func WithMarshalerOption(mime string, marshaler Marshaler) ServeMuxOption { - return func(mux *ServeMux) { - if err := mux.marshalers.add(mime, marshaler); err != nil { - panic(err) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go deleted file mode 100755 index 194de6f..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package runtime_test - -import ( - "errors" - "io" - "net/http" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -func TestMarshalerForRequest(t *testing.T) { - r, err := http.NewRequest("GET", "http://example.com", nil) - if err != nil { - t.Fatalf(`http.NewRequest("GET", "http://example.com", nil) failed with %v; want success`, err) - } - r.Header.Set("Accept", "application/x-out") - r.Header.Set("Content-Type", "application/x-in") - - mux := runtime.NewServeMux() - - in, out := runtime.MarshalerForRequest(mux, r) - if _, ok := in.(*runtime.JSONPb); !ok { - t.Errorf("in = %#v; want a runtime.JSONPb", in) - } - if _, ok := out.(*runtime.JSONPb); !ok { - t.Errorf("out = %#v; want a runtime.JSONPb", in) - } - - var marshalers [3]dummyMarshaler - specs := []struct { - opt runtime.ServeMuxOption - - wantIn runtime.Marshaler - wantOut runtime.Marshaler - }{ - { - opt: runtime.WithMarshalerOption(runtime.MIMEWildcard, &marshalers[0]), - wantIn: &marshalers[0], - wantOut: &marshalers[0], - }, - { - opt: runtime.WithMarshalerOption("application/x-in", &marshalers[1]), - wantIn: &marshalers[1], - wantOut: &marshalers[0], - }, - { - opt: runtime.WithMarshalerOption("application/x-out", &marshalers[2]), - wantIn: &marshalers[1], - wantOut: &marshalers[2], - }, - } - for i, spec := range specs { - var opts []runtime.ServeMuxOption - for _, s := range specs[:i+1] { - opts = append(opts, s.opt) - } - mux = runtime.NewServeMux(opts...) - - in, out = runtime.MarshalerForRequest(mux, r) - if got, want := in, spec.wantIn; got != want { - t.Errorf("in = %#v; want %#v", got, want) - } - if got, want := out, spec.wantOut; got != want { - t.Errorf("out = %#v; want %#v", got, want) - } - } - - r.Header.Set("Content-Type", "application/x-another") - in, out = runtime.MarshalerForRequest(mux, r) - if got, want := in, &marshalers[1]; got != want { - t.Errorf("in = %#v; want %#v", got, want) - } - if got, want := out, &marshalers[0]; got != want { - t.Errorf("out = %#v; want %#v", got, want) - } -} - -type dummyMarshaler struct{} - -func (dummyMarshaler) ContentType() string { return "" } -func (dummyMarshaler) Marshal(interface{}) ([]byte, error) { - return nil, errors.New("not implemented") -} - -func (dummyMarshaler) Unmarshal([]byte, interface{}) error { - return errors.New("not implemented") -} - -func (dummyMarshaler) NewDecoder(r io.Reader) runtime.Decoder { - return dummyDecoder{} -} -func (dummyMarshaler) NewEncoder(w io.Writer) runtime.Encoder { - return dummyEncoder{} -} - -type dummyDecoder struct{} - -func (dummyDecoder) Decode(interface{}) error { - return errors.New("not implemented") -} - -type dummyEncoder struct{} - -func (dummyEncoder) Encode(interface{}) error { - return errors.New("not implemented") -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go deleted file mode 100755 index 1d4c757..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go +++ /dev/null @@ -1,260 +0,0 @@ -package runtime - -import ( - "fmt" - "net/http" - "net/textproto" - "strings" - - "context" - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// A HandlerFunc handles a specific pair of path pattern and HTTP method. -type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) - -// ServeMux is a request multiplexer for grpc-gateway. -// It matches http requests to patterns and invokes the corresponding handler. -type ServeMux struct { - // handlers maps HTTP method to a list of handlers. - handlers map[string][]handler - forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error - marshalers marshalerRegistry - incomingHeaderMatcher HeaderMatcherFunc - outgoingHeaderMatcher HeaderMatcherFunc - metadataAnnotators []func(context.Context, *http.Request) metadata.MD - protoErrorHandler ProtoErrorHandlerFunc -} - -// ServeMuxOption is an option that can be given to a ServeMux on construction. -type ServeMuxOption func(*ServeMux) - -// WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption. -// -// forwardResponseOption is an option that will be called on the relevant context.Context, -// http.ResponseWriter, and proto.Message before every forwarded response. -// -// The message may be nil in the case where just a header is being sent. -func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption { - return func(serveMux *ServeMux) { - serveMux.forwardResponseOptions = append(serveMux.forwardResponseOptions, forwardResponseOption) - } -} - -// HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context. -type HeaderMatcherFunc func(string) (string, bool) - -// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header -// keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with -// 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'. -func DefaultHeaderMatcher(key string) (string, bool) { - key = textproto.CanonicalMIMEHeaderKey(key) - if isPermanentHTTPHeader(key) { - return MetadataPrefix + key, true - } else if strings.HasPrefix(key, MetadataHeaderPrefix) { - return key[len(MetadataHeaderPrefix):], true - } - return "", false -} - -// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway. -// -// This matcher will be called with each header in http.Request. If matcher returns true, that header will be -// passed to gRPC context. To transform the header before passing to gRPC context, matcher should return modified header. -func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { - return func(mux *ServeMux) { - mux.incomingHeaderMatcher = fn - } -} - -// WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway. -// -// This matcher will be called with each header in response header metadata. If matcher returns true, that header will be -// passed to http response returned from gateway. To transform the header before passing to response, -// matcher should return modified header. -func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { - return func(mux *ServeMux) { - mux.outgoingHeaderMatcher = fn - } -} - -// WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context. -// -// This can be used by services that need to read from http.Request and modify gRPC context. A common use case -// is reading token from cookie and adding it in gRPC context. -func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption { - return func(serveMux *ServeMux) { - serveMux.metadataAnnotators = append(serveMux.metadataAnnotators, annotator) - } -} - -// WithProtoErrorHandler returns a ServeMuxOption for passing metadata to a gRPC context. -// -// This can be used to handle an error as general proto message defined by gRPC. -// The response including body and status is not backward compatible with the default error handler. -// When this option is used, HTTPError and OtherErrorHandler are overwritten on initialization. -func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption { - return func(serveMux *ServeMux) { - serveMux.protoErrorHandler = fn - } -} - -// NewServeMux returns a new ServeMux whose internal mapping is empty. -func NewServeMux(opts ...ServeMuxOption) *ServeMux { - serveMux := &ServeMux{ - handlers: make(map[string][]handler), - forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), - marshalers: makeMarshalerMIMERegistry(), - } - - for _, opt := range opts { - opt(serveMux) - } - - if serveMux.protoErrorHandler != nil { - HTTPError = serveMux.protoErrorHandler - // OtherErrorHandler is no longer used when protoErrorHandler is set. - // Overwritten by a special error handler to return Unknown. - OtherErrorHandler = func(w http.ResponseWriter, r *http.Request, _ string, _ int) { - ctx := context.Background() - _, outboundMarshaler := MarshalerForRequest(serveMux, r) - sterr := status.Error(codes.Unknown, "unexpected use of OtherErrorHandler") - serveMux.protoErrorHandler(ctx, serveMux, outboundMarshaler, w, r, sterr) - } - } - - if serveMux.incomingHeaderMatcher == nil { - serveMux.incomingHeaderMatcher = DefaultHeaderMatcher - } - - if serveMux.outgoingHeaderMatcher == nil { - serveMux.outgoingHeaderMatcher = func(key string) (string, bool) { - return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true - } - } - - return serveMux -} - -// Handle associates "h" to the pair of HTTP method and path pattern. -func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { - s.handlers[meth] = append(s.handlers[meth], handler{pat: pat, h: h}) -} - -// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path. -func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - path := r.URL.Path - if !strings.HasPrefix(path, "/") { - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.InvalidArgument, http.StatusText(http.StatusBadRequest)) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) - } - return - } - - components := strings.Split(path[1:], "/") - l := len(components) - var verb string - if idx := strings.LastIndex(components[l-1], ":"); idx == 0 { - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) - } - return - } else if idx > 0 { - c := components[l-1] - components[l-1], verb = c[:idx], c[idx+1:] - } - - if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && isPathLengthFallback(r) { - r.Method = strings.ToUpper(override) - if err := r.ParseForm(); err != nil { - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.InvalidArgument, err.Error()) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) - } - return - } - } - for _, h := range s.handlers[r.Method] { - pathParams, err := h.pat.Match(components, verb) - if err != nil { - continue - } - h.h(w, r, pathParams) - return - } - - // lookup other methods to handle fallback from GET to POST and - // to determine if it is MethodNotAllowed or NotFound. - for m, handlers := range s.handlers { - if m == r.Method { - continue - } - for _, h := range handlers { - pathParams, err := h.pat.Match(components, verb) - if err != nil { - continue - } - // X-HTTP-Method-Override is optional. Always allow fallback to POST. - if isPathLengthFallback(r) { - if err := r.ParseForm(); err != nil { - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.InvalidArgument, err.Error()) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) - } - return - } - h.h(w, r, pathParams) - return - } - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusMethodNotAllowed)) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - } - return - } - } - - if s.protoErrorHandler != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) - s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) - } else { - OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) - } -} - -// GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux. -func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error { - return s.forwardResponseOptions -} - -func isPathLengthFallback(r *http.Request) bool { - return r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" -} - -type handler struct { - pat Pattern - h HandlerFunc -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go deleted file mode 100755 index bb90a73..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/mux_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package runtime_test - -import ( - "bytes" - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -func TestMuxServeHTTP(t *testing.T) { - type stubPattern struct { - method string - ops []int - pool []string - verb string - } - for _, spec := range []struct { - patterns []stubPattern - - reqMethod string - reqPath string - headers map[string]string - - respStatus int - respContent string - }{ - { - patterns: nil, - reqMethod: "GET", - reqPath: "/", - respStatus: http.StatusNotFound, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "GET", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "GET", - reqPath: "/bar", - respStatus: http.StatusNotFound, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "GET", - ops: []int{int(utilities.OpPush), 0}, - }, - }, - reqMethod: "GET", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - respStatus: http.StatusOK, - respContent: "POST /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "DELETE", - reqPath: "/foo", - respStatus: http.StatusMethodNotAllowed, - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - }, - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/x-www-form-urlencoded", - "X-HTTP-Method-Override": "GET", - }, - respStatus: http.StatusOK, - respContent: "GET /foo", - }, - { - patterns: []stubPattern{ - { - method: "GET", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - }, - }, - reqMethod: "POST", - reqPath: "/foo", - headers: map[string]string{ - "Content-Type": "application/json", - }, - respStatus: http.StatusMethodNotAllowed, - }, - { - patterns: []stubPattern{ - { - method: "POST", - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"foo"}, - verb: "bar", - }, - }, - reqMethod: "POST", - reqPath: "/foo:bar", - headers: map[string]string{ - "Content-Type": "application/json", - }, - respStatus: http.StatusOK, - respContent: "POST /foo:bar", - }, - } { - mux := runtime.NewServeMux() - for _, p := range spec.patterns { - func(p stubPattern) { - pat, err := runtime.NewPattern(1, p.ops, p.pool, p.verb) - if err != nil { - t.Fatalf("runtime.NewPattern(1, %#v, %#v, %q) failed with %v; want success", p.ops, p.pool, p.verb, err) - } - mux.Handle(p.method, pat, func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) { - fmt.Fprintf(w, "%s %s", p.method, pat.String()) - }) - }(p) - } - - url := fmt.Sprintf("http://host.example%s", spec.reqPath) - r, err := http.NewRequest(spec.reqMethod, url, bytes.NewReader(nil)) - if err != nil { - t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", spec.reqMethod, url, err) - } - for name, value := range spec.headers { - r.Header.Set(name, value) - } - w := httptest.NewRecorder() - mux.ServeHTTP(w, r) - - if got, want := w.Code, spec.respStatus; got != want { - t.Errorf("w.Code = %d; want %d; patterns=%v; req=%v", got, want, spec.patterns, r) - } - if spec.respContent != "" { - if got, want := w.Body.String(), spec.respContent; got != want { - t.Errorf("w.Body = %q; want %q; patterns=%v; req=%v", got, want, spec.patterns, r) - } - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go deleted file mode 100755 index 8a9ec2c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go +++ /dev/null @@ -1,227 +0,0 @@ -package runtime - -import ( - "errors" - "fmt" - "strings" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc/grpclog" -) - -var ( - // ErrNotMatch indicates that the given HTTP request path does not match to the pattern. - ErrNotMatch = errors.New("not match to the path pattern") - // ErrInvalidPattern indicates that the given definition of Pattern is not valid. - ErrInvalidPattern = errors.New("invalid pattern") -) - -type op struct { - code utilities.OpCode - operand int -} - -// Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto. -type Pattern struct { - // ops is a list of operations - ops []op - // pool is a constant pool indexed by the operands or vars. - pool []string - // vars is a list of variables names to be bound by this pattern - vars []string - // stacksize is the max depth of the stack - stacksize int - // tailLen is the length of the fixed-size segments after a deep wildcard - tailLen int - // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. - verb string -} - -// NewPattern returns a new Pattern from the given definition values. -// "ops" is a sequence of op codes. "pool" is a constant pool. -// "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. -// "version" must be 1 for now. -// It returns an error if the given definition is invalid. -func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) { - if version != 1 { - grpclog.Printf("unsupported version: %d", version) - return Pattern{}, ErrInvalidPattern - } - - l := len(ops) - if l%2 != 0 { - grpclog.Printf("odd number of ops codes: %d", l) - return Pattern{}, ErrInvalidPattern - } - - var ( - typedOps []op - stack, maxstack int - tailLen int - pushMSeen bool - vars []string - ) - for i := 0; i < l; i += 2 { - op := op{code: utilities.OpCode(ops[i]), operand: ops[i+1]} - switch op.code { - case utilities.OpNop: - continue - case utilities.OpPush: - if pushMSeen { - tailLen++ - } - stack++ - case utilities.OpPushM: - if pushMSeen { - grpclog.Printf("pushM appears twice") - return Pattern{}, ErrInvalidPattern - } - pushMSeen = true - stack++ - case utilities.OpLitPush: - if op.operand < 0 || len(pool) <= op.operand { - grpclog.Printf("negative literal index: %d", op.operand) - return Pattern{}, ErrInvalidPattern - } - if pushMSeen { - tailLen++ - } - stack++ - case utilities.OpConcatN: - if op.operand <= 0 { - grpclog.Printf("negative concat size: %d", op.operand) - return Pattern{}, ErrInvalidPattern - } - stack -= op.operand - if stack < 0 { - grpclog.Print("stack underflow") - return Pattern{}, ErrInvalidPattern - } - stack++ - case utilities.OpCapture: - if op.operand < 0 || len(pool) <= op.operand { - grpclog.Printf("variable name index out of bound: %d", op.operand) - return Pattern{}, ErrInvalidPattern - } - v := pool[op.operand] - op.operand = len(vars) - vars = append(vars, v) - stack-- - if stack < 0 { - grpclog.Printf("stack underflow") - return Pattern{}, ErrInvalidPattern - } - default: - grpclog.Printf("invalid opcode: %d", op.code) - return Pattern{}, ErrInvalidPattern - } - - if maxstack < stack { - maxstack = stack - } - typedOps = append(typedOps, op) - } - return Pattern{ - ops: typedOps, - pool: pool, - vars: vars, - stacksize: maxstack, - tailLen: tailLen, - verb: verb, - }, nil -} - -// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization. -func MustPattern(p Pattern, err error) Pattern { - if err != nil { - grpclog.Fatalf("Pattern initialization failed: %v", err) - } - return p -} - -// Match examines components if it matches to the Pattern. -// If it matches, the function returns a mapping from field paths to their captured values. -// If otherwise, the function returns an error. -func (p Pattern) Match(components []string, verb string) (map[string]string, error) { - if p.verb != verb { - return nil, ErrNotMatch - } - - var pos int - stack := make([]string, 0, p.stacksize) - captured := make([]string, len(p.vars)) - l := len(components) - for _, op := range p.ops { - switch op.code { - case utilities.OpNop: - continue - case utilities.OpPush, utilities.OpLitPush: - if pos >= l { - return nil, ErrNotMatch - } - c := components[pos] - if op.code == utilities.OpLitPush { - if lit := p.pool[op.operand]; c != lit { - return nil, ErrNotMatch - } - } - stack = append(stack, c) - pos++ - case utilities.OpPushM: - end := len(components) - if end < pos+p.tailLen { - return nil, ErrNotMatch - } - end -= p.tailLen - stack = append(stack, strings.Join(components[pos:end], "/")) - pos = end - case utilities.OpConcatN: - n := op.operand - l := len(stack) - n - stack = append(stack[:l], strings.Join(stack[l:], "/")) - case utilities.OpCapture: - n := len(stack) - 1 - captured[op.operand] = stack[n] - stack = stack[:n] - } - } - if pos < l { - return nil, ErrNotMatch - } - bindings := make(map[string]string) - for i, val := range captured { - bindings[p.vars[i]] = val - } - return bindings, nil -} - -// Verb returns the verb part of the Pattern. -func (p Pattern) Verb() string { return p.verb } - -func (p Pattern) String() string { - var stack []string - for _, op := range p.ops { - switch op.code { - case utilities.OpNop: - continue - case utilities.OpPush: - stack = append(stack, "*") - case utilities.OpLitPush: - stack = append(stack, p.pool[op.operand]) - case utilities.OpPushM: - stack = append(stack, "**") - case utilities.OpConcatN: - n := op.operand - l := len(stack) - n - stack = append(stack[:l], strings.Join(stack[l:], "/")) - case utilities.OpCapture: - n := len(stack) - 1 - stack[n] = fmt.Sprintf("{%s=%s}", p.vars[op.operand], stack[n]) - } - } - segs := strings.Join(stack, "/") - if p.verb != "" { - return fmt.Sprintf("/%s:%s", segs, p.verb) - } - return "/" + segs -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go deleted file mode 100755 index 8f5a664..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern_test.go +++ /dev/null @@ -1,590 +0,0 @@ -package runtime - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -const ( - validVersion = 1 - anything = 0 -) - -func TestNewPattern(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - - stackSizeWant, tailLenWant int - }{ - {}, - { - ops: []int{int(utilities.OpNop), anything}, - stackSizeWant: 0, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpPush), anything}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"abc"}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{int(utilities.OpPushM), anything}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - }, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"abc"}, - stackSizeWant: 1, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"lit1", "lit2", "var1"}, - stackSizeWant: 4, - tailLenWant: 0, - }, - { - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - }, - pool: []string{"lit1", "lit2", "var1"}, - stackSizeWant: 2, - tailLenWant: 2, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 2, - int(utilities.OpConcatN), 3, - int(utilities.OpLitPush), 3, - int(utilities.OpCapture), 4, - }, - pool: []string{"lit1", "lit2", "lit3", "lit4", "var1"}, - stackSizeWant: 4, - tailLenWant: 2, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"abc"}, - verb: "LOCK", - stackSizeWant: 1, - tailLenWant: 0, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - if got, want := pat.stacksize, spec.stackSizeWant; got != want { - t.Errorf("pat.stacksize = %d; want %d", got, want) - } - if got, want := pat.tailLen, spec.tailLenWant; got != want { - t.Errorf("pat.stacksize = %d; want %d", got, want) - } - } -} - -func TestNewPatternWithWrongOp(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - }{ - { - // op code out of bound - ops: []int{-1, anything}, - }, - { - // op code out of bound - ops: []int{int(utilities.OpEnd), 0}, - }, - { - // odd number of items - ops: []int{int(utilities.OpPush)}, - }, - { - // negative index - ops: []int{int(utilities.OpLitPush), -1}, - pool: []string{"abc"}, - }, - { - // index out of bound - ops: []int{int(utilities.OpLitPush), 1}, - pool: []string{"abc"}, - }, - { - // negative # of segments - ops: []int{int(utilities.OpConcatN), -1}, - pool: []string{"abc"}, - }, - { - // negative index - ops: []int{int(utilities.OpCapture), -1}, - pool: []string{"abc"}, - }, - { - // index out of bound - ops: []int{int(utilities.OpCapture), 1}, - pool: []string{"abc"}, - }, - { - // pushM appears twice - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 0, - int(utilities.OpPushM), anything, - }, - pool: []string{"abc"}, - }, - } { - _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err == nil { - t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) - continue - } - if err != ErrInvalidPattern { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) - continue - } - } -} - -func TestNewPatternWithStackUnderflow(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - }{ - { - ops: []int{int(utilities.OpConcatN), 1}, - }, - { - ops: []int{int(utilities.OpCapture), 0}, - pool: []string{"abc"}, - }, - } { - _, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err == nil { - t.Errorf("NewPattern(%d, %v, %q, %q) succeeded; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, ErrInvalidPattern) - continue - } - if err != ErrInvalidPattern { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want failure with %v", validVersion, spec.ops, spec.pool, spec.verb, err, ErrInvalidPattern) - continue - } - } -} - -func TestMatch(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - verb string - - match []string - notMatch []string - }{ - { - match: []string{""}, - notMatch: []string{"example"}, - }, - { - ops: []int{int(utilities.OpNop), anything}, - match: []string{""}, - notMatch: []string{"example", "path/to/example"}, - }, - { - ops: []int{int(utilities.OpPush), anything}, - match: []string{"abc", "def"}, - notMatch: []string{"", "abc/def"}, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - match: []string{"v1"}, - notMatch: []string{"", "v2"}, - }, - { - ops: []int{int(utilities.OpPushM), anything}, - match: []string{"", "abc", "abc/def", "abc/def/ghi"}, - }, - { - ops: []int{ - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 0, - }, - pool: []string{"tail"}, - match: []string{"tail", "abc/tail", "abc/def/tail"}, - notMatch: []string{ - "", "abc", "abc/def", - "tail/extra", "abc/tail/extra", "abc/def/tail/extra", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - match: []string{"v1/bucket/my-bucket", "v1/bucket/our-bucket"}, - notMatch: []string{ - "", - "v1", - "v1/bucket", - "v2/bucket/my-bucket", - "v1/pubsub/my-topic", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "o", "name"}, - match: []string{ - "v1/o", - "v1/o/my-bucket", - "v1/o/our-bucket", - "v1/o/my-bucket/dir", - "v1/o/my-bucket/dir/dir2", - "v1/o/my-bucket/dir/dir2/obj", - }, - notMatch: []string{ - "", - "v1", - "v2/o/my-bucket", - "v1/b/my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 4, - }, - pool: []string{"v2", "b", "name", "o", "oname"}, - match: []string{ - "v2/b/my-bucket/o/obj", - "v2/b/our-bucket/o/obj", - "v2/b/my-bucket/o/dir", - }, - notMatch: []string{ - "", - "v2", - "v2/b", - "v2/b/my-bucket", - "v2/b/my-bucket/o", - }, - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"v1"}, - verb: "LOCK", - match: []string{"v1:LOCK"}, - notMatch: []string{"v1", "LOCK"}, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - - for _, path := range spec.match { - _, err = pat.Match(segments(path)) - if err != nil { - t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", path, err, spec.ops, spec.pool) - } - } - - for _, path := range spec.notMatch { - _, err = pat.Match(segments(path)) - if err == nil { - t.Errorf("pat.Match(%q) succeeded; want failure with %v; pattern = (%v, %q)", path, ErrNotMatch, spec.ops, spec.pool) - continue - } - if err != ErrNotMatch { - t.Errorf("pat.Match(%q) failed with %v; want failure with %v; pattern = (%v, %q)", spec.notMatch, err, ErrNotMatch, spec.ops, spec.pool) - } - } - } -} - -func TestMatchWithBinding(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - path string - verb string - - want map[string]string - }{ - { - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpNop), anything}, - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPush), anything}, - path: "abc", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPush), anything}, - verb: "LOCK", - path: "abc:LOCK", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"endpoint"}, - path: "endpoint", - want: make(map[string]string), - }, - { - ops: []int{int(utilities.OpPushM), anything}, - path: "abc/def/ghi", - want: make(map[string]string), - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - path: "v1/bucket/my-bucket", - want: map[string]string{ - "name": "my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "bucket", "name"}, - verb: "LOCK", - path: "v1/bucket/my-bucket:LOCK", - want: map[string]string{ - "name": "my-bucket", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - }, - pool: []string{"v1", "o", "name"}, - path: "v1/o/my-bucket/dir/dir2/obj", - want: map[string]string{ - "name": "o/my-bucket/dir/dir2/obj", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 2, - int(utilities.OpConcatN), 3, - int(utilities.OpCapture), 4, - int(utilities.OpLitPush), 3, - }, - pool: []string{"v1", "o", ".ext", "tail", "name"}, - path: "v1/o/my-bucket/dir/dir2/obj/.ext/tail", - want: map[string]string{ - "name": "o/my-bucket/dir/dir2/obj/.ext", - }, - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 4, - }, - pool: []string{"v2", "b", "name", "o", "oname"}, - path: "v2/b/my-bucket/o/obj", - want: map[string]string{ - "name": "b/my-bucket", - "oname": "obj", - }, - }, - } { - pat, err := NewPattern(validVersion, spec.ops, spec.pool, spec.verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, spec.verb, err) - continue - } - - got, err := pat.Match(segments(spec.path)) - if err != nil { - t.Errorf("pat.Match(%q) failed with %v; want success; pattern = (%v, %q)", spec.path, err, spec.ops, spec.pool) - } - if !reflect.DeepEqual(got, spec.want) { - t.Errorf("pat.Match(%q) = %q; want %q; pattern = (%v, %q)", spec.path, got, spec.want, spec.ops, spec.pool) - } - } -} - -func segments(path string) (components []string, verb string) { - if path == "" { - return nil, "" - } - components = strings.Split(path, "/") - l := len(components) - c := components[l-1] - if idx := strings.LastIndex(c, ":"); idx >= 0 { - components[l-1], verb = c[:idx], c[idx+1:] - } - return components, verb -} - -func TestPatternString(t *testing.T) { - for _, spec := range []struct { - ops []int - pool []string - - want string - }{ - { - want: "/", - }, - { - ops: []int{int(utilities.OpNop), anything}, - want: "/", - }, - { - ops: []int{int(utilities.OpPush), anything}, - want: "/*", - }, - { - ops: []int{int(utilities.OpLitPush), 0}, - pool: []string{"endpoint"}, - want: "/endpoint", - }, - { - ops: []int{int(utilities.OpPushM), anything}, - want: "/**", - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - }, - want: "/*", - }, - { - ops: []int{ - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 1, - int(utilities.OpCapture), 0, - }, - pool: []string{"name"}, - want: "/{name=*}", - }, - { - ops: []int{ - int(utilities.OpLitPush), 0, - int(utilities.OpLitPush), 1, - int(utilities.OpPush), anything, - int(utilities.OpConcatN), 2, - int(utilities.OpCapture), 2, - int(utilities.OpLitPush), 3, - int(utilities.OpPushM), anything, - int(utilities.OpLitPush), 4, - int(utilities.OpConcatN), 3, - int(utilities.OpCapture), 6, - int(utilities.OpLitPush), 5, - }, - pool: []string{"v1", "buckets", "bucket_name", "objects", ".ext", "tail", "name"}, - want: "/v1/{bucket_name=buckets/*}/{name=objects/**/.ext}/tail", - }, - } { - p, err := NewPattern(validVersion, spec.ops, spec.pool, "") - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, "", err) - continue - } - if got, want := p.String(), spec.want; got != want { - t.Errorf("%#v.String() = %q; want %q", p, got, want) - } - - verb := "LOCK" - p, err = NewPattern(validVersion, spec.ops, spec.pool, verb) - if err != nil { - t.Errorf("NewPattern(%d, %v, %q, %q) failed with %v; want success", validVersion, spec.ops, spec.pool, verb, err) - continue - } - if got, want := p.String(), fmt.Sprintf("%s:%s", spec.want, verb); got != want { - t.Errorf("%#v.String() = %q; want %q", p, got, want) - } - } -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go deleted file mode 100755 index a3151e2..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go +++ /dev/null @@ -1,80 +0,0 @@ -package runtime - -import ( - "github.com/golang/protobuf/proto" -) - -// StringP returns a pointer to a string whose pointee is same as the given string value. -func StringP(val string) (*string, error) { - return proto.String(val), nil -} - -// BoolP parses the given string representation of a boolean value, -// and returns a pointer to a bool whose value is same as the parsed value. -func BoolP(val string) (*bool, error) { - b, err := Bool(val) - if err != nil { - return nil, err - } - return proto.Bool(b), nil -} - -// Float64P parses the given string representation of a floating point number, -// and returns a pointer to a float64 whose value is same as the parsed number. -func Float64P(val string) (*float64, error) { - f, err := Float64(val) - if err != nil { - return nil, err - } - return proto.Float64(f), nil -} - -// Float32P parses the given string representation of a floating point number, -// and returns a pointer to a float32 whose value is same as the parsed number. -func Float32P(val string) (*float32, error) { - f, err := Float32(val) - if err != nil { - return nil, err - } - return proto.Float32(f), nil -} - -// Int64P parses the given string representation of an integer -// and returns a pointer to a int64 whose value is same as the parsed integer. -func Int64P(val string) (*int64, error) { - i, err := Int64(val) - if err != nil { - return nil, err - } - return proto.Int64(i), nil -} - -// Int32P parses the given string representation of an integer -// and returns a pointer to a int32 whose value is same as the parsed integer. -func Int32P(val string) (*int32, error) { - i, err := Int32(val) - if err != nil { - return nil, err - } - return proto.Int32(i), err -} - -// Uint64P parses the given string representation of an integer -// and returns a pointer to a uint64 whose value is same as the parsed integer. -func Uint64P(val string) (*uint64, error) { - i, err := Uint64(val) - if err != nil { - return nil, err - } - return proto.Uint64(i), err -} - -// Uint32P parses the given string representation of an integer -// and returns a pointer to a uint32 whose value is same as the parsed integer. -func Uint32P(val string) (*uint32, error) { - i, err := Uint32(val) - if err != nil { - return nil, err - } - return proto.Uint32(i), err -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go deleted file mode 100755 index 059928c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go +++ /dev/null @@ -1,61 +0,0 @@ -package runtime - -import ( - "io" - "net/http" - - "context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// ProtoErrorHandlerFunc handles the error as a gRPC error generated via status package and replies to the request. -type ProtoErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error) - -var _ ProtoErrorHandlerFunc = DefaultHTTPProtoErrorHandler - -// DefaultHTTPProtoErrorHandler is an implementation of HTTPError. -// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. -// If otherwise, it replies with http.StatusInternalServerError. -// -// The response body returned by this function is a Status message marshaled by a Marshaler. -// -// Do not set this function to HTTPError variable directly, use WithProtoErrorHandler option instead. -func DefaultHTTPProtoErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) { - // return Internal when Marshal failed - const fallback = `{"code": 13, "message": "failed to marshal error message"}` - - w.Header().Del("Trailer") - w.Header().Set("Content-Type", marshaler.ContentType()) - - s, ok := status.FromError(err) - if !ok { - s = status.New(codes.Unknown, err.Error()) - } - - buf, merr := marshaler.Marshal(s.Proto()) - if merr != nil { - grpclog.Printf("Failed to marshal error message %q: %v", s.Proto(), merr) - w.WriteHeader(http.StatusInternalServerError) - if _, err := io.WriteString(w, fallback); err != nil { - grpclog.Printf("Failed to write response: %v", err) - } - return - } - - md, ok := ServerMetadataFromContext(ctx) - if !ok { - grpclog.Printf("Failed to extract ServerMetadata from context") - } - - handleForwardResponseServerMetadata(w, mux, md) - handleForwardResponseTrailerHeader(w, md) - st := HTTPStatusFromCode(s.Code()) - w.WriteHeader(st) - if _, err := w.Write(buf); err != nil { - grpclog.Printf("Failed to write response: %v", err) - } - - handleForwardResponseTrailer(w, md) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go deleted file mode 100755 index 07d0ff8..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go +++ /dev/null @@ -1,357 +0,0 @@ -package runtime - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "regexp" - "strconv" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc/grpclog" -) - -// PopulateQueryParameters populates "values" into "msg". -// A value is ignored if its key starts with one of the elements in "filter". -func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { - for key, values := range values { - re, err := regexp.Compile("^(.*)\\[(.*)\\]$") - if err != nil { - return err - } - match := re.FindStringSubmatch(key) - if len(match) == 3 { - key = match[1] - values = append([]string{match[2]}, values...) - } - fieldPath := strings.Split(key, ".") - if filter.HasCommonPrefix(fieldPath) { - continue - } - if err := populateFieldValueFromPath(msg, fieldPath, values); err != nil { - return err - } - } - return nil -} - -// PopulateFieldFromPath sets a value in a nested Protobuf structure. -// It instantiates missing protobuf fields as it goes. -func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { - fieldPath := strings.Split(fieldPathString, ".") - return populateFieldValueFromPath(msg, fieldPath, []string{value}) -} - -func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error { - m := reflect.ValueOf(msg) - if m.Kind() != reflect.Ptr { - return fmt.Errorf("unexpected type %T: %v", msg, msg) - } - var props *proto.Properties - m = m.Elem() - for i, fieldName := range fieldPath { - isLast := i == len(fieldPath)-1 - if !isLast && m.Kind() != reflect.Struct { - return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, ".")) - } - var f reflect.Value - var err error - f, props, err = fieldByProtoName(m, fieldName) - if err != nil { - return err - } else if !f.IsValid() { - grpclog.Printf("field not found in %T: %s", msg, strings.Join(fieldPath, ".")) - return nil - } - - switch f.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: - if !isLast { - return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) - } - m = f - case reflect.Slice: - if !isLast { - return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, ".")) - } - // Handle []byte - if f.Type().Elem().Kind() == reflect.Uint8 { - m = f - break - } - return populateRepeatedField(f, values, props) - case reflect.Ptr: - if f.IsNil() { - m = reflect.New(f.Type().Elem()) - f.Set(m.Convert(f.Type())) - } - m = f.Elem() - continue - case reflect.Struct: - m = f - continue - case reflect.Map: - if !isLast { - return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) - } - return populateMapField(f, values, props) - default: - return fmt.Errorf("unexpected type %s in %T", f.Type(), msg) - } - } - switch len(values) { - case 0: - return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, ".")) - case 1: - default: - grpclog.Printf("too many field values: %s", strings.Join(fieldPath, ".")) - } - return populateField(m, values[0], props) -} - -// fieldByProtoName looks up a field whose corresponding protobuf field name is "name". -// "m" must be a struct value. It returns zero reflect.Value if no such field found. -func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties, error) { - props := proto.GetProperties(m.Type()) - - // look up field name in oneof map - if op, ok := props.OneofTypes[name]; ok { - v := reflect.New(op.Type.Elem()) - field := m.Field(op.Field) - if !field.IsNil() { - return reflect.Value{}, nil, fmt.Errorf("field already set for %s oneof", props.Prop[op.Field].OrigName) - } - field.Set(v) - return v.Elem().Field(0), op.Prop, nil - } - - for _, p := range props.Prop { - if p.OrigName == name { - return m.FieldByName(p.Name), p, nil - } - if p.JSONName == name { - return m.FieldByName(p.Name), p, nil - } - } - return reflect.Value{}, nil, nil -} - -func populateMapField(f reflect.Value, values []string, props *proto.Properties) error { - if len(values) != 2 { - return fmt.Errorf("more than one value provided for key %s in map %s", values[0], props.Name) - } - - key, value := values[0], values[1] - keyType := f.Type().Key() - valueType := f.Type().Elem() - if f.IsNil() { - f.Set(reflect.MakeMap(f.Type())) - } - - keyConv, ok := convFromType[keyType.Kind()] - if !ok { - return fmt.Errorf("unsupported key type %s in map %s", keyType, props.Name) - } - valueConv, ok := convFromType[valueType.Kind()] - if !ok { - return fmt.Errorf("unsupported value type %s in map %s", valueType, props.Name) - } - - keyV := keyConv.Call([]reflect.Value{reflect.ValueOf(key)}) - if err := keyV[1].Interface(); err != nil { - return err.(error) - } - valueV := valueConv.Call([]reflect.Value{reflect.ValueOf(value)}) - if err := valueV[1].Interface(); err != nil { - return err.(error) - } - - f.SetMapIndex(keyV[0].Convert(keyType), valueV[0].Convert(valueType)) - - return nil -} - -func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error { - elemType := f.Type().Elem() - - // is the destination field a slice of an enumeration type? - if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { - return populateFieldEnumRepeated(f, values, enumValMap) - } - - conv, ok := convFromType[elemType.Kind()] - if !ok { - return fmt.Errorf("unsupported field type %s", elemType) - } - f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) - for i, v := range values { - result := conv.Call([]reflect.Value{reflect.ValueOf(v)}) - if err := result[1].Interface(); err != nil { - return err.(error) - } - f.Index(i).Set(result[0].Convert(f.Index(i).Type())) - } - return nil -} - -func populateField(f reflect.Value, value string, props *proto.Properties) error { - i := f.Addr().Interface() - - // Handle protobuf well known types - type wkt interface { - XXX_WellKnownType() string - } - if wkt, ok := i.(wkt); ok { - switch wkt.XXX_WellKnownType() { - case "Timestamp": - if value == "null" { - f.Field(0).SetInt(0) - f.Field(1).SetInt(0) - return nil - } - - t, err := time.Parse(time.RFC3339Nano, value) - if err != nil { - return fmt.Errorf("bad Timestamp: %v", err) - } - f.Field(0).SetInt(int64(t.Unix())) - f.Field(1).SetInt(int64(t.Nanosecond())) - return nil - case "DoubleValue": - fallthrough - case "FloatValue": - float64Val, err := strconv.ParseFloat(value, 64) - if err != nil { - return fmt.Errorf("bad DoubleValue: %s", value) - } - f.Field(0).SetFloat(float64Val) - return nil - case "Int64Value": - fallthrough - case "Int32Value": - int64Val, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return fmt.Errorf("bad DoubleValue: %s", value) - } - f.Field(0).SetInt(int64Val) - return nil - case "UInt64Value": - fallthrough - case "UInt32Value": - uint64Val, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return fmt.Errorf("bad DoubleValue: %s", value) - } - f.Field(0).SetUint(uint64Val) - return nil - case "BoolValue": - if value == "true" { - f.Field(0).SetBool(true) - } else if value == "false" { - f.Field(0).SetBool(false) - } else { - return fmt.Errorf("bad BoolValue: %s", value) - } - return nil - case "StringValue": - f.Field(0).SetString(value) - return nil - case "BytesValue": - bytesVal, err := base64.StdEncoding.DecodeString(value) - if err != nil { - return fmt.Errorf("bad BytesValue: %s", value) - } - f.Field(0).SetBytes(bytesVal) - return nil - } - } - - // Handle google well known types - if gwkt, ok := i.(proto.Message); ok { - switch proto.MessageName(gwkt) { - case "google.protobuf.FieldMask": - p := f.Field(0) - for _, v := range strings.Split(value, ",") { - if v != "" { - p.Set(reflect.Append(p, reflect.ValueOf(v))) - } - } - return nil - } - } - - // is the destination field an enumeration type? - if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { - return populateFieldEnum(f, value, enumValMap) - } - - conv, ok := convFromType[f.Kind()] - if !ok { - return fmt.Errorf("unsupported field type %T", f) - } - result := conv.Call([]reflect.Value{reflect.ValueOf(value)}) - if err := result[1].Interface(); err != nil { - return err.(error) - } - f.Set(result[0].Convert(f.Type())) - return nil -} - -func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) { - // see if it's an enumeration string - if enumVal, ok := enumValMap[value]; ok { - return reflect.ValueOf(enumVal).Convert(t), nil - } - - // check for an integer that matches an enumeration value - eVal, err := strconv.Atoi(value) - if err != nil { - return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) - } - for _, v := range enumValMap { - if v == int32(eVal) { - return reflect.ValueOf(eVal).Convert(t), nil - } - } - return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) -} - -func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error { - cval, err := convertEnum(value, f.Type(), enumValMap) - if err != nil { - return err - } - f.Set(cval) - return nil -} - -func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error { - elemType := f.Type().Elem() - f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) - for i, v := range values { - result, err := convertEnum(v, elemType, enumValMap) - if err != nil { - return err - } - f.Index(i).Set(result) - } - return nil -} - -var ( - convFromType = map[reflect.Kind]reflect.Value{ - reflect.String: reflect.ValueOf(String), - reflect.Bool: reflect.ValueOf(Bool), - reflect.Float64: reflect.ValueOf(Float64), - reflect.Float32: reflect.ValueOf(Float32), - reflect.Int64: reflect.ValueOf(Int64), - reflect.Int32: reflect.ValueOf(Int32), - reflect.Uint64: reflect.ValueOf(Uint64), - reflect.Uint32: reflect.ValueOf(Uint32), - reflect.Slice: reflect.ValueOf(Bytes), - } -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go deleted file mode 100755 index 904be49..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/runtime/query_test.go +++ /dev/null @@ -1,794 +0,0 @@ -package runtime_test - -import ( - "errors" - "fmt" - "net/url" - "reflect" - "testing" - "time" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/genproto/protobuf/field_mask" -) - -func TestPopulateParameters(t *testing.T) { - timeT := time.Date(2016, time.December, 15, 12, 23, 32, 49, time.UTC) - timeStr := timeT.Format(time.RFC3339Nano) - timePb, err := ptypes.TimestampProto(timeT) - if err != nil { - t.Fatalf("Couldn't setup timestamp in Protobuf format: %v", err) - } - - fieldmaskStr := "float_value,double_value" - fieldmaskPb := &field_mask.FieldMask{Paths: []string{"float_value", "double_value"}} - - for _, spec := range []struct { - values url.Values - filter *utilities.DoubleArray - want proto.Message - wanterr error - }{ - { - values: url.Values{ - "float_value": {"1.5"}, - "double_value": {"2.5"}, - "int64_value": {"-1"}, - "int32_value": {"-2"}, - "uint64_value": {"3"}, - "uint32_value": {"4"}, - "bool_value": {"true"}, - "string_value": {"str"}, - "bytes_value": {"Ynl0ZXM="}, - "repeated_value": {"a", "b", "c"}, - "enum_value": {"1"}, - "repeated_enum": {"1", "2", "0"}, - "timestamp_value": {timeStr}, - "fieldmask_value": {fieldmaskStr}, - "wrapper_float_value": {"1.5"}, - "wrapper_double_value": {"2.5"}, - "wrapper_int64_value": {"-1"}, - "wrapper_int32_value": {"-2"}, - "wrapper_u_int64_value": {"3"}, - "wrapper_u_int32_value": {"4"}, - "wrapper_bool_value": {"true"}, - "wrapper_string_value": {"str"}, - "wrapper_bytes_value": {"Ynl0ZXM="}, - "map_value[key]": {"value"}, - "map_value[second]": {"bar"}, - "map_value[third]": {"zzz"}, - "map_value[fourth]": {""}, - `map_value[~!@#$%^&*()]`: {"value"}, - "map_value2[key]": {"-2"}, - "map_value3[-2]": {"value"}, - "map_value4[key]": {"-1"}, - "map_value5[-1]": {"value"}, - "map_value6[key]": {"3"}, - "map_value7[3]": {"value"}, - "map_value8[key]": {"4"}, - "map_value9[4]": {"value"}, - "map_value10[key]": {"1.5"}, - "map_value11[1.5]": {"value"}, - "map_value12[key]": {"2.5"}, - "map_value13[2.5]": {"value"}, - "map_value14[key]": {"true"}, - "map_value15[true]": {"value"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: -1, - Int32Value: -2, - Uint64Value: 3, - Uint32Value: 4, - BoolValue: true, - StringValue: "str", - BytesValue: []byte("bytes"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - TimestampValue: timePb, - FieldMaskValue: fieldmaskPb, - WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, - WrapperInt64Value: &wrappers.Int64Value{Value: -1}, - WrapperInt32Value: &wrappers.Int32Value{Value: -2}, - WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, - WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, - WrapperBoolValue: &wrappers.BoolValue{Value: true}, - WrapperStringValue: &wrappers.StringValue{Value: "str"}, - WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, - MapValue: map[string]string{ - "key": "value", - "second": "bar", - "third": "zzz", - "fourth": "", - `~!@#$%^&*()`: "value", - }, - MapValue2: map[string]int32{"key": -2}, - MapValue3: map[int32]string{-2: "value"}, - MapValue4: map[string]int64{"key": -1}, - MapValue5: map[int64]string{-1: "value"}, - MapValue6: map[string]uint32{"key": 3}, - MapValue7: map[uint32]string{3: "value"}, - MapValue8: map[string]uint64{"key": 4}, - MapValue9: map[uint64]string{4: "value"}, - MapValue10: map[string]float32{"key": 1.5}, - MapValue11: map[float32]string{1.5: "value"}, - MapValue12: map[string]float64{"key": 2.5}, - MapValue13: map[float64]string{2.5: "value"}, - MapValue14: map[string]bool{"key": true}, - MapValue15: map[bool]string{true: "value"}, - }, - }, - { - values: url.Values{ - "floatValue": {"1.5"}, - "doubleValue": {"2.5"}, - "int64Value": {"-1"}, - "int32Value": {"-2"}, - "uint64Value": {"3"}, - "uint32Value": {"4"}, - "boolValue": {"true"}, - "stringValue": {"str"}, - "bytesValue": {"Ynl0ZXM="}, - "repeatedValue": {"a", "b", "c"}, - "enumValue": {"1"}, - "repeatedEnum": {"1", "2", "0"}, - "timestampValue": {timeStr}, - "fieldmaskValue": {fieldmaskStr}, - "wrapperFloatValue": {"1.5"}, - "wrapperDoubleValue": {"2.5"}, - "wrapperInt64Value": {"-1"}, - "wrapperInt32Value": {"-2"}, - "wrapperUInt64Value": {"3"}, - "wrapperUInt32Value": {"4"}, - "wrapperBoolValue": {"true"}, - "wrapperStringValue": {"str"}, - "wrapperBytesValue": {"Ynl0ZXM="}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - FloatValue: 1.5, - DoubleValue: 2.5, - Int64Value: -1, - Int32Value: -2, - Uint64Value: 3, - Uint32Value: 4, - BoolValue: true, - StringValue: "str", - BytesValue: []byte("bytes"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - TimestampValue: timePb, - FieldMaskValue: fieldmaskPb, - WrapperFloatValue: &wrappers.FloatValue{Value: 1.5}, - WrapperDoubleValue: &wrappers.DoubleValue{Value: 2.5}, - WrapperInt64Value: &wrappers.Int64Value{Value: -1}, - WrapperInt32Value: &wrappers.Int32Value{Value: -2}, - WrapperUInt64Value: &wrappers.UInt64Value{Value: 3}, - WrapperUInt32Value: &wrappers.UInt32Value{Value: 4}, - WrapperBoolValue: &wrappers.BoolValue{Value: true}, - WrapperStringValue: &wrappers.StringValue{Value: "str"}, - WrapperBytesValue: &wrappers.BytesValue{Value: []byte("bytes")}, - }, - }, - { - values: url.Values{ - "enum_value": {"EnumValue_Z"}, - "repeated_enum": {"EnumValue_X", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - EnumValue: EnumValue_Z, - RepeatedEnum: []EnumValue{EnumValue_X, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "float_value": {"1.5"}, - "double_value": {"2.5"}, - "int64_value": {"-1"}, - "int32_value": {"-2"}, - "uint64_value": {"3"}, - "uint32_value": {"4"}, - "bool_value": {"true"}, - "string_value": {"str"}, - "repeated_value": {"a", "b", "c"}, - "enum_value": {"1"}, - "repeated_enum": {"1", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto2Message{ - FloatValue: proto.Float32(1.5), - DoubleValue: proto.Float64(2.5), - Int64Value: proto.Int64(-1), - Int32Value: proto.Int32(-2), - Uint64Value: proto.Uint64(3), - Uint32Value: proto.Uint32(4), - BoolValue: proto.Bool(true), - StringValue: proto.String("str"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "floatValue": {"1.5"}, - "doubleValue": {"2.5"}, - "int64Value": {"-1"}, - "int32Value": {"-2"}, - "uint64Value": {"3"}, - "uint32Value": {"4"}, - "boolValue": {"true"}, - "stringValue": {"str"}, - "repeatedValue": {"a", "b", "c"}, - "enumValue": {"1"}, - "repeatedEnum": {"1", "2", "0"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto2Message{ - FloatValue: proto.Float32(1.5), - DoubleValue: proto.Float64(2.5), - Int64Value: proto.Int64(-1), - Int32Value: proto.Int32(-2), - Uint64Value: proto.Uint64(3), - Uint32Value: proto.Uint32(4), - BoolValue: proto.Bool(true), - StringValue: proto.String("str"), - RepeatedValue: []string{"a", "b", "c"}, - EnumValue: EnumValue_Y, - RepeatedEnum: []EnumValue{EnumValue_Y, EnumValue_Z, EnumValue_X}, - }, - }, - { - values: url.Values{ - "nested.nested.nested.repeated_value": {"a", "b", "c"}, - "nested.nested.nested.string_value": {"s"}, - "nested.nested.string_value": {"t"}, - "nested.string_value": {"u"}, - "nested_non_null.string_value": {"v"}, - "nested.nested.map_value[first]": {"foo"}, - "nested.nested.map_value[second]": {"bar"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - Nested: &proto2Message{ - Nested: &proto3Message{ - MapValue: map[string]string{ - "first": "foo", - "second": "bar", - }, - Nested: &proto2Message{ - RepeatedValue: []string{"a", "b", "c"}, - StringValue: proto.String("s"), - }, - StringValue: "t", - }, - StringValue: proto.String("u"), - }, - NestedNonNull: proto2Message{ - StringValue: proto.String("v"), - }, - }, - }, - { - values: url.Values{ - "uint64_value": {"1", "2", "3", "4", "5"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - Uint64Value: 1, - }, - }, - { - values: url.Values{ - "oneof_string_value": {"foobar"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - OneofValue: &proto3Message_OneofStringValue{"foobar"}, - }, - }, - { - values: url.Values{ - "oneof_bool_value": {"true"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{ - OneofValue: &proto3Message_OneofBoolValue{true}, - }, - }, - { - // Don't allow setting a oneof more than once - values: url.Values{ - "oneof_bool_value": {"true"}, - "oneof_string_value": {"foobar"}, - }, - filter: utilities.NewDoubleArray(nil), - want: &proto3Message{}, - wanterr: errors.New("field already set for oneof_value oneof"), - }, - } { - msg := proto.Clone(spec.want) - msg.Reset() - err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) - if spec.wanterr != nil { - if !reflect.DeepEqual(err, spec.wanterr) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want error %v", spec.values, spec.filter, err, spec.wanterr) - } - continue - } - - if err != nil { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) - continue - } - if got, want := msg, spec.want; !proto.Equal(got, want) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) - } - } -} - -func TestPopulateParametersWithFilters(t *testing.T) { - for _, spec := range []struct { - values url.Values - filter *utilities.DoubleArray - want proto.Message - }{ - { - values: url.Values{ - "bool_value": {"true"}, - "string_value": {"str"}, - "repeated_value": {"a", "b", "c"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"bool_value"}, {"repeated_value"}, - }), - want: &proto3Message{ - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested"}, - }), - want: &proto3Message{ - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested", "nested"}, - }), - want: &proto3Message{ - Nested: &proto2Message{ - StringValue: proto.String("str"), - }, - StringValue: "str", - }, - }, - { - values: url.Values{ - "nested.nested.bool_value": {"true"}, - "nested.nested.string_value": {"str"}, - "nested.string_value": {"str"}, - "string_value": {"str"}, - }, - filter: utilities.NewDoubleArray([][]string{ - {"nested", "nested", "string_value"}, - }), - want: &proto3Message{ - Nested: &proto2Message{ - StringValue: proto.String("str"), - Nested: &proto3Message{ - BoolValue: true, - }, - }, - StringValue: "str", - }, - }, - } { - msg := proto.Clone(spec.want) - msg.Reset() - err := runtime.PopulateQueryParameters(msg, spec.values, spec.filter) - if err != nil { - t.Errorf("runtime.PoplateQueryParameters(msg, %v, %v) failed with %v; want success", spec.values, spec.filter, err) - continue - } - if got, want := msg, spec.want; !proto.Equal(got, want) { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v = %v; want %v", spec.values, spec.filter, got, want) - } - } -} - -func TestPopulateQueryParametersWithInvalidNestedParameters(t *testing.T) { - for _, spec := range []struct { - msg proto.Message - values url.Values - filter *utilities.DoubleArray - }{ - { - msg: &proto3Message{}, - values: url.Values{ - "float_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "double_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "int64_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "int32_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "uint64_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "uint32_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "bool_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "string_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "repeated_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "enum_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "enum_value.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - { - msg: &proto3Message{}, - values: url.Values{ - "repeated_enum.nested": {"test"}, - }, - filter: utilities.NewDoubleArray(nil), - }, - } { - spec.msg.Reset() - err := runtime.PopulateQueryParameters(spec.msg, spec.values, spec.filter) - if err == nil { - t.Errorf("runtime.PopulateQueryParameters(msg, %v, %v) did not fail; want error", spec.values, spec.filter) - } - } -} - -type proto3Message struct { - Nested *proto2Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` - NestedNonNull proto2Message `protobuf:"bytes,15,opt,name=nested_non_null,json=nestedNonNull" json:"nested_non_null,omitempty"` - FloatValue float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - Int64Value int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - Int32Value int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Uint64Value uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` - Uint32Value uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` - BoolValue bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - StringValue string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - BytesValue []byte `protobuf:"bytes,25,opt,name=bytes_value,json=bytesValue" json:"bytes_value,omitempty"` - RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` - EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` - RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` - TimestampValue *timestamp.Timestamp `protobuf:"bytes,16,opt,name=timestamp_value,json=timestampValue" json:"timestamp_value,omitempty"` - FieldMaskValue *field_mask.FieldMask `protobuf:"bytes,27,opt,name=fieldmask_value,json=fieldmaskValue" json:"fieldmask_value,omitempty"` - OneofValue proto3Message_OneofValue `protobuf_oneof:"oneof_value"` - WrapperDoubleValue *wrappers.DoubleValue `protobuf:"bytes,17,opt,name=wrapper_double_value,json=wrapperDoubleValue" json:"wrapper_double_value,omitempty"` - WrapperFloatValue *wrappers.FloatValue `protobuf:"bytes,18,opt,name=wrapper_float_value,json=wrapperFloatValue" json:"wrapper_float_value,omitempty"` - WrapperInt64Value *wrappers.Int64Value `protobuf:"bytes,19,opt,name=wrapper_int64_value,json=wrapperInt64Value" json:"wrapper_int64_value,omitempty"` - WrapperInt32Value *wrappers.Int32Value `protobuf:"bytes,20,opt,name=wrapper_int32_value,json=wrapperInt32Value" json:"wrapper_int32_value,omitempty"` - WrapperUInt64Value *wrappers.UInt64Value `protobuf:"bytes,21,opt,name=wrapper_u_int64_value,json=wrapperUInt64Value" json:"wrapper_u_int64_value,omitempty"` - WrapperUInt32Value *wrappers.UInt32Value `protobuf:"bytes,22,opt,name=wrapper_u_int32_value,json=wrapperUInt32Value" json:"wrapper_u_int32_value,omitempty"` - WrapperBoolValue *wrappers.BoolValue `protobuf:"bytes,23,opt,name=wrapper_bool_value,json=wrapperBoolValue" json:"wrapper_bool_value,omitempty"` - WrapperStringValue *wrappers.StringValue `protobuf:"bytes,24,opt,name=wrapper_string_value,json=wrapperStringValue" json:"wrapper_string_value,omitempty"` - WrapperBytesValue *wrappers.BytesValue `protobuf:"bytes,26,opt,name=wrapper_bytes_value,json=wrapperBytesValue" json:"wrapper_bytes_value,omitempty"` - MapValue map[string]string `protobuf:"bytes,27,opt,name=map_value,json=mapValue" json:"map_value,omitempty"` - MapValue2 map[string]int32 `protobuf:"bytes,28,opt,name=map_value2,json=mapValue2" json:"map_value2,omitempty"` - MapValue3 map[int32]string `protobuf:"bytes,29,opt,name=map_value3,json=mapValue3" json:"map_value3,omitempty"` - MapValue4 map[string]int64 `protobuf:"bytes,30,opt,name=map_value4,json=mapValue4" json:"map_value4,omitempty"` - MapValue5 map[int64]string `protobuf:"bytes,31,opt,name=map_value5,json=mapValue5" json:"map_value5,omitempty"` - MapValue6 map[string]uint32 `protobuf:"bytes,32,opt,name=map_value6,json=mapValue6" json:"map_value6,omitempty"` - MapValue7 map[uint32]string `protobuf:"bytes,33,opt,name=map_value7,json=mapValue7" json:"map_value7,omitempty"` - MapValue8 map[string]uint64 `protobuf:"bytes,34,opt,name=map_value8,json=mapValue8" json:"map_value8,omitempty"` - MapValue9 map[uint64]string `protobuf:"bytes,35,opt,name=map_value9,json=mapValue9" json:"map_value9,omitempty"` - MapValue10 map[string]float32 `protobuf:"bytes,36,opt,name=map_value10,json=mapValue10" json:"map_value10,omitempty"` - MapValue11 map[float32]string `protobuf:"bytes,37,opt,name=map_value11,json=mapValue11" json:"map_value11,omitempty"` - MapValue12 map[string]float64 `protobuf:"bytes,38,opt,name=map_value12,json=mapValue12" json:"map_value12,omitempty"` - MapValue13 map[float64]string `protobuf:"bytes,39,opt,name=map_value13,json=mapValue13" json:"map_value13,omitempty"` - MapValue14 map[string]bool `protobuf:"bytes,40,opt,name=map_value14,json=mapValue14" json:"map_value14,omitempty"` - MapValue15 map[bool]string `protobuf:"bytes,41,opt,name=map_value15,json=mapValue15" json:"map_value15,omitempty"` -} - -func (m *proto3Message) Reset() { *m = proto3Message{} } -func (m *proto3Message) String() string { return proto.CompactTextString(m) } -func (*proto3Message) ProtoMessage() {} - -func (m *proto3Message) GetNested() *proto2Message { - if m != nil { - return m.Nested - } - return nil -} - -type proto3Message_OneofValue interface { - proto3Message_OneofValue() -} - -type proto3Message_OneofBoolValue struct { - OneofBoolValue bool `protobuf:"varint,13,opt,name=oneof_bool_value,json=oneofBoolValue,oneof"` -} -type proto3Message_OneofStringValue struct { - OneofStringValue string `protobuf:"bytes,14,opt,name=oneof_string_value,json=oneofStringValue,oneof"` -} - -func (*proto3Message_OneofBoolValue) proto3Message_OneofValue() {} -func (*proto3Message_OneofStringValue) proto3Message_OneofValue() {} - -func (m *proto3Message) GetOneofValue() proto3Message_OneofValue { - if m != nil { - return m.OneofValue - } - return nil -} - -func (m *proto3Message) GetOneofBoolValue() bool { - if x, ok := m.GetOneofValue().(*proto3Message_OneofBoolValue); ok { - return x.OneofBoolValue - } - return false -} - -func (m *proto3Message) GetOneofStringValue() string { - if x, ok := m.GetOneofValue().(*proto3Message_OneofStringValue); ok { - return x.OneofStringValue - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*proto3Message) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _proto3Message_OneofMarshaler, _proto3Message_OneofUnmarshaler, _proto3Message_OneofSizer, []interface{}{ - (*proto3Message_OneofBoolValue)(nil), - (*proto3Message_OneofStringValue)(nil), - } -} - -func _proto3Message_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*proto3Message) - // oneof_value - switch x := m.OneofValue.(type) { - case *proto3Message_OneofBoolValue: - t := uint64(0) - if x.OneofBoolValue { - t = 1 - } - b.EncodeVarint(13<<3 | proto.WireVarint) - b.EncodeVarint(t) - case *proto3Message_OneofStringValue: - b.EncodeVarint(14<<3 | proto.WireBytes) - b.EncodeStringBytes(x.OneofStringValue) - case nil: - default: - return fmt.Errorf("proto3Message.OneofValue has unexpected type %T", x) - } - return nil -} - -func _proto3Message_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*proto3Message) - switch tag { - case 14: // oneof_value.oneof_bool_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.OneofValue = &proto3Message_OneofBoolValue{x != 0} - return true, err - case 15: // oneof_value.oneof_string_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.OneofValue = &proto3Message_OneofStringValue{x} - return true, err - default: - return false, nil - } -} - -func _proto3Message_OneofSizer(msg proto.Message) (n int) { - m := msg.(*proto3Message) - // oneof_value - switch x := m.OneofValue.(type) { - case *proto3Message_OneofBoolValue: - n += proto.SizeVarint(14<<3 | proto.WireVarint) - n += 1 - case *proto3Message_OneofStringValue: - n += proto.SizeVarint(15<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.OneofStringValue))) - n += len(x.OneofStringValue) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type proto2Message struct { - Nested *proto3Message `protobuf:"bytes,1,opt,name=nested,json=nested" json:"nested,omitempty"` - FloatValue *float32 `protobuf:"fixed32,2,opt,name=float_value,json=floatValue" json:"float_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - Int64Value *int64 `protobuf:"varint,4,opt,name=int64_value,json=int64Value" json:"int64_value,omitempty"` - Int32Value *int32 `protobuf:"varint,5,opt,name=int32_value,json=int32Value" json:"int32_value,omitempty"` - Uint64Value *uint64 `protobuf:"varint,6,opt,name=uint64_value,json=uint64Value" json:"uint64_value,omitempty"` - Uint32Value *uint32 `protobuf:"varint,7,opt,name=uint32_value,json=uint32Value" json:"uint32_value,omitempty"` - BoolValue *bool `protobuf:"varint,8,opt,name=bool_value,json=boolValue" json:"bool_value,omitempty"` - StringValue *string `protobuf:"bytes,9,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - RepeatedValue []string `protobuf:"bytes,10,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` - EnumValue EnumValue `protobuf:"varint,11,opt,name=enum_value,json=enumValue,enum=runtime_test_api.EnumValue" json:"enum_value,omitempty"` - RepeatedEnum []EnumValue `protobuf:"varint,12,rep,packed,name=repeated_enum,json=repeatedEnum,enum=runtime_test_api.EnumValue" json:"repeated_enum,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *proto2Message) Reset() { *m = proto2Message{} } -func (m *proto2Message) String() string { return proto.CompactTextString(m) } -func (*proto2Message) ProtoMessage() {} - -func (m *proto2Message) GetNested() *proto3Message { - if m != nil { - return m.Nested - } - return nil -} - -func (m *proto2Message) GetFloatValue() float32 { - if m != nil && m.FloatValue != nil { - return *m.FloatValue - } - return 0 -} - -func (m *proto2Message) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *proto2Message) GetInt64Value() int64 { - if m != nil && m.Int64Value != nil { - return *m.Int64Value - } - return 0 -} - -func (m *proto2Message) GetInt32Value() int32 { - if m != nil && m.Int32Value != nil { - return *m.Int32Value - } - return 0 -} - -func (m *proto2Message) GetUint64Value() uint64 { - if m != nil && m.Uint64Value != nil { - return *m.Uint64Value - } - return 0 -} - -func (m *proto2Message) GetUint32Value() uint32 { - if m != nil && m.Uint32Value != nil { - return *m.Uint32Value - } - return 0 -} - -func (m *proto2Message) GetBoolValue() bool { - if m != nil && m.BoolValue != nil { - return *m.BoolValue - } - return false -} - -func (m *proto2Message) GetStringValue() string { - if m != nil && m.StringValue != nil { - return *m.StringValue - } - return "" -} - -func (m *proto2Message) GetRepeatedValue() []string { - if m != nil { - return m.RepeatedValue - } - return nil -} - -type EnumValue int32 - -const ( - EnumValue_X EnumValue = 0 - EnumValue_Y EnumValue = 1 - EnumValue_Z EnumValue = 2 -) - -var EnumValue_name = map[int32]string{ - 0: "EnumValue_X", - 1: "EnumValue_Y", - 2: "EnumValue_Z", -} -var EnumValue_value = map[string]int32{ - "EnumValue_X": 0, - "EnumValue_Y": 1, - "EnumValue_Z": 2, -} - -func init() { - proto.RegisterEnum("runtime_test_api.EnumValue", EnumValue_name, EnumValue_value) -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE deleted file mode 100755 index 261eeb9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/README.grpc-gateway b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/README.grpc-gateway deleted file mode 100755 index cd723e5..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/README.grpc-gateway +++ /dev/null @@ -1,22 +0,0 @@ -Google APIs -============ - -Project: Google APIs -URL: https://github.com/google/googleapis -Revision: a9fb190cdb78ed9bb2d6bb3fb5b9ef46effa5df3 -License: Apache License 2.0 - - -Imported Files ---------------- - -- google/api/annotations.proto -- google/api/http.proto - - -Generated Files ----------------- - -They are generated from the .proto files by protoc-gen-go. -- google/api/annotations.pb.go -- google/api/http.pb.go diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/annotations.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/annotations.proto deleted file mode 100755 index 85c361b..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/annotations.proto +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2015, 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.api; - -import "google/api/http.proto"; -import "google/protobuf/descriptor.proto"; - -option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; -option java_multiple_files = true; -option java_outer_classname = "AnnotationsProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - -extend google.protobuf.MethodOptions { - // See `HttpRule`. - HttpRule http = 72295728; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/http.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/http.proto deleted file mode 100755 index 5f8538a..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/http.proto +++ /dev/null @@ -1,291 +0,0 @@ -// 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.api; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; -option java_multiple_files = true; -option java_outer_classname = "HttpProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - - -// Defines the HTTP configuration for a service. It contains a list of -// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method -// to one or more HTTP REST API methods. -message Http { - // A list of HTTP configuration rules that apply to individual API methods. - // - // **NOTE:** All service configuration rules follow "last one wins" order. - repeated HttpRule rules = 1; -} - -// `HttpRule` defines the mapping of an RPC method to one or more HTTP -// REST APIs. The mapping determines what portions of the request -// message are populated from the path, query parameters, or body of -// the HTTP request. The mapping is typically specified as an -// `google.api.http` annotation, see "google/api/annotations.proto" -// for details. -// -// The mapping consists of a field specifying the path template and -// method kind. The path template can refer to fields in the request -// message, as in the example below which describes a REST GET -// operation on a resource collection of messages: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// SubMessage sub = 2; // `sub.subfield` is url-mapped -// } -// message Message { -// string text = 1; // content of the resource -// } -// -// The same http annotation can alternatively be expressed inside the -// `GRPC API Configuration` YAML file. -// -// http: -// rules: -// - selector: .Messaging.GetMessage -// get: /v1/messages/{message_id}/{sub.subfield} -// -// This definition enables an automatic, bidrectional mapping of HTTP -// JSON to RPC. Example: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` -// -// In general, not only fields but also field paths can be referenced -// from a path pattern. Fields mapped to the path pattern cannot be -// repeated and must have a primitive (non-message) type. -// -// Any fields in the request message which are not bound by the path -// pattern automatically become (optional) HTTP query -// parameters. Assume the following definition of the request message: -// -// -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// int64 revision = 2; // becomes a parameter -// SubMessage sub = 3; // `sub.subfield` becomes a parameter -// } -// -// -// This enables a HTTP JSON to RPC mapping as below: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` -// -// Note that fields which are mapped to HTTP parameters must have a -// primitive type or a repeated primitive type. Message types are not -// allowed. In the case of a repeated type, the parameter can be -// repeated in the URL, as in `...?param=A¶m=B`. -// -// For HTTP method kinds which allow a request body, the `body` field -// specifies the mapping. Consider a REST update method on the -// message resource collection: -// -// -// service Messaging { -// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "message" -// }; -// } -// } -// message UpdateMessageRequest { -// string message_id = 1; // mapped to the URL -// Message message = 2; // mapped to the body -// } -// -// -// The following HTTP JSON to RPC mapping is enabled, where the -// representation of the JSON in the request body is determined by -// protos JSON encoding: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` -// -// The special name `*` can be used in the body mapping to define that -// every field not bound by the path template should be mapped to the -// request body. This enables the following alternative definition of -// the update method: -// -// service Messaging { -// rpc UpdateMessage(Message) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "*" -// }; -// } -// } -// message Message { -// string message_id = 1; -// string text = 2; -// } -// -// -// The following HTTP JSON to RPC mapping is enabled: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` -// -// Note that when using `*` in the body mapping, it is not possible to -// have HTTP parameters, as all fields not bound by the path end in -// the body. This makes this option more rarely used in practice of -// defining REST APIs. The common usage of `*` is in custom methods -// which don't use the URL at all for transferring data. -// -// It is possible to define multiple HTTP methods for one RPC by using -// the `additional_bindings` option. Example: -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http) = { -// get: "/v1/messages/{message_id}" -// additional_bindings { -// get: "/v1/users/{user_id}/messages/{message_id}" -// } -// }; -// } -// } -// message GetMessageRequest { -// string message_id = 1; -// string user_id = 2; -// } -// -// -// This enables the following two alternative HTTP JSON to RPC -// mappings: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` -// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` -// -// # Rules for HTTP mapping -// -// The rules for mapping HTTP path, query parameters, and body fields -// to the request message are as follows: -// -// 1. The `body` field specifies either `*` or a field path, or is -// omitted. If omitted, it assumes there is no HTTP body. -// 2. Leaf fields (recursive expansion of nested messages in the -// request) can be classified into three types: -// (a) Matched in the URL template. -// (b) Covered by body (if body is `*`, everything except (a) fields; -// else everything under the body field) -// (c) All other fields. -// 3. URL query parameters found in the HTTP request are mapped to (c) fields. -// 4. Any body sent with an HTTP request can contain only (b) fields. -// -// The syntax of the path template is as follows: -// -// Template = "/" Segments [ Verb ] ; -// Segments = Segment { "/" Segment } ; -// Segment = "*" | "**" | LITERAL | Variable ; -// Variable = "{" FieldPath [ "=" Segments ] "}" ; -// FieldPath = IDENT { "." IDENT } ; -// Verb = ":" LITERAL ; -// -// The syntax `*` matches a single path segment. It follows the semantics of -// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String -// Expansion. -// -// The syntax `**` matches zero or more path segments. It follows the semantics -// of [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.3 Reserved -// Expansion. NOTE: it must be the last segment in the path except the Verb. -// -// The syntax `LITERAL` matches literal text in the URL path. -// -// The syntax `Variable` matches the entire path as specified by its template; -// this nested template must not contain further variables. If a variable -// matches a single path segment, its template may be omitted, e.g. `{var}` -// is equivalent to `{var=*}`. -// -// NOTE: the field paths in variables and in the `body` must not refer to -// repeated fields or map fields. -// -// Use CustomHttpPattern to specify any HTTP method that is not included in the -// `pattern` field, such as HEAD, or "*" to leave the HTTP method unspecified for -// a given URL path rule. The wild-card rule is useful for services that provide -// content to Web (HTML) clients. -message HttpRule { - // Selects methods to which this rule applies. - // - // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. - string selector = 1; - - // Determines the URL pattern is matched by this rules. This pattern can be - // used with any of the {get|put|post|delete|patch} methods. A custom method - // can be defined using the 'custom' field. - oneof pattern { - // Used for listing and getting information about resources. - string get = 2; - - // Used for updating a resource. - string put = 3; - - // Used for creating a resource. - string post = 4; - - // Used for deleting a resource. - string delete = 5; - - // Used for updating a resource. - string patch = 6; - - // Custom pattern is used for defining custom verbs. - CustomHttpPattern custom = 8; - } - - // The name of the request field whose value is mapped to the HTTP body, or - // `*` for mapping all fields not captured by the path pattern to the HTTP - // body. NOTE: the referred field must not be a repeated field and must be - // present at the top-level of request message type. - string body = 7; - - // Additional HTTP bindings for the selector. Nested bindings must - // not contain an `additional_bindings` field themselves (that is, - // the nesting may only be one level deep). - repeated HttpRule additional_bindings = 11; -} - -// A custom pattern is used for defining custom HTTP verb. -message CustomHttpPattern { - // The name of this custom HTTP verb. - string kind = 1; - - // The path matched by this custom verb. - string path = 2; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/code.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/code.proto deleted file mode 100755 index 8fef411..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/code.proto +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2017 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; - -option go_package = "google.golang.org/genproto/googleapis/rpc/code;code"; -option java_multiple_files = true; -option java_outer_classname = "CodeProto"; -option java_package = "com.google.rpc"; -option objc_class_prefix = "RPC"; - - -// The canonical error codes for Google APIs. -// -// -// Sometimes multiple error codes may apply. Services should return -// the most specific error code that applies. For example, prefer -// `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply. -// Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`. -enum Code { - // Not an error; returned on success - // - // HTTP Mapping: 200 OK - OK = 0; - - // The operation was cancelled, typically by the caller. - // - // HTTP Mapping: 499 Client Closed Request - CANCELLED = 1; - - // Unknown error. For example, this error may be returned when - // a `Status` value received from another address space belongs to - // an error space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - // - // HTTP Mapping: 500 Internal Server Error - UNKNOWN = 2; - - // The client specified an invalid argument. Note that this differs - // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - // - // HTTP Mapping: 400 Bad Request - INVALID_ARGUMENT = 3; - - // The deadline expired before the operation could complete. For operations - // that change the state of the system, this error may be returned - // even if the operation has completed successfully. For example, a - // successful response from a server could have been delayed long - // enough for the deadline to expire. - // - // HTTP Mapping: 504 Gateway Timeout - DEADLINE_EXCEEDED = 4; - - // Some requested entity (e.g., file or directory) was not found. - // - // Note to server developers: if a request is denied for an entire class - // of users, such as gradual feature rollout or undocumented whitelist, - // `NOT_FOUND` may be used. If a request is denied for some users within - // a class of users, such as user-based access control, `PERMISSION_DENIED` - // must be used. - // - // HTTP Mapping: 404 Not Found - NOT_FOUND = 5; - - // The entity that a client attempted to create (e.g., file or directory) - // already exists. - // - // HTTP Mapping: 409 Conflict - ALREADY_EXISTS = 6; - - // The caller does not have permission to execute the specified - // operation. `PERMISSION_DENIED` must not be used for rejections - // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` - // instead for those errors). `PERMISSION_DENIED` must not be - // used if the caller can not be identified (use `UNAUTHENTICATED` - // instead for those errors). This error code does not imply the - // request is valid or the requested entity exists or satisfies - // other pre-conditions. - // - // HTTP Mapping: 403 Forbidden - PERMISSION_DENIED = 7; - - // The request does not have valid authentication credentials for the - // operation. - // - // HTTP Mapping: 401 Unauthorized - UNAUTHENTICATED = 16; - - // Some resource has been exhausted, perhaps a per-user quota, or - // perhaps the entire file system is out of space. - // - // HTTP Mapping: 429 Too Many Requests - RESOURCE_EXHAUSTED = 8; - - // The operation was rejected because the system is not in a state - // required for the operation's execution. For example, the directory - // to be deleted is non-empty, an rmdir operation is applied to - // a non-directory, etc. - // - // Service implementors can use the following guidelines to decide - // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - // (a) Use `UNAVAILABLE` if the client can retry just the failing call. - // (b) Use `ABORTED` if the client should retry at a higher level - // (e.g., when a client-specified test-and-set fails, indicating the - // client should restart a read-modify-write sequence). - // (c) Use `FAILED_PRECONDITION` if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, `FAILED_PRECONDITION` - // should be returned since the client should not retry unless - // the files are deleted from the directory. - // - // HTTP Mapping: 400 Bad Request - FAILED_PRECONDITION = 9; - - // The operation was aborted, typically due to a concurrency issue such as - // a sequencer check failure or transaction abort. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 409 Conflict - ABORTED = 10; - - // The operation was attempted past the valid range. E.g., seeking or - // reading past end-of-file. - // - // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate `INVALID_ARGUMENT` if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // `OUT_OF_RANGE` if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between `FAILED_PRECONDITION` and - // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an `OUT_OF_RANGE` error to detect when - // they are done. - // - // HTTP Mapping: 400 Bad Request - OUT_OF_RANGE = 11; - - // The operation is not implemented or is not supported/enabled in this - // service. - // - // HTTP Mapping: 501 Not Implemented - UNIMPLEMENTED = 12; - - // Internal errors. This means that some invariants expected by the - // underlying system have been broken. This error code is reserved - // for serious errors. - // - // HTTP Mapping: 500 Internal Server Error - INTERNAL = 13; - - // The service is currently unavailable. This is most likely a - // transient condition, which can be corrected by retrying with - // a backoff. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 503 Service Unavailable - UNAVAILABLE = 14; - - // Unrecoverable data loss or corruption. - // - // HTTP Mapping: 500 Internal Server Error - DATA_LOSS = 15; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/error_details.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/error_details.proto deleted file mode 100755 index f24ae00..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/error_details.proto +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2017 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/duration.proto"; - -option go_package = "google.golang.org/genproto/googleapis/rpc/errdetails;errdetails"; -option java_multiple_files = true; -option java_outer_classname = "ErrorDetailsProto"; -option java_package = "com.google.rpc"; -option objc_class_prefix = "RPC"; - - -// Describes when the clients can retry a failed request. Clients could ignore -// the recommendation here or retry when this information is missing from error -// responses. -// -// It's always recommended that clients should use exponential backoff when -// retrying. -// -// Clients should wait until `retry_delay` amount of time has passed since -// receiving the error response before retrying. If retrying requests also -// fail, clients should use an exponential backoff scheme to gradually increase -// the delay between retries based on `retry_delay`, until either a maximum -// number of retires have been reached or a maximum retry delay cap has been -// reached. -message RetryInfo { - // Clients should wait at least this long between retrying the same request. - google.protobuf.Duration retry_delay = 1; -} - -// Describes additional debugging info. -message DebugInfo { - // The stack trace entries indicating where the error occurred. - repeated string stack_entries = 1; - - // Additional debugging information provided by the server. - string detail = 2; -} - -// Describes how a quota check failed. -// -// For example if a daily limit was exceeded for the calling project, -// a service could respond with a QuotaFailure detail containing the project -// id and the description of the quota limit that was exceeded. If the -// calling project hasn't enabled the service in the developer console, then -// a service could respond with the project id and set `service_disabled` -// to true. -// -// Also see RetryDetail and Help types for other details about handling a -// quota failure. -message QuotaFailure { - // A message type used to describe a single quota violation. For example, a - // daily quota or a custom quota that was exceeded. - message Violation { - // The subject on which the quota check failed. - // For example, "clientip:" or "project:". - string subject = 1; - - // A description of how the quota check failed. Clients can use this - // description to find more about the quota configuration in the service's - // public documentation, or find the relevant quota limit to adjust through - // developer console. - // - // For example: "Service disabled" or "Daily Limit for read operations - // exceeded". - string description = 2; - } - - // Describes all quota violations. - repeated Violation violations = 1; -} - -// Describes what preconditions have failed. -// -// For example, if an RPC failed because it required the Terms of Service to be -// acknowledged, it could list the terms of service violation in the -// PreconditionFailure message. -message PreconditionFailure { - // A message type used to describe a single precondition failure. - message Violation { - // The type of PreconditionFailure. We recommend using a service-specific - // enum type to define the supported precondition violation types. For - // example, "TOS" for "Terms of Service violation". - string type = 1; - - // The subject, relative to the type, that failed. - // For example, "google.com/cloud" relative to the "TOS" type would - // indicate which terms of service is being referenced. - string subject = 2; - - // A description of how the precondition failed. Developers can use this - // description to understand how to fix the failure. - // - // For example: "Terms of service not accepted". - string description = 3; - } - - // Describes all precondition violations. - repeated Violation violations = 1; -} - -// Describes violations in a client request. This error type focuses on the -// syntactic aspects of the request. -message BadRequest { - // A message type used to describe a single bad request field. - message FieldViolation { - // A path leading to a field in the request body. The value will be a - // sequence of dot-separated identifiers that identify a protocol buffer - // field. E.g., "field_violations.field" would identify this field. - string field = 1; - - // A description of why the request element is bad. - string description = 2; - } - - // Describes all violations in a client request. - repeated FieldViolation field_violations = 1; -} - -// Contains metadata about the request that clients can attach when filing a bug -// or providing other forms of feedback. -message RequestInfo { - // An opaque string that should only be interpreted by the service generating - // it. For example, it can be used to identify requests in the service's logs. - string request_id = 1; - - // Any data that was used to serve this request. For example, an encrypted - // stack trace that can be sent back to the service provider for debugging. - string serving_data = 2; -} - -// Describes the resource that is being accessed. -message ResourceInfo { - // A name for the type of resource being accessed, e.g. "sql table", - // "cloud storage bucket", "file", "Google calendar"; or the type URL - // of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic". - string resource_type = 1; - - // The name of the resource being accessed. For example, a shared calendar - // name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current - // error is [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. - string resource_name = 2; - - // The owner of the resource (optional). - // For example, "user:" or "project:". - string owner = 3; - - // Describes what error is encountered when accessing this resource. - // For example, updating a cloud project may require the `writer` permission - // on the developer console project. - string description = 4; -} - -// Provides links to documentation or for performing an out of band action. -// -// For example, if a quota check failed with an error indicating the calling -// project hasn't enabled the accessed service, this can contain a URL pointing -// directly to the right place in the developer console to flip the bit. -message Help { - // Describes a URL link. - message Link { - // Describes what the link offers. - string description = 1; - - // The URL of the link. - string url = 2; - } - - // URL(s) pointing to additional information on handling the current error. - repeated Link links = 1; -} - -// Provides a localized error message that is safe to return to the user -// which can be attached to an RPC error. -message LocalizedMessage { - // The locale used following the specification defined at - // http://www.rfc-editor.org/rfc/bcp/bcp47.txt. - // Examples are: "en-US", "fr-CH", "es-MX" - string locale = 1; - - // The localized error message in the above locale. - string message = 2; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/status.proto b/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/status.proto deleted file mode 100755 index 0839ee9..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/status.proto +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2017 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` that 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. -// -// - 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 is a common set of - // message types for APIs to use. - repeated google.protobuf.Any details = 3; -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel b/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel deleted file mode 100755 index 58d291c..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel +++ /dev/null @@ -1,20 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "pattern.go", - "trie.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/utilities", -) - -go_test( - name = "go_default_xtest", - size = "small", - srcs = ["trie_test.go"], - deps = [":go_default_library"], -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go b/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go deleted file mode 100755 index cf79a4d..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package utilities provides members for internal use in grpc-gateway. -package utilities diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go b/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go deleted file mode 100755 index dfe7de4..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go +++ /dev/null @@ -1,22 +0,0 @@ -package utilities - -// An OpCode is a opcode of compiled path patterns. -type OpCode int - -// These constants are the valid values of OpCode. -const ( - // OpNop does nothing - OpNop = OpCode(iota) - // OpPush pushes a component to stack - OpPush - // OpLitPush pushes a component to stack if it matches to the literal - OpLitPush - // OpPushM concatenates the remaining components and pushes it to stack - OpPushM - // OpConcatN pops N items from stack, concatenates them and pushes it back to stack - OpConcatN - // OpCapture pops an item and binds it to the variable - OpCapture - // OpEnd is the least positive invalid opcode. - OpEnd -) diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go b/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go deleted file mode 100755 index c2b7b30..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go +++ /dev/null @@ -1,177 +0,0 @@ -package utilities - -import ( - "sort" -) - -// DoubleArray is a Double Array implementation of trie on sequences of strings. -type DoubleArray struct { - // Encoding keeps an encoding from string to int - Encoding map[string]int - // Base is the base array of Double Array - Base []int - // Check is the check array of Double Array - Check []int -} - -// NewDoubleArray builds a DoubleArray from a set of sequences of strings. -func NewDoubleArray(seqs [][]string) *DoubleArray { - da := &DoubleArray{Encoding: make(map[string]int)} - if len(seqs) == 0 { - return da - } - - encoded := registerTokens(da, seqs) - sort.Sort(byLex(encoded)) - - root := node{row: -1, col: -1, left: 0, right: len(encoded)} - addSeqs(da, encoded, 0, root) - - for i := len(da.Base); i > 0; i-- { - if da.Check[i-1] != 0 { - da.Base = da.Base[:i] - da.Check = da.Check[:i] - break - } - } - return da -} - -func registerTokens(da *DoubleArray, seqs [][]string) [][]int { - var result [][]int - for _, seq := range seqs { - var encoded []int - for _, token := range seq { - if _, ok := da.Encoding[token]; !ok { - da.Encoding[token] = len(da.Encoding) - } - encoded = append(encoded, da.Encoding[token]) - } - result = append(result, encoded) - } - for i := range result { - result[i] = append(result[i], len(da.Encoding)) - } - return result -} - -type node struct { - row, col int - left, right int -} - -func (n node) value(seqs [][]int) int { - return seqs[n.row][n.col] -} - -func (n node) children(seqs [][]int) []*node { - var result []*node - lastVal := int(-1) - last := new(node) - for i := n.left; i < n.right; i++ { - if lastVal == seqs[i][n.col+1] { - continue - } - last.right = i - last = &node{ - row: i, - col: n.col + 1, - left: i, - } - result = append(result, last) - } - last.right = n.right - return result -} - -func addSeqs(da *DoubleArray, seqs [][]int, pos int, n node) { - ensureSize(da, pos) - - children := n.children(seqs) - var i int - for i = 1; ; i++ { - ok := func() bool { - for _, child := range children { - code := child.value(seqs) - j := i + code - ensureSize(da, j) - if da.Check[j] != 0 { - return false - } - } - return true - }() - if ok { - break - } - } - da.Base[pos] = i - for _, child := range children { - code := child.value(seqs) - j := i + code - da.Check[j] = pos + 1 - } - terminator := len(da.Encoding) - for _, child := range children { - code := child.value(seqs) - if code == terminator { - continue - } - j := i + code - addSeqs(da, seqs, j, *child) - } -} - -func ensureSize(da *DoubleArray, i int) { - for i >= len(da.Base) { - da.Base = append(da.Base, make([]int, len(da.Base)+1)...) - da.Check = append(da.Check, make([]int, len(da.Check)+1)...) - } -} - -type byLex [][]int - -func (l byLex) Len() int { return len(l) } -func (l byLex) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l byLex) Less(i, j int) bool { - si := l[i] - sj := l[j] - var k int - for k = 0; k < len(si) && k < len(sj); k++ { - if si[k] < sj[k] { - return true - } - if si[k] > sj[k] { - return false - } - } - if k < len(sj) { - return true - } - return false -} - -// HasCommonPrefix determines if any sequence in the DoubleArray is a prefix of the given sequence. -func (da *DoubleArray) HasCommonPrefix(seq []string) bool { - if len(da.Base) == 0 { - return false - } - - var i int - for _, t := range seq { - code, ok := da.Encoding[t] - if !ok { - break - } - j := da.Base[i] + code - if len(da.Check) <= j || da.Check[j] != i+1 { - break - } - i = j - } - j := da.Base[i] + len(da.Encoding) - if len(da.Check) <= j || da.Check[j] != i+1 { - return false - } - return true -} diff --git a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go b/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go deleted file mode 100755 index 0178aa8..0000000 --- a/examples/github.com/grpc-ecosystem/grpc-gateway/utilities/trie_test.go +++ /dev/null @@ -1,372 +0,0 @@ -package utilities_test - -import ( - "reflect" - "testing" - - "github.com/grpc-ecosystem/grpc-gateway/utilities" -) - -func TestMaxCommonPrefix(t *testing.T) { - for _, spec := range []struct { - da utilities.DoubleArray - tokens []string - want bool - }{ - { - da: utilities.DoubleArray{}, - tokens: nil, - want: false, - }, - { - da: utilities.DoubleArray{}, - tokens: []string{"foo"}, - want: false, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: nil, - want: false, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: []string{"foo"}, - want: true, - }, - { - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - }, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - }, - tokens: []string{"bar"}, - want: false, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"foo"}, - want: true, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"bar"}, - want: true, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"something-else"}, - want: false, - }, - { - // foo|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - tokens: []string{"foo", "bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo", "bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"bar"}, - want: true, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"something-else"}, - want: false, - }, - { - // foo|foo\.bar|bar - da: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 3, 1, 0, 4, 0, 0}, - Check: []int{0, 1, 1, 3, 2, 2, 5}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^bar$ - // 4: ^foo.bar - // 5: ^foo$ - // 6: ^foo.bar$ - }, - tokens: []string{"foo", "bar", "baz"}, - want: true, - }, - } { - got := spec.da.HasCommonPrefix(spec.tokens) - if got != spec.want { - t.Errorf("%#v.HasCommonPrefix(%v) = %v; want %v", spec.da, spec.tokens, got, spec.want) - } - } -} - -func TestAdd(t *testing.T) { - for _, spec := range []struct { - tokens [][]string - want utilities.DoubleArray - }{ - { - want: utilities.DoubleArray{ - Encoding: make(map[string]int), - }, - }, - { - tokens: [][]string{{"foo"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{"foo": 0}, - Base: []int{1, 1, 0}, - Check: []int{0, 1, 2}, - // 0: ^ - // 1: ^foo - // 2: ^foo$ - }, - }, - { - tokens: [][]string{{"foo"}, {"bar"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - }, - Base: []int{1, 1, 2, 0, 0}, - Check: []int{0, 1, 1, 2, 3}, - // 0: ^ - // 1: ^foo - // 2: ^bar - // 3: ^foo$ - // 4: ^bar$ - }, - }, - { - tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - }, - Base: []int{1, 1, 1, 2, 0, 0}, - Check: []int{0, 1, 2, 2, 3, 4}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^foo.bar$ - // 5: ^foo.baz$ - }, - }, - { - tokens: [][]string{{"foo", "bar"}, {"foo", "baz"}, {"qux"}}, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - "qux": 3, - }, - Base: []int{1, 1, 1, 2, 3, 0, 0, 0}, - Check: []int{0, 1, 2, 2, 1, 3, 4, 5}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^qux - // 5: ^foo.bar$ - // 6: ^foo.baz$ - // 7: ^qux$ - }, - }, - { - tokens: [][]string{ - {"foo", "bar"}, - {"foo", "baz", "bar"}, - {"qux", "foo"}, - }, - want: utilities.DoubleArray{ - Encoding: map[string]int{ - "foo": 0, - "bar": 1, - "baz": 2, - "qux": 3, - }, - Base: []int{1, 1, 1, 5, 8, 0, 3, 0, 5, 0}, - Check: []int{0, 1, 2, 2, 1, 3, 4, 7, 5, 9}, - // 0: ^ - // 1: ^foo - // 2: ^foo.bar - // 3: ^foo.baz - // 4: ^qux - // 5: ^foo.bar$ - // 6: ^foo.baz.bar - // 7: ^foo.baz.bar$ - // 8: ^qux.foo - // 9: ^qux.foo$ - }, - }, - } { - da := utilities.NewDoubleArray(spec.tokens) - if got, want := da.Encoding, spec.want.Encoding; !reflect.DeepEqual(got, want) { - t.Errorf("da.Encoding = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - if got, want := da.Base, spec.want.Base; !compareArray(got, want) { - t.Errorf("da.Base = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - if got, want := da.Check, spec.want.Check; !compareArray(got, want) { - t.Errorf("da.Check = %v; want %v; tokens = %#v", got, want, spec.tokens) - } - } -} - -func compareArray(got, want []int) bool { - var i int - for i = 0; i < len(got) && i < len(want); i++ { - if got[i] != want[i] { - return false - } - } - if i < len(want) { - return false - } - for ; i < len(got); i++ { - if got[i] != 0 { - return false - } - } - return true -} diff --git a/examples/github.com/mwitkow/go-proto-validators/.gitignore b/examples/github.com/mwitkow/go-proto-validators/.gitignore deleted file mode 100755 index 5f452f6..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/.gitignore +++ /dev/null @@ -1,89 +0,0 @@ -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -# User-specific stuff: -# .idea/workspace.xml -# .idea/tasks.xml -# .idea/dictionaries - -# Sensitive or high-churn files: -# .idea/dataSources.ids -# .idea/dataSources.xml -# .idea/sqlDataSources.xml -# .idea/dynamic.xml -# .idea/uiDesigner.xml - -# Gradle: -# .idea/gradle.xml -# .idea/libraries - -# Mongo Explorer plugin: -# .idea/mongoSettings.xml - -## File-based project format: -*.ipr -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -### Vim template -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist -*~ -### Linux template -*~ - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# Created by .ignore support plugin (hsz.mobi) diff --git a/examples/github.com/mwitkow/go-proto-validators/.travis.yml b/examples/github.com/mwitkow/go-proto-validators/.travis.yml deleted file mode 100755 index 7c43822..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -sudo: false - -go: - - 1.5 - - 1.6 - -before_install: - - ./install_protoc.sh - - export PATH=$PATH:$HOME/soft/protobuf - -install: - - go get github.com/stretchr/testify - - go get github.com/gogo/protobuf/protoc-gen-gogo - - go get github.com/golang/protobuf/protoc-gen-go - -script: - - make test diff --git a/examples/github.com/mwitkow/go-proto-validators/LICENSE.txt b/examples/github.com/mwitkow/go-proto-validators/LICENSE.txt deleted file mode 100755 index b2b0650..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/LICENSE.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/examples/github.com/mwitkow/go-proto-validators/Makefile b/examples/github.com/mwitkow/go-proto-validators/Makefile deleted file mode 100755 index ff1bc0d..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/Makefile +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright 2016 Michal Witkowski. All Rights Reserved. -# See LICENSE for licensing terms. - -export PATH := ${GOPATH}/bin:${PATH} - -install: - @echo "--- Installing govalidators to GOPATH" - go install github.com/mwitkow/go-proto-validators/protoc-gen-govalidators - -regenerate_test_gogo: - @echo "Regenerating test .proto files with gogo imports" - (protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=test \ - --gogo_out=test/gogo \ - --govalidators_out=gogoimport=true:test/gogo test/*.proto) - -regenerate_test_golang: - @echo "--- Regenerating test .proto files with golang imports" - (protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=test \ - --go_out=test/golang \ - --govalidators_out=test/golang test/*.proto) - -regenerate_example: install - @echo "--- Regenerating example directory" - (protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=. \ - --go_out=. \ - --govalidators_out=. examples/*.proto) - -test: install regenerate_test_gogo regenerate_test_golang - @echo "Running tests" - go test -v ./... - -regenerate: - @echo "--- Regenerating validator.proto" - (protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=${GOPATH}/src/github.com/gogo/protobuf/protobuf \ - --proto_path=. \ - --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:. \ - validator.proto) diff --git a/examples/github.com/mwitkow/go-proto-validators/README.md b/examples/github.com/mwitkow/go-proto-validators/README.md deleted file mode 100755 index 3df5ea8..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/README.md +++ /dev/null @@ -1,132 +0,0 @@ -# Golang ProtoBuf Validator Compiler - -[![Travis Build](https://travis-ci.org/mwitkow/go-proto-validators.svg)](https://travis-ci.org/mwitkow/go-proto-validators) -[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) - -A `protoc` plugin that generates `Validate() error` functions on Go proto `struct`s based on field options inside `.proto` -files. The validation functions are code-generated and thus don't suffer on performance from tag-based reflection on -deeply-nested messages. - -## Paint me a code picture - -Let's take the following `proto3` snippet: - -```proto -syntax = "proto3"; -package validator.examples; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message InnerMessage { - // some_integer can only be in range (1, 100). - int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}]; - // some_float can only be in range (0;1). - double some_float = 2 [(validator.field) = {float_gte: 0, float_lte: 1}]; -} - -message OuterMessage { - // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax). - string important_string = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; - // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage. - InnerMessage inner = 2 [(validator.field) = {msg_exists : true}]; -} -``` - -First, the **`required` keyword is back** for `proto3`, under the guise of `msg_exists`. The painful `if-nil` checks are taken care of! - -Second, the expected values in fields are now part of the contract `.proto` file. No more hunting down conditions in code! - -Third, the generated code is understandable and has clear understandable error messages. Take a look: - -```go -func (this *InnerMessage) Validate() error { - if !(this.SomeInteger > 0) { - return fmt.Errorf("validation error: InnerMessage.SomeInteger must be greater than '0'") - } - if !(this.SomeInteger < 100) { - return fmt.Errorf("validation error: InnerMessage.SomeInteger must be less than '100'") - } - if !(this.SomeFloat >= 0) { - return fmt.Errorf("validation error: InnerMessage.SomeFloat must be greater than or equal to '0'") - } - if !(this.SomeFloat <= 1) { - return fmt.Errorf("validation error: InnerMessage.SomeFloat must be less than or equal to '1'") - } - return nil -} - -var _regex_OuterMessage_ImportantString = regexp.MustCompile("^[a-z]{2,5}$") - -func (this *OuterMessage) Validate() error { - if !_regex_OuterMessage_ImportantString.MatchString(this.ImportantString) { - return fmt.Errorf("validation error: OuterMessage.ImportantString must conform to regex '^[a-z]{2,5}$'") - } - if nil == this.Inner { - return fmt.Errorf("validation error: OuterMessage.Inner message must exist") - } - if this.Inner != nil { - if err := validators.CallValidatorIfExists(this.Inner); err != nil { - return err - } - } - return nil -} -``` - -## Installing and using - -The `protoc` compiler expects to find plugins named `proto-gen-XYZ` on the execution `$PATH`. So first: - -```sh -export PATH=${PATH}:${GOPATH}/bin -``` - -Then, do the usual - -```sh -go get github.com/mwitkow/go-proto-validators/protoc-gen-govalidators -``` - -Your `protoc` builds probably look very simple like: - -```sh -protoc \ - --proto_path=. \ - --go_out=. \ - *.proto -``` - -That's fine, until you encounter `.proto` includes. Because `go-proto-validators` uses field options inside the `.proto` -files themselves, it's `.proto` definition (and the Google `descriptor.proto` itself) need to on the `protoc` include -path. Hence the above becomes: - -```sh -protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=${GOPATH}/src/github.com/google/protobuf/src \ - --proto_path=. \ - --go_out=. \ - --govalidators_out=. \ - *.proto -``` - -Or with gogo protobufs: - -```sh -protoc \ - --proto_path=${GOPATH}/src \ - --proto_path=${GOPATH}/src/github.com/gogo/protobuf/protobuf \ - --proto_path=. \ - --gogo_out=. \ - --govalidators_out=gogoimport=true:. \ - *.proto -``` - -Basically the magical incantation (apart from includes) is the `--govalidators_out`. That triggers the -`protoc-gen-govalidators` plugin to generate `mymessage.validator.pb.go`. That's it :) - -###License - -`go-proto-validators` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details. - - - diff --git a/examples/github.com/mwitkow/go-proto-validators/examples/.gitignore b/examples/github.com/mwitkow/go-proto-validators/examples/.gitignore deleted file mode 100755 index fefa436..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/examples/.gitignore +++ /dev/null @@ -1 +0,0 @@ -!*.pb.go \ No newline at end of file diff --git a/examples/github.com/mwitkow/go-proto-validators/examples/nested.pb.go b/examples/github.com/mwitkow/go-proto-validators/examples/nested.pb.go deleted file mode 100755 index 96bc418..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/examples/nested.pb.go +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by protoc-gen-go. -// source: examples/nested.proto -// DO NOT EDIT! - -/* -Package validator_examples is a generated protocol buffer package. - -It is generated from these files: - examples/nested.proto - -It has these top-level messages: - InnerMessage - OuterMessage -*/ -package validator_examples - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/mwitkow/go-proto-validators" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -const _ = proto.ProtoPackageIsVersion1 - -type InnerMessage struct { - // some_integer can only be in range (1, 100). - SomeInteger int32 `protobuf:"varint,1,opt,name=some_integer,json=someInteger" json:"some_integer,omitempty"` -} - -func (m *InnerMessage) Reset() { *m = InnerMessage{} } -func (m *InnerMessage) String() string { return proto.CompactTextString(m) } -func (*InnerMessage) ProtoMessage() {} -func (*InnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -type OuterMessage struct { - // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax). - ImportantString string `protobuf:"bytes,1,opt,name=important_string,json=importantString" json:"important_string,omitempty"` - // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage. - Inner *InnerMessage `protobuf:"bytes,2,opt,name=inner" json:"inner,omitempty"` -} - -func (m *OuterMessage) Reset() { *m = OuterMessage{} } -func (m *OuterMessage) String() string { return proto.CompactTextString(m) } -func (*OuterMessage) ProtoMessage() {} -func (*OuterMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *OuterMessage) GetInner() *InnerMessage { - if m != nil { - return m.Inner - } - return nil -} - -func init() { - proto.RegisterType((*InnerMessage)(nil), "validator.examples.InnerMessage") - proto.RegisterType((*OuterMessage)(nil), "validator.examples.OuterMessage") -} - -var fileDescriptor0 = []byte{ - // 245 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0xad, 0x48, 0xcc, - 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0x4b, 0x2d, 0x2e, 0x49, 0x4d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x12, 0x2a, 0x4b, 0xcc, 0xc9, 0x4c, 0x49, 0x2c, 0xc9, 0x2f, 0xd2, 0x83, 0x29, 0x90, - 0x32, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0xcf, 0x2d, 0xcf, 0x2c, - 0xc9, 0xce, 0x2f, 0xd7, 0x4f, 0xcf, 0xd7, 0x05, 0x6b, 0xd0, 0x85, 0xab, 0x2f, 0xd6, 0x47, 0x68, - 0x05, 0x4b, 0x29, 0x59, 0x73, 0xf1, 0x78, 0xe6, 0xe5, 0xa5, 0x16, 0xf9, 0xa6, 0x16, 0x17, 0x27, - 0xa6, 0xa7, 0x0a, 0x69, 0x73, 0xf1, 0x14, 0xe7, 0xe7, 0xa6, 0xc6, 0x67, 0xe6, 0x95, 0xa4, 0xa6, - 0xa7, 0x16, 0x49, 0x30, 0x2a, 0x30, 0x6a, 0xb0, 0x3a, 0x71, 0x3c, 0xba, 0x2f, 0xcf, 0x22, 0xc0, - 0x20, 0x91, 0x12, 0xc4, 0x0d, 0x92, 0xf5, 0x84, 0x48, 0x2a, 0xf5, 0x32, 0x72, 0xf1, 0xf8, 0x97, - 0x96, 0x20, 0x74, 0xdb, 0x72, 0x09, 0x64, 0xe6, 0x16, 0xe4, 0x17, 0x95, 0x24, 0xe6, 0x95, 0xc4, - 0x17, 0x97, 0x14, 0x65, 0xe6, 0xa5, 0x83, 0x4d, 0xe0, 0x74, 0x12, 0x02, 0x9a, 0xc0, 0xc7, 0xc5, - 0x13, 0x17, 0x9d, 0xa8, 0x5b, 0x15, 0x5b, 0x6d, 0xa4, 0x63, 0x5a, 0xab, 0x12, 0xc4, 0x0f, 0x57, - 0x1b, 0x0c, 0x56, 0x2a, 0x64, 0xc7, 0xc5, 0x9a, 0x09, 0x72, 0x8c, 0x04, 0x13, 0x50, 0x0f, 0xb7, - 0x91, 0x82, 0x1e, 0xa6, 0x47, 0xf5, 0x90, 0x5d, 0xeb, 0xc4, 0x06, 0x34, 0x15, 0xa8, 0x36, 0x08, - 0xa2, 0x2d, 0x89, 0x0d, 0xec, 0x27, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x08, 0x68, 0xd9, - 0xd5, 0x38, 0x01, 0x00, 0x00, -} diff --git a/examples/github.com/mwitkow/go-proto-validators/examples/nested.proto b/examples/github.com/mwitkow/go-proto-validators/examples/nested.proto deleted file mode 100755 index 5689c03..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/examples/nested.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; -package validator.examples; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message InnerMessage { - // some_integer can only be in range (1, 100). - int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}]; -} - -message OuterMessage { - // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax). - string important_string = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; - // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage. - InnerMessage inner = 2 [(validator.field) = {msg_exists : true}]; -} \ No newline at end of file diff --git a/examples/github.com/mwitkow/go-proto-validators/examples/nested.validator.pb.go b/examples/github.com/mwitkow/go-proto-validators/examples/nested.validator.pb.go deleted file mode 100755 index 3ee7b1b..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/examples/nested.validator.pb.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: examples/nested.proto -// DO NOT EDIT! - -/* -Package validator_examples is a generated protocol buffer package. - -It is generated from these files: - examples/nested.proto - -It has these top-level messages: - InnerMessage - OuterMessage -*/ -package validator_examples - -import regexp "regexp" -import fmt "fmt" -import github_com_mwitkow_go_proto_validators "github.com/mwitkow/go-proto-validators" -import proto "github.com/golang/protobuf/proto" -import math "math" -import _ "github.com/mwitkow/go-proto-validators" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -func (this *InnerMessage) Validate() error { - if !(this.SomeInteger > 0) { - return fmt.Errorf("validation error: InnerMessage.SomeInteger must be greater than '0'") - } - if !(this.SomeInteger < 100) { - return fmt.Errorf("validation error: InnerMessage.SomeInteger must be less than '100'") - } - return nil -} - -var _regex_OuterMessage_ImportantString = regexp.MustCompile("^[a-z]{2,5}$") - -func (this *OuterMessage) Validate() error { - if !_regex_OuterMessage_ImportantString.MatchString(this.ImportantString) { - return fmt.Errorf("validation error: OuterMessage.ImportantString must conform to regex " + "^[a-z]{2,5}$") - } - if nil == this.Inner { - return fmt.Errorf("validation error: OuterMessage.Inner message must exist") - } - if this.Inner != nil { - if err := github_com_mwitkow_go_proto_validators.CallValidatorIfExists(this.Inner); err != nil { - return err - } - } - return nil -} diff --git a/examples/github.com/mwitkow/go-proto-validators/helper.go b/examples/github.com/mwitkow/go-proto-validators/helper.go deleted file mode 100755 index 9a3ee9b..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/helper.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package validator - -import "strings" - -// Validator is a general interface that allows a message to be validated. -type Validator interface { - Validate() error -} - -func CallValidatorIfExists(candidate interface{}) error { - if validator, ok := candidate.(Validator); ok { - return validator.Validate() - } - return nil -} - -type fieldError struct { - fieldStack []string - nestedErr error -} - -func (f *fieldError) Error() string { - return "invalid field " + strings.Join(f.fieldStack, ".") + ": " + f.nestedErr.Error() -} - -// FieldError wraps a given Validator error providing a message call stack. -func FieldError(fieldName string, err error) error { - if fErr, ok := err.(*fieldError); ok { - fErr.fieldStack = append([]string{fieldName}, fErr.fieldStack...) - return err - } - return &fieldError{ - fieldStack: []string{fieldName}, - nestedErr: err, - } -} diff --git a/examples/github.com/mwitkow/go-proto-validators/install_protoc.sh b/examples/github.com/mwitkow/go-proto-validators/install_protoc.sh deleted file mode 100755 index d7ec41c..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/install_protoc.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash -# Copyright 2016 Michal Witkowski. All Rights Reserved. -# See LICENSE for licensing terms. -# -# This script installs protobuf compiler `protoc` into PATH. - -version=${PROTOBUF_VERSION:-"3.0.0-beta-2"} -dst_dir="${HOME}/soft/protobuf" - -# Fail on issues. -set -e - -echo "Downloading and installing protoc ${version}" - -mkdir -p ${dst_dir} - -wget https://github.com/google/protobuf/releases/download/v${version}/protoc-${version}-linux-x86_64.zip -O ${dst_dir}/dist.zip - -cd ${dst_dir} -unzip -o dist.zip - -echo "Proto in \$PROTOBUF_DIR=${PROTOBUF_DIR}" diff --git a/examples/github.com/mwitkow/go-proto-validators/plugin/plugin.go b/examples/github.com/mwitkow/go-proto-validators/plugin/plugin.go deleted file mode 100755 index 221c0a5..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/plugin/plugin.go +++ /dev/null @@ -1,591 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -/* - -The validator plugin generates a Validate method for each message. -By default, if none of the message's fields are annotated with the gogo validator annotation, it returns a nil. -In case some of the fields are annotated, the Validate function returns nil upon sucessful validation, or an error -describing why the validation failed. -The Validate method is called recursively for all submessage of the message. - -TODO(michal): ADD COMMENTS. - -Equal is enabled using the following extensions: - - - equal - - equal_all - -While VerboseEqual is enable dusing the following extensions: - - - verbose_equal - - verbose_equal_all - -The equal plugin also generates a test given it is enabled using one of the following extensions: - - - testgen - - testgen_all - -Let us look at: - - github.com/gogo/protobuf/test/example/example.proto - -Btw all the output can be seen at: - - github.com/gogo/protobuf/test/example/* - -The following message: - - - -given to the equal plugin, will generate the following code: - - - -and the following test code: - - -*/ -package plugin - -import ( - "fmt" - "os" - "reflect" - "strconv" - "strings" - - "github.com/gogo/protobuf/gogoproto" - "github.com/gogo/protobuf/proto" - descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" - "github.com/gogo/protobuf/protoc-gen-gogo/generator" - "github.com/gogo/protobuf/vanity" - "github.com/mwitkow/go-proto-validators" -) - -type plugin struct { - *generator.Generator - generator.PluginImports - regexPkg generator.Single - fmtPkg generator.Single - protoPkg generator.Single - validatorPkg generator.Single - useGogoImport bool -} - -func NewPlugin(useGogoImport bool) generator.Plugin { - return &plugin{useGogoImport: useGogoImport} -} - -func (p *plugin) Name() string { - return "validator" -} - -func (p *plugin) Init(g *generator.Generator) { - p.Generator = g -} - -func (p *plugin) Generate(file *generator.FileDescriptor) { - if !p.useGogoImport { - vanity.TurnOffGogoImport(file.FileDescriptorProto) - } - p.PluginImports = generator.NewPluginImports(p.Generator) - p.regexPkg = p.NewImport("regexp") - p.fmtPkg = p.NewImport("fmt") - p.validatorPkg = p.NewImport("github.com/mwitkow/go-proto-validators") - - for _, msg := range file.Messages() { - if msg.DescriptorProto.GetOptions().GetMapEntry() { - continue - } - p.generateRegexVars(file, msg) - if gogoproto.IsProto3(file.FileDescriptorProto) { - p.generateProto3Message(file, msg) - } else { - p.generateProto2Message(file, msg) - } - - } -} - -func getFieldValidatorIfAny(field *descriptor.FieldDescriptorProto) *validator.FieldValidator { - if field.Options != nil { - v, err := proto.GetExtension(field.Options, validator.E_Field) - if err == nil && v.(*validator.FieldValidator) != nil { - return (v.(*validator.FieldValidator)) - } - } - return nil -} - -func (p *plugin) isSupportedInt(field *descriptor.FieldDescriptorProto) bool { - switch *(field.Type) { - case descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_INT64: - return true - case descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_UINT64: - return true - case descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: - return true - } - return false -} - -func (p *plugin) isSupportedFloat(field *descriptor.FieldDescriptorProto) bool { - switch *(field.Type) { - case descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_DOUBLE: - return true - case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_FIXED64: - return true - case descriptor.FieldDescriptorProto_TYPE_SFIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED64: - return true - } - return false -} - -func (p *plugin) generateRegexVars(file *generator.FileDescriptor, message *generator.Descriptor) { - ccTypeName := generator.CamelCaseSlice(message.TypeName()) - for _, field := range message.Field { - validator := getFieldValidatorIfAny(field) - if validator != nil && validator.Regex != nil { - fieldName := p.GetFieldName(message, field) - p.P(`var `, p.regexName(ccTypeName, fieldName), ` = `, p.regexPkg.Use(), `.MustCompile(`, "`", *validator.Regex, "`", `)`) - } - } -} - -func (p *plugin) generateProto2Message(file *generator.FileDescriptor, message *generator.Descriptor) { - ccTypeName := generator.CamelCaseSlice(message.TypeName()) - - p.P(`func (this *`, ccTypeName, `) Validate() error {`) - p.In() - for _, field := range message.Field { - fieldName := p.GetFieldName(message, field) - fieldValidator := getFieldValidatorIfAny(field) - if fieldValidator == nil && !field.IsMessage() { - continue - } - if p.validatorWithMessageExists(fieldValidator) { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is a proto2 message, validator.msg_exists has no effect\n", ccTypeName, fieldName) - } - variableName := "this." + fieldName - repeated := field.IsRepeated() - nullable := gogoproto.IsNullable(field) - // For proto2 syntax, only Gogo generates non-pointer fields - nonpointer := gogoproto.ImportsGoGoProto(file.FileDescriptorProto) && !gogoproto.IsNullable(field) - if repeated { - p.generateRepeatedCountValidator(variableName, ccTypeName, fieldName, fieldValidator) - if field.IsMessage() || p.validatorWithNonRepeatedConstraint(fieldValidator) { - p.P(`for _, item := range `, variableName, `{`) - p.In() - variableName = "item" - } - } else if nullable { - p.P(`if `, variableName, ` != nil {`) - p.In() - if !field.IsBytes() { - variableName = "*(" + variableName + ")" - } - } else if nonpointer { - // can use the field directly - } else if !field.IsMessage() { - variableName = `this.Get` + fieldName + `()` - } - if !repeated && fieldValidator != nil { - if fieldValidator.RepeatedCountMin != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is not repeated, validator.min_elts has no effects\n", ccTypeName, fieldName) - } - if fieldValidator.RepeatedCountMax != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is not repeated, validator.max_elts has no effects\n", ccTypeName, fieldName) - } - } - if field.IsString() { - p.generateStringValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if p.isSupportedInt(field) { - p.generateIntValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if p.isSupportedFloat(field) { - p.generateFloatValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if field.IsBytes() { - p.generateLengthValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if field.IsMessage() { - if repeated && nullable { - variableName = "*(item)" - } - p.P(`if err := `, p.validatorPkg.Use(), `.CallValidatorIfExists(&(`, variableName, `)); err != nil {`) - p.In() - p.P(`return `, p.validatorPkg.Use(), `.FieldError("`, fieldName, `", err)`) - p.Out() - p.P(`}`) - } - if repeated { - // end the repeated loop - if field.IsMessage() || p.validatorWithNonRepeatedConstraint(fieldValidator) { - // This internal 'if' cannot be refactored as it would change semantics with respect to the corresponding prelude 'if's - p.Out() - p.P(`}`) - } - } else if nullable { - // end the if around nullable - p.Out() - p.P(`}`) - } - } - p.P(`return nil`) - p.Out() - p.P(`}`) -} - -func (p *plugin) generateProto3Message(file *generator.FileDescriptor, message *generator.Descriptor) { - ccTypeName := generator.CamelCaseSlice(message.TypeName()) - p.P(`func (this *`, ccTypeName, `) Validate() error {`) - p.In() - for _, field := range message.Field { - fieldValidator := getFieldValidatorIfAny(field) - if fieldValidator == nil && !field.IsMessage() { - continue - } - isOneOf := field.OneofIndex != nil - fieldName := p.GetOneOfFieldName(message, field) - variableName := "this." + fieldName - repeated := field.IsRepeated() - // Golang's proto3 has no concept of unset primitive fields - nullable := (gogoproto.IsNullable(field) || !gogoproto.ImportsGoGoProto(file.FileDescriptorProto)) && field.IsMessage() - if p.fieldIsProto3Map(file, message, field) { - p.P(`// Validation of proto3 map<> fields is unsupported.`) - continue - } - if isOneOf { - p.In() - oneOfName := p.GetFieldName(message, field) - oneOfType := p.OneOfTypeName(message, field) - //if x, ok := m.GetType().(*OneOfMessage3_OneInt); ok { - p.P(`if oneOfNester, ok := this.Get` + oneOfName + `().(* ` + oneOfType + `); ok {`) - variableName = "oneOfNester." + p.GetOneOfFieldName(message, field) - } - if repeated { - p.generateRepeatedCountValidator(variableName, ccTypeName, fieldName, fieldValidator) - if field.IsMessage() || p.validatorWithNonRepeatedConstraint(fieldValidator) { - p.P(`for _, item := range `, variableName, `{`) - p.In() - variableName = "item" - } - } else if fieldValidator != nil { - if fieldValidator.RepeatedCountMin != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is not repeated, validator.min_elts has no effects\n", ccTypeName, fieldName) - } - if fieldValidator.RepeatedCountMax != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is not repeated, validator.max_elts has no effects\n", ccTypeName, fieldName) - } - } - if field.IsString() { - p.generateStringValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if p.isSupportedInt(field) { - p.generateIntValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if p.isSupportedFloat(field) { - p.generateFloatValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if field.IsBytes() { - p.generateLengthValidator(variableName, ccTypeName, fieldName, fieldValidator) - } else if field.IsMessage() { - if p.validatorWithMessageExists(fieldValidator) { - if nullable && !repeated { - p.P(`if nil == `, variableName, `{`) - p.In() - p.P(`return `, p.validatorPkg.Use(), `.FieldError("`, fieldName, `",`, p.fmtPkg.Use(), `.Errorf("message must exist"))`) - p.Out() - p.P(`}`) - } else if repeated { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is repeated, validator.msg_exists has no effect\n", ccTypeName, fieldName) - } else if !nullable { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v is a nullable=false, validator.msg_exists has no effect\n", ccTypeName, fieldName) - } - } - if nullable { - p.P(`if `, variableName, ` != nil {`) - p.In() - } else { - // non-nullable fields in proto3 store actual structs, we need pointers to operate on interfaces - variableName = "&(" + variableName + ")" - } - p.P(`if err := `, p.validatorPkg.Use(), `.CallValidatorIfExists(`, variableName, `); err != nil {`) - p.In() - p.P(`return `, p.validatorPkg.Use(), `.FieldError("`, fieldName, `", err)`) - p.Out() - p.P(`}`) - if nullable { - p.Out() - p.P(`}`) - } - } - if repeated && (field.IsMessage() || p.validatorWithNonRepeatedConstraint(fieldValidator)) { - // end the repeated loop - p.Out() - p.P(`}`) - } - if isOneOf { - // end the oneof if statement - p.Out() - p.P(`}`) - } - } - p.P(`return nil`) - p.Out() - p.P(`}`) -} - -func (p *plugin) generateIntValidator(variableName string, ccTypeName string, fieldName string, fv *validator.FieldValidator) { - if fv.IntGt != nil { - p.P(`if !(`, variableName, ` > `, fv.IntGt, `) {`) - p.In() - errorStr := fmt.Sprintf(`be greater than '%d'`, fv.GetIntGt()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - if fv.IntLt != nil { - p.P(`if !(`, variableName, ` < `, fv.IntLt, `) {`) - p.In() - errorStr := fmt.Sprintf(`be less than '%d'`, fv.GetIntLt()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } -} - -func (p *plugin) generateLengthValidator(variableName string, ccTypeName string, fieldName string, fv *validator.FieldValidator) { - if fv.LengthGt != nil { - p.P(`if !( len(`, variableName, `) > `, fv.LengthGt, `) {`) - p.In() - errorStr := fmt.Sprintf(`length be greater than '%d'`, fv.GetLengthGt()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - - if fv.LengthLt != nil { - p.P(`if !( len(`, variableName, `) < `, fv.LengthLt, `) {`) - p.In() - errorStr := fmt.Sprintf(`length be less than '%d'`, fv.GetLengthLt()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - - if fv.LengthEq != nil { - p.P(`if !( len(`, variableName, `) == `, fv.LengthEq, `) {`) - p.In() - errorStr := fmt.Sprintf(`length be not equal '%d'`, fv.GetLengthEq()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - -} - -func (p *plugin) generateFloatValidator(variableName string, ccTypeName string, fieldName string, fv *validator.FieldValidator) { - upperIsStrict := true - lowerIsStrict := true - - // First check for incompatible constraints (i.e flt_lt & flt_lte both defined, etc) and determine the real limits. - if fv.FloatEpsilon != nil && fv.FloatLt == nil && fv.FloatGt == nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v has no 'float_lt' or 'float_gt' field so setting 'float_epsilon' has no effect.", ccTypeName, fieldName) - } - if fv.FloatLt != nil && fv.FloatLte != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v has both 'float_lt' and 'float_lte' constraints, only the strictest will be used.", ccTypeName, fieldName) - strictLimit := fv.GetFloatLt() - if fv.FloatEpsilon != nil { - strictLimit += fv.GetFloatEpsilon() - } - - if fv.GetFloatLte() < strictLimit { - upperIsStrict = false - } - } else if fv.FloatLte != nil { - upperIsStrict = false - } - - if fv.FloatGt != nil && fv.FloatGte != nil { - fmt.Fprintf(os.Stderr, "WARNING: field %v.%v has both 'float_gt' and 'float_gte' constraints, only the strictest will be used.", ccTypeName, fieldName) - strictLimit := fv.GetFloatGt() - if fv.FloatEpsilon != nil { - strictLimit -= fv.GetFloatEpsilon() - } - - if fv.GetFloatGte() > strictLimit { - lowerIsStrict = false - } - } else if fv.FloatGte != nil { - lowerIsStrict = false - } - - // Generate the constraint checking code. - errorStr := "" - compareStr := "" - if fv.FloatGt != nil || fv.FloatGte != nil { - compareStr = fmt.Sprint(`if !(`, variableName) - if lowerIsStrict { - errorStr = fmt.Sprintf(`be strictly greater than '%g'`, fv.GetFloatGt()) - if fv.FloatEpsilon != nil { - errorStr += fmt.Sprintf(` with a tolerance of '%g'`, fv.GetFloatEpsilon()) - compareStr += fmt.Sprint(` + `, fv.GetFloatEpsilon()) - } - compareStr += fmt.Sprint(` > `, fv.GetFloatGt(), `) {`) - } else { - errorStr = fmt.Sprintf(`be greater than or equal to '%g'`, fv.GetFloatGte()) - compareStr += fmt.Sprint(` >= `, fv.GetFloatGte(), `) {`) - } - p.P(compareStr) - p.In() - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - - if fv.FloatLt != nil || fv.FloatLte != nil { - compareStr = fmt.Sprint(`if !(`, variableName) - if upperIsStrict { - errorStr = fmt.Sprintf(`be strictly lower than '%g'`, fv.GetFloatLt()) - if fv.FloatEpsilon != nil { - errorStr += fmt.Sprintf(` with a tolerance of '%g'`, fv.GetFloatEpsilon()) - compareStr += fmt.Sprint(` - `, fv.GetFloatEpsilon()) - } - compareStr += fmt.Sprint(` < `, fv.GetFloatLt(), `) {`) - } else { - errorStr = fmt.Sprintf(`be lower than or equal to '%g'`, fv.GetFloatLte()) - compareStr += fmt.Sprint(` <= `, fv.GetFloatLte(), `) {`) - } - p.P(compareStr) - p.In() - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } -} - -func (p *plugin) generateStringValidator(variableName string, ccTypeName string, fieldName string, fv *validator.FieldValidator) { - if fv.Regex != nil { - p.P(`if !`, p.regexName(ccTypeName, fieldName), `.MatchString(`, variableName, `) {`) - p.In() - errorStr := "be a string conforming to regex " + strconv.Quote(fv.GetRegex()) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - if fv.StringNotEmpty != nil && fv.GetStringNotEmpty() { - p.P(`if `, variableName, ` == "" {`) - p.In() - errorStr := "not be an empty string" - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - p.generateLengthValidator(variableName, ccTypeName, fieldName, fv) - -} - -func (p *plugin) generateRepeatedCountValidator(variableName string, ccTypeName string, fieldName string, fv *validator.FieldValidator) { - if fv == nil { - return - } - if fv.RepeatedCountMin != nil { - compareStr := fmt.Sprint(`if len(`, variableName, `) < `, fv.GetRepeatedCountMin(), ` {`) - p.P(compareStr) - p.In() - errorStr := fmt.Sprint(`contain at least `, fv.GetRepeatedCountMin(), ` elements`) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } - if fv.RepeatedCountMax != nil { - compareStr := fmt.Sprint(`if len(`, variableName, `) > `, fv.GetRepeatedCountMax(), ` {`) - p.P(compareStr) - p.In() - errorStr := fmt.Sprint(`contain at most `, fv.GetRepeatedCountMax(), ` elements`) - p.generateErrorString(variableName, fieldName, errorStr, fv) - p.Out() - p.P(`}`) - } -} - -func (p *plugin) generateErrorString(variableName string, fieldName string, specificError string, fv *validator.FieldValidator) { - if fv.GetHumanError() == "" { - p.P(`return `, p.validatorPkg.Use(), `.FieldError("`, fieldName, `",`, p.fmtPkg.Use(), ".Errorf(`value '%v' must ", specificError, "`", `, `, variableName, `))`) - } else { - p.P(`return `, p.validatorPkg.Use(), `.FieldError("`, fieldName, `",`, p.fmtPkg.Use(), ".Errorf(`", fv.GetHumanError(), "`))") - } - -} - -func (p *plugin) fieldIsProto3Map(file *generator.FileDescriptor, message *generator.Descriptor, field *descriptor.FieldDescriptorProto) bool { - // Context from descriptor.proto - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - if field.GetType() != descriptor.FieldDescriptorProto_TYPE_MESSAGE || !field.IsRepeated() { - return false - } - typeName := field.GetTypeName() - var msg *descriptor.DescriptorProto - if strings.HasPrefix(typeName, ".") { - // Fully qualified case, look up in global map, must work or fail badly. - msg = p.ObjectNamed(field.GetTypeName()).(*generator.Descriptor).DescriptorProto - } else { - // Nested, relative case. - msg = file.GetNestedMessage(message.DescriptorProto, field.GetTypeName()) - } - return msg.GetOptions().GetMapEntry() -} - -func (p *plugin) validatorWithAnyConstraint(fv *validator.FieldValidator) bool { - if fv == nil { - return false - } - - // Need to use reflection in order to be future-proof for new types of constraints. - v := reflect.ValueOf(fv) - for i := 0; i < v.NumField(); i++ { - if v.Field(i).Interface() != nil { - return true - } - } - return false -} - -func (p *plugin) validatorWithMessageExists(fv *validator.FieldValidator) bool { - return fv != nil && fv.MsgExists != nil && *(fv.MsgExists) -} - -func (p *plugin) validatorWithNonRepeatedConstraint(fv *validator.FieldValidator) bool { - if fv == nil { - return false - } - - // Need to use reflection in order to be future-proof for new types of constraints. - v := reflect.ValueOf(*fv) - for i := 0; i < v.NumField(); i++ { - if v.Type().Field(i).Name != "RepeatedCountMin" && v.Type().Field(i).Name != "RepeatedCountMax" && v.Field(i).Pointer() != 0 { - return true - } - } - return false -} - -func (p *plugin) regexName(ccTypeName string, fieldName string) string { - return "_regex_" + ccTypeName + "_" + fieldName -} diff --git a/examples/github.com/mwitkow/go-proto-validators/protoc-gen-govalidators/main.go b/examples/github.com/mwitkow/go-proto-validators/protoc-gen-govalidators/main.go deleted file mode 100755 index 2aacf29..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/protoc-gen-govalidators/main.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package main - -import ( - "io/ioutil" - "os" - "strconv" - "strings" - - "github.com/gogo/protobuf/proto" - "github.com/gogo/protobuf/protoc-gen-gogo/generator" - validator_plugin "github.com/mwitkow/go-proto-validators/plugin" -) - -func main() { - gen := generator.New() - - data, err := ioutil.ReadAll(os.Stdin) - if err != nil { - gen.Error(err, "reading input") - } - - if err := proto.Unmarshal(data, gen.Request); err != nil { - gen.Error(err, "parsing input proto") - } - - if len(gen.Request.FileToGenerate) == 0 { - gen.Fail("no files to generate") - } - - useGogoImport := false - // Match parsing algorithm from Generator.CommandLineParameters - for _, parameter := range strings.Split(gen.Request.GetParameter(), ",") { - kvp := strings.SplitN(parameter, "=", 2) - // We only care about key-value pairs where the key is "gogoimport" - if len(kvp) != 2 || kvp[0] != "gogoimport" { - continue - } - useGogoImport, err = strconv.ParseBool(kvp[1]) - if err != nil { - gen.Error(err, "parsing gogoimport option") - } - } - - gen.CommandLineParameters(gen.Request.GetParameter()) - - gen.WrapTypes() - gen.SetPackageNames() - gen.BuildTypeNameMap() - gen.GeneratePlugin(validator_plugin.NewPlugin(useGogoImport)) - - for i := 0; i < len(gen.Response.File); i++ { - gen.Response.File[i].Name = proto.String(strings.Replace(*gen.Response.File[i].Name, ".pb.go", ".validator.pb.go", -1)) - } - - // Send back the results. - data, err = proto.Marshal(gen.Response) - if err != nil { - gen.Error(err, "failed to marshal output proto") - } - _, err = os.Stdout.Write(data) - if err != nil { - gen.Error(err, "failed to write output proto") - } -} diff --git a/examples/github.com/mwitkow/go-proto-validators/test/.gitignore b/examples/github.com/mwitkow/go-proto-validators/test/.gitignore deleted file mode 100755 index f8fcb25..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.pb.go -Makefile \ No newline at end of file diff --git a/examples/github.com/mwitkow/go-proto-validators/test/gogo/validator_test.go b/examples/github.com/mwitkow/go-proto-validators/test/gogo/validator_test.go deleted file mode 100755 index 5f34906..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/gogo/validator_test.go +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package validatortest - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -var ( - stableBytes = make([]byte, 12) -) - -func buildProto3(someString string, someInt uint32, identifier string, someValue int64, someDoubleStrict float64, - someFloatStrict float32, someDouble float64, someFloat float32, nonEmptyString string, repeatedCount uint32, someStringLength string, someBytes []byte) *ValidatorMessage3 { - goodEmbeddedProto3 := &ValidatorMessage3_Embedded{ - Identifier: identifier, - SomeValue: someValue, - } - - goodProto3 := &ValidatorMessage3{ - SomeString: someString, - SomeStringRep: []string{someString, "xyz34"}, - SomeStringNoQuotes: someString, - SomeStringUnescaped: someString, - - SomeInt: someInt, - SomeIntRep: []uint32{someInt, 12, 13, 14, 15, 16}, - SomeIntRepNonNull: []uint32{someInt, 102}, - - SomeEmbedded: nil, - SomeEmbeddedNonNullable: *goodEmbeddedProto3, - SomeEmbeddedExists: goodEmbeddedProto3, - SomeEmbeddedRep: []*ValidatorMessage3_Embedded{goodEmbeddedProto3}, - SomeEmbeddedRepNonNullable: []ValidatorMessage3_Embedded{*goodEmbeddedProto3}, - - StrictSomeDouble: someDoubleStrict, - StrictSomeDoubleRep: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeDoubleRepNonNull: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeFloat: someFloatStrict, - StrictSomeFloatRep: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatRepNonNull: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - - SomeDouble: someDouble, - SomeDoubleRep: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeDoubleRepNonNull: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeFloat: someFloat, - SomeFloatRep: []float32{someFloat, 0.5, 0.55, 0.6}, - SomeFloatRepNonNull: []float32{someFloat, 0.5, 0.55, 0.6}, - - SomeNonEmptyString: nonEmptyString, - SomeStringEqReq: someStringLength, - SomeStringLtReq: someStringLength, - SomeStringGtReq: someStringLength, - - SomeBytesLtReq: someBytes, - SomeBytesGtReq: someBytes, - SomeBytesEqReq: someBytes, - RepeatedBaseType: []int32{}, - } - - goodProto3.Repeated = make([]int32, repeatedCount, repeatedCount) - - return goodProto3 -} - -func buildProto2(someString string, someInt uint32, identifier string, someValue int64, someDoubleStrict float64, - someFloatStrict float32, someDouble float64, someFloat float32, nonEmptyString string, repeatedCount uint32, someStringLength string, someBytes []byte) *ValidatorMessage { - goodEmbeddedProto2 := &ValidatorMessage_Embedded{ - Identifier: &identifier, - SomeValue: &someValue, - } - - goodProto2 := &ValidatorMessage{ - StringReq: &someString, - StringReqNonNull: someString, - - StringOpt: nil, - StringOptNonNull: someString, - - StringUnescaped: &someString, - - IntReq: &someInt, - IntReqNonNull: someInt, - IntRep: []uint32{someInt, 12, 13, 14, 15, 16}, - IntRepNonNull: []uint32{someInt, 12, 13, 14, 15, 16}, - - EmbeddedReq: goodEmbeddedProto2, - EmbeddedNonNull: *goodEmbeddedProto2, - EmbeddedRep: []*ValidatorMessage_Embedded{goodEmbeddedProto2}, - EmbeddedRepNonNullable: []ValidatorMessage_Embedded{*goodEmbeddedProto2}, - - StrictSomeDoubleReq: &someDoubleStrict, - StrictSomeDoubleReqNonNull: someDoubleStrict, - StrictSomeDoubleRep: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeDoubleRepNonNull: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatReq: &someFloatStrict, - StrictSomeFloatReqNonNull: someFloatStrict, - StrictSomeFloatRep: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatRepNonNull: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - - SomeDoubleReq: &someDouble, - SomeDoubleReqNonNull: someDouble, - SomeDoubleRep: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeDoubleRepNonNull: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeFloatReq: &someFloat, - SomeFloatReqNonNull: someFloat, - SomeFloatRep: []float32{someFloat, 0.5, 0.55, 0.6}, - SomeFloatRepNonNull: []float32{someFloat, 0.5, 0.55, 0.6}, - - SomeNonEmptyString: &nonEmptyString, - SomeStringEqReq: &someStringLength, - SomeStringLtReq: &someStringLength, - SomeStringGtReq: &someStringLength, - - SomeBytesLtReq: someBytes, - SomeBytesGtReq: someBytes, - SomeBytesEqReq: someBytes, - RepeatedBaseType: []int32{}, - } - - goodProto2.Repeated = make([]int32, repeatedCount, repeatedCount) - - return goodProto2 -} - -func TestGoodProto3(t *testing.T) { - var err error - goodProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - err = goodProto3.Validate() - if err != nil { - t.Fatalf("unexpected fail in validator: %v", err) - } -} - -func TestGoodProto2(t *testing.T) { - var err error - goodProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - err = goodProto2.Validate() - if err != nil { - t.Fatalf("unexpected fail in validator: %v", err) - } -} - -func TestStringRegex(t *testing.T) { - tooLong1Proto3 := buildProto3("toolong", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong2Proto3 := buildProto3("-%ab", 11, "bad#", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong2Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong1Proto2 := buildProto2("toolong", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong2Proto2 := buildProto2("-%ab", 11, "bad#", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong2Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestIntLowerBounds(t *testing.T) { - lowerThan10Proto3 := buildProto3("-%ab", 9, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan10Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan10Proto2 := buildProto2("-%ab", 9, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan10Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", -1, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", -1, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestIntUpperBounds(t *testing.T) { - greaterThan100Proto3 := buildProto3("-%ab", 11, "abba", 101, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan100Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan100Proto2 := buildProto2("-%ab", 11, "abba", 101, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan100Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestDoubleStrictLowerBounds(t *testing.T) { - lowerThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.3, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.3, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.300000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan035EpsilonProto3.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } - greaterThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.300000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan035EpsilonProto2.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } -} - -func TestDoubleStrictUpperBounds(t *testing.T) { - greaterThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.70000000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.70000000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.6999999999, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan065EpsilonProto3.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } - lowerThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.6999999999, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan065EpsilonProto2.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } -} - -func TestFloatStrictLowerBounds(t *testing.T) { - lowerThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.2999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.2999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.3000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := greaterThan035EpsilonProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - greaterThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.3000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := greaterThan035EpsilonProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatStrictUpperBounds(t *testing.T) { - greaterThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.7000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.7000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.6999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := lowerThan065EpsilonProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - lowerThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.6999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := lowerThan065EpsilonProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestDoubleNonStrictLowerBounds(t *testing.T) { - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.2499999, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.2499999, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.25, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.25, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestDoubleNonStrictUpperBounds(t *testing.T) { - higherThan1Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75111111, 0.5, "x", 4, "1234567890", stableBytes) - if higherThan1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - higherThan1Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75111111, 0.5, "x", 4, "1234567890", stableBytes) - if higherThan1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatNonStrictLowerBounds(t *testing.T) { - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.2499999, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.2499999, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.25, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.25, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatNonStrictUpperBounds(t *testing.T) { - higherThan1Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75111111, "x", 4, "1234567890", stableBytes) - if higherThan1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - higherThan1Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75111111, "x", 4, "1234567890", stableBytes) - if higherThan1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestStringNonEmpty(t *testing.T) { - emptyStringProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "", 4, "1234567890", stableBytes) - if emptyStringProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - emptyStringProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "", 4, "1234567890", stableBytes) - if emptyStringProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - nonEmptyStringProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := nonEmptyStringProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - nonEmptyStringProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := nonEmptyStringProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestRepeatedEltsCount(t *testing.T) { - notEnoughEltsProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 1, "1234567890", stableBytes) - if notEnoughEltsProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - notEnoughEltsProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 1, "1234567890", stableBytes) - if notEnoughEltsProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooManyEltsProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 14, "1234567890", stableBytes) - if tooManyEltsProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooManyEltsProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 14, "1234567890", stableBytes) - if tooManyEltsProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - validEltsCountProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := validEltsCountProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - validEltsCountProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := validEltsCountProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestMsgExist(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.SomeEmbedded = nil - if err := someProto3.Validate(); err != nil { - t.Fatalf("validate shouldn't fail on missing SomeEmbedded, not annotated") - } - someProto3.SomeEmbeddedExists = nil - if err := someProto3.Validate(); err == nil { - t.Fatalf("expected fail due to lacking SomeEmbeddedExists") - } else if !strings.HasPrefix(err.Error(), "invalid field SomeEmbeddedExists:") { - t.Fatalf("expected fieldError, got '%v'", err) - } -} - -func TestNestedError3(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.SomeEmbeddedExists.SomeValue = 101 // should be less than 101 - if err := someProto3.Validate(); err == nil { - t.Fatalf("expected fail due to nested SomeEmbeddedExists.SomeValue being wrong") - } else if !strings.HasPrefix(err.Error(), "invalid field SomeEmbeddedExists.SomeValue:") { - t.Fatalf("expected fieldError, got '%v'", err) - } -} - -func TestCustomError_Proto3(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.CustomErrorInt = 30 - expectedErr := "invalid field CustomErrorInt: My Custom Error" - if err := someProto3.Validate(); err == nil { - t.Fatalf("validate should fail on missing CustomErrorInt") - } else if err.Error() != expectedErr { - t.Fatalf("validation error should be '%s' but was '%s'", expectedErr, err.Error()) - } -} - -func TestMapAlwaysPassesUntilFixedProperly(t *testing.T) { - example := &ValidatorMapMessage3{} - if err := example.Validate(); err != nil { - t.Fatalf("map validators should always pass") - } -} - -func TestOneOf_NestedMessage(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "999", // bad - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_ThreeInt{ - ThreeInt: 100, // > 20 - }, - } - err := example.Validate() - assert.Error(t, err, "nested message in oneof should fail validation on ExternalMsg") - assert.Contains(t, err.Error(), "OneMsg.Identifier", "error must err on the ExternalMsg.Identifier") -} - -func TestOneOf_NestedInt(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "abba", // good - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_ThreeInt{ - ThreeInt: 19, // > 20 - }, - } - err := example.Validate() - assert.Error(t, err, "nested message in oneof should fail validation on ThreeInt") - assert.Contains(t, err.Error(), "ThreeInt", "error must err on the ThreeInt.ThreeInt") -} - -func TestOneOf_Passes(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "abba", // good - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_FourInt{ - FourInt: 101, // > 101 - }, - } - err := example.Validate() - assert.NoError(t, err, "This message should pass all validation") -} diff --git a/examples/github.com/mwitkow/go-proto-validators/test/golang/validator_test.go b/examples/github.com/mwitkow/go-proto-validators/test/golang/validator_test.go deleted file mode 100755 index 8668359..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/golang/validator_test.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package validatortest - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -var ( - stableBytes = make([]byte, 12) -) - -func buildProto3(someString string, someInt uint32, identifier string, someValue int64, someDoubleStrict float64, - someFloatStrict float32, someDouble float64, someFloat float32, nonEmptyString string, repeatedCount uint32, - someStringLength string, someBytes []byte) *ValidatorMessage3 { - goodEmbeddedProto3 := &ValidatorMessage3_Embedded{ - Identifier: identifier, - SomeValue: someValue, - } - - goodProto3 := &ValidatorMessage3{ - SomeString: someString, - SomeStringRep: []string{someString, "xyz34"}, - SomeStringNoQuotes: someString, - SomeStringUnescaped: someString, - - SomeInt: someInt, - SomeIntRep: []uint32{someInt, 12, 13, 14, 15, 16}, - SomeIntRepNonNull: []uint32{someInt, 102}, - - SomeEmbedded: nil, - SomeEmbeddedNonNullable: goodEmbeddedProto3, - SomeEmbeddedExists: goodEmbeddedProto3, - SomeEmbeddedRep: []*ValidatorMessage3_Embedded{goodEmbeddedProto3}, - SomeEmbeddedRepNonNullable: []*ValidatorMessage3_Embedded{goodEmbeddedProto3}, - - StrictSomeDouble: someDoubleStrict, - StrictSomeDoubleRep: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeDoubleRepNonNull: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeFloat: someFloatStrict, - StrictSomeFloatRep: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatRepNonNull: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - - SomeDouble: someDouble, - SomeDoubleRep: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeDoubleRepNonNull: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeFloat: someFloat, - SomeFloatRep: []float32{someFloat, 0.5, 0.55, 0.6}, - SomeFloatRepNonNull: []float32{someFloat, 0.5, 0.55, 0.6}, - - SomeNonEmptyString: nonEmptyString, - SomeStringEqReq: someStringLength, - SomeStringLtReq: someStringLength, - SomeStringGtReq: someStringLength, - - SomeBytesLtReq: someBytes, - SomeBytesGtReq: someBytes, - SomeBytesEqReq: someBytes, - - RepeatedBaseType: []int32{}, - } - - goodProto3.Repeated = make([]int32, repeatedCount, repeatedCount) - - return goodProto3 -} - -func buildProto2(someString string, someInt uint32, identifier string, someValue int64, someDoubleStrict float64, someFloatStrict float32, someDouble float64, someFloat float32, nonEmptyString string, repeatedCount uint32, someStringLength string, someBytes []byte) *ValidatorMessage { - goodEmbeddedProto2 := &ValidatorMessage_Embedded{ - Identifier: &identifier, - SomeValue: &someValue, - } - - goodProto2 := &ValidatorMessage{ - StringReq: &someString, - StringReqNonNull: &someString, - - StringOpt: nil, - StringOptNonNull: &someString, - - StringUnescaped: &someString, - - IntReq: &someInt, - IntReqNonNull: &someInt, - IntRep: []uint32{someInt, 12, 13, 14, 15, 16}, - IntRepNonNull: []uint32{someInt, 12, 13, 14, 15, 16}, - - EmbeddedReq: goodEmbeddedProto2, - EmbeddedNonNull: goodEmbeddedProto2, - EmbeddedRep: []*ValidatorMessage_Embedded{goodEmbeddedProto2}, - EmbeddedRepNonNullable: []*ValidatorMessage_Embedded{goodEmbeddedProto2}, - - StrictSomeDoubleReq: &someDoubleStrict, - StrictSomeDoubleReqNonNull: &someDoubleStrict, - StrictSomeDoubleRep: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeDoubleRepNonNull: []float64{someDoubleStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatReq: &someFloatStrict, - StrictSomeFloatReqNonNull: &someFloatStrict, - StrictSomeFloatRep: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - StrictSomeFloatRepNonNull: []float32{someFloatStrict, 0.5, 0.55, 0.6}, - - SomeDoubleReq: &someDouble, - SomeDoubleReqNonNull: &someDouble, - SomeDoubleRep: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeDoubleRepNonNull: []float64{someDouble, 0.5, 0.55, 0.6}, - SomeFloatReq: &someFloat, - SomeFloatReqNonNull: &someFloat, - SomeFloatRep: []float32{someFloat, 0.5, 0.55, 0.6}, - SomeFloatRepNonNull: []float32{someFloat, 0.5, 0.55, 0.6}, - - SomeNonEmptyString: &nonEmptyString, - SomeStringEqReq: &someStringLength, - SomeStringLtReq: &someStringLength, - SomeStringGtReq: &someStringLength, - SomeBytesLtReq: someBytes, - SomeBytesGtReq: someBytes, - SomeBytesEqReq: someBytes, - RepeatedBaseType: []int32{}, - } - - goodProto2.Repeated = make([]int32, repeatedCount, repeatedCount) - - return goodProto2 -} - -func TestGoodProto3(t *testing.T) { - var err error - goodProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - err = goodProto3.Validate() - if err != nil { - t.Fatalf("unexpected fail in validator: %v", err) - } -} - -func TestGoodProto2(t *testing.T) { - var err error - goodProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - err = goodProto2.Validate() - if err != nil { - t.Fatalf("unexpected fail in validator: %v", err) - } -} - -func TestStringRegex(t *testing.T) { - tooLong1Proto3 := buildProto3("toolong", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong2Proto3 := buildProto3("-%ab", 11, "bad#", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong2Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong1Proto2 := buildProto2("toolong", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooLong2Proto2 := buildProto2("-%ab", 11, "bad#", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if tooLong2Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestIntLowerBounds(t *testing.T) { - lowerThan10Proto3 := buildProto3("-%ab", 9, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan10Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan10Proto2 := buildProto2("-%ab", 9, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan10Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", -1, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", -1, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestIntUpperBounds(t *testing.T) { - greaterThan100Proto3 := buildProto3("-%ab", 11, "abba", 101, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan100Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan100Proto2 := buildProto2("-%ab", 11, "abba", 101, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan100Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } -} - -func TestDoubleStrictLowerBounds(t *testing.T) { - lowerThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.3, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.3, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.300000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan035EpsilonProto3.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } - greaterThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.300000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan035EpsilonProto2.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } -} - -func TestDoubleStrictUpperBounds(t *testing.T) { - greaterThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.70000000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.70000000001, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.6999999999, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan065EpsilonProto3.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } - lowerThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.6999999999, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan065EpsilonProto2.Validate() != nil { - t.Fatalf("unexpected fail in validator") - } -} - -func TestFloatStrictLowerBounds(t *testing.T) { - lowerThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.2999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.2999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan035EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan035EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.3000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := greaterThan035EpsilonProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - greaterThan035EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.3000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := greaterThan035EpsilonProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatStrictUpperBounds(t *testing.T) { - greaterThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.7000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - greaterThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.7000001, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if greaterThan065EpsilonProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan065EpsilonProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.6999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := lowerThan065EpsilonProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - lowerThan065EpsilonProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.6999999, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := lowerThan065EpsilonProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestDoubleNonStrictLowerBounds(t *testing.T) { - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.2499999, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.2499999, 0.5, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.25, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.25, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestDoubleNonStrictUpperBounds(t *testing.T) { - higherThan1Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75111111, 0.5, "x", 4, "1234567890", stableBytes) - if higherThan1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - higherThan1Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75111111, 0.5, "x", 4, "1234567890", stableBytes) - if higherThan1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.75, 0.5, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatNonStrictLowerBounds(t *testing.T) { - lowerThan0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.2499999, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - lowerThan0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.2499999, "x", 4, "1234567890", stableBytes) - if lowerThan0Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.25, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.25, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestFloatNonStrictUpperBounds(t *testing.T) { - higherThan1Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75111111, "x", 4, "1234567890", stableBytes) - if higherThan1Proto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - higherThan1Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75111111, "x", 4, "1234567890", stableBytes) - if higherThan1Proto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - equalTo0Proto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - equalTo0Proto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.75, "x", 4, "1234567890", stableBytes) - if err := equalTo0Proto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestStringNonEmpty(t *testing.T) { - emptyStringProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "", 4, "1234567890", stableBytes) - if emptyStringProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - emptyStringProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "", 4, "1234567890", stableBytes) - if emptyStringProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - nonEmptyStringProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := nonEmptyStringProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - nonEmptyStringProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := nonEmptyStringProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestRepeatedEltsCount(t *testing.T) { - notEnoughEltsProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 1, "1234567890", stableBytes) - if notEnoughEltsProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - notEnoughEltsProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 1, "1234567890", stableBytes) - if notEnoughEltsProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooManyEltsProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 14, "1234567890", stableBytes) - if tooManyEltsProto3.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - tooManyEltsProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 14, "1234567890", stableBytes) - if tooManyEltsProto2.Validate() == nil { - t.Fatalf("expected fail in validator, but it didn't happen") - } - validEltsCountProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := validEltsCountProto3.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } - validEltsCountProto2 := buildProto2("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := validEltsCountProto2.Validate(); err != nil { - t.Fatalf("unexpected fail in validator %v", err) - } -} - -func TestMsgExist(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.SomeEmbedded = nil - if err := someProto3.Validate(); err != nil { - t.Fatalf("validate shouldn't fail on missing SomeEmbedded, not annotated") - } - someProto3.SomeEmbeddedExists = nil - if err := someProto3.Validate(); err == nil { - t.Fatalf("expected fail due to lacking SomeEmbeddedExists") - } else if !strings.HasPrefix(err.Error(), "invalid field SomeEmbeddedExists:") { - t.Fatalf("expected fieldError, got '%v'", err) - } -} - -func TestStringLengthValidator(t *testing.T) { - StringLengthErrorProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "abc456", stableBytes) - if err := StringLengthErrorProto3.Validate(); err == nil { - t.Fatalf("validate shouldn't fail on error length") - } - - StringLengthSuccess := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := StringLengthSuccess.Validate(); err != nil { - t.Fatalf("validate shouldn't fail on equal length") - } -} - -func TestBytesLengthValidator(t *testing.T) { - StringLengthErrorProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "abc456", []byte("anc")) - if err := StringLengthErrorProto3.Validate(); err == nil { - t.Fatalf("validate shouldn't fail on error length") - } - - StringLengthSuccess := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - if err := StringLengthSuccess.Validate(); err != nil { - t.Fatalf("validate shouldn't fail on equal length") - } -} - -func TestNestedError3(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.SomeEmbeddedExists.SomeValue = 101 // should be less than 101 - if err := someProto3.Validate(); err == nil { - t.Fatalf("expected fail due to nested SomeEmbeddedNonNullable.SomeValue being wrong") - } else if !strings.HasPrefix(err.Error(), "invalid field SomeEmbeddedNonNullable.SomeValue:") { - t.Fatalf("expected fieldError, got '%v'", err) - } -} - -func TestCustomError_Proto3(t *testing.T) { - someProto3 := buildProto3("-%ab", 11, "abba", 99, 0.5, 0.5, 0.5, 0.5, "x", 4, "1234567890", stableBytes) - someProto3.CustomErrorInt = 30 - expectedErr := "invalid field CustomErrorInt: My Custom Error" - if err := someProto3.Validate(); err == nil { - t.Fatalf("validate should fail on missing CustomErrorInt") - } else if err.Error() != expectedErr { - t.Fatalf("validation error should be '%s' but was '%s'", expectedErr, err.Error()) - } -} - -func TestMapAlwaysPassesUntilFixedProperly(t *testing.T) { - example := &ValidatorMapMessage3{} - if err := example.Validate(); err != nil { - t.Fatalf("map validators should always pass") - } -} - -func TestOneOf_NestedMessage(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "999", // bad - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_ThreeInt{ - ThreeInt: 100, // > 20 - }, - } - err := example.Validate() - assert.Error(t, err, "nested message in oneof should fail validation on ExternalMsg") - assert.Contains(t, err.Error(), "OneMsg.Identifier", "error must err on the ExternalMsg.Identifier") -} - -func TestOneOf_NestedInt(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "abba", // good - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_ThreeInt{ - ThreeInt: 19, // > 20 - }, - } - err := example.Validate() - assert.Error(t, err, "nested message in oneof should fail validation on ThreeInt") - assert.Contains(t, err.Error(), "ThreeInt", "error must err on the ThreeInt.ThreeInt") -} - -func TestOneOf_Passes(t *testing.T) { - example := &OneOfMessage3{ - SomeInt: 30, - Type: &OneOfMessage3_OneMsg{ - OneMsg: &ExternalMsg{ - Identifier: "abba", // good - SomeValue: 99, // good - }, - }, - Something: &OneOfMessage3_FourInt{ - FourInt: 101, // > 101 - }, - } - err := example.Validate() - assert.NoError(t, err, "This message should pass all validation") -} diff --git a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto2.proto b/examples/github.com/mwitkow/go-proto-validators/test/validator_proto2.proto deleted file mode 100755 index e0e95ae..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto2.proto +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -syntax = "proto2"; -package validatortest; - -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message ValidatorMessage { - // Embedded message test structure. - message Embedded { - optional string Identifier = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; - required int64 SomeValue = 2 [(validator.field) = {int_gt: 0, int_lt: 100}]; - } - - // String regex constraint tests. - required string StringReq = 1 [(validator.field) = {regex: "^.{2,5}$"}]; - required string StringReqNonNull = 2 [(validator.field) = {regex: "^.{2,5}$"}, (gogoproto.nullable) = false]; - optional string StringOpt = 3 [(validator.field) = {regex: "^.{2,5}$"}]; - optional string StringOptNonNull = 4 [(validator.field) = {regex: "^.{2,5}$"}, (gogoproto.nullable) = false]; - required string StringUnescaped = 5 [(validator.field) = {regex: "[\\p{L}\\p{N}]({\\p{L}\\p{N}_- ]{0,28}[\\p{L}\\p{N}])?."}]; - - // Strict integer inequality constraint tests. - required uint32 IntReq = 6 [(validator.field) = {int_gt: 10}]; - required uint32 IntReqNonNull = 7 [(validator.field) = {int_gt: 0}, (gogoproto.nullable) = false]; - repeated uint32 IntRep = 8 [(validator.field) = {int_gt: 10}]; - repeated uint32 IntRepNonNull = 9 [(validator.field) = {int_gt: 0}]; - - // Embedded message recursive constraint tests. - required Embedded embeddedReq = 10; - required Embedded embeddedNonNull = 11 [(gogoproto.nullable) = false]; - repeated Embedded embeddedRep = 12; - repeated Embedded embeddedRepNonNullable = 13 [(gogoproto.nullable) = false]; - - // Custom error tests. - optional int32 CustomErrorInt = 16 [(validator.field) = {int_gt: 10, human_error: "My Custom Error"}]; - - // Strict floating-point inequality constraint tests. - // With this epsilon value, the limits become - // SomeFloat+0.05 > 0.35 - // SomeFloat-0.05 < 0.65 - required double StrictSomeDoubleReq = 17 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - required double StrictSomeDoubleReqNonNull = 18 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}, (gogoproto.nullable) = false]; - repeated double StrictSomeDoubleRep = 19 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated double StrictSomeDoubleRepNonNull = 20 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - required float StrictSomeFloatReq = 21 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - required float StrictSomeFloatReqNonNull = 22 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}, (gogoproto.nullable) = false]; - repeated float StrictSomeFloatRep = 23 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated float StrictSomeFloatRepNonNull = 24 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - - // Non-strict floating-point inequality constraint tests. - required double SomeDoubleReq = 25 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - required double SomeDoubleReqNonNull = 26 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}, (gogoproto.nullable) = false]; - repeated double SomeDoubleRep = 27 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated double SomeDoubleRepNonNull = 28 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - required float SomeFloatReq = 29 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - required float SomeFloatReqNonNull = 30 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}, (gogoproto.nullable) = false]; - repeated float SomeFloatRep = 31 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated float SomeFloatRepNonNull = 32 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - - // String not-empty constraint tests. - required string SomeNonEmptyString = 33 [(validator.field) = {string_not_empty: true}]; - - // Repeated base-type without constraint tests. - repeated int32 RepeatedBaseType = 34; - - // Repeated element count constraint tests. - repeated int32 Repeated = 35 [(validator.field) = {repeated_count_min: 2, repeated_count_max: 5}]; - - optional string SomeStringLtReq = 36 [(validator.field) = {length_gt: 2}]; - optional string SomeStringGtReq = 37 [(validator.field) = {length_lt: 12}]; - optional string SomeStringEqReq = 38 [(validator.field) = {length_eq: 10}]; - optional bytes SomeBytesLtReq = 39 [(validator.field) = {length_gt: 5}]; - optional bytes SomeBytesGtReq = 40 [(validator.field) = {length_lt: 20}]; - optional bytes SomeBytesEqReq = 41 [(validator.field) = {length_eq: 12}]; - -} diff --git a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3.proto b/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3.proto deleted file mode 100755 index dd0b9dd..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3.proto +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -syntax = "proto3"; -package validatortest; - -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message ValidatorMessage3 { - // Embedded message test structure. - message Embedded { - string Identifier = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; - int64 SomeValue = 2 [(validator.field) = {int_gt: 0, int_lt: 100}]; - } - - // String regex constraint tests. - string SomeString = 1 [(validator.field) = {regex: "^.{2,5}$"}]; - repeated string SomeStringRep = 2 [(validator.field) = {regex: "^.{2,5}$"}]; - string SomeStringNoQuotes = 3 [(validator.field) = {regex: "^[^\"]{2,5}$"}]; - string SomeStringUnescaped = 4 [(validator.field) = {regex: "[\\p{L}\\p{N}]({\\p{L}\\p{N}_- ]{0,28}[\\p{L}\\p{N}])?."}]; - - // Strict integer inequality constraint tests. - uint32 SomeInt = 6 [(validator.field) = {int_gt: 10}]; - repeated uint32 SomeIntRep = 7 [(validator.field) = {int_gt: 10}]; - repeated uint32 SomeIntRepNonNull = 8 [(validator.field) = {int_gt: 10}]; - - // Embedded message existence and recursive constraint tests. - Embedded someEmbedded = 10; - Embedded someEmbeddedNonNullable = 11 [(gogoproto.nullable) = false]; - Embedded someEmbeddedExists = 12 [(validator.field) = {msg_exists : true}]; - repeated Embedded someEmbeddedRep = 14; - repeated Embedded someEmbeddedRepNonNullable = 15 [(gogoproto.nullable) = false]; - - // Custom error tests. - int32 CustomErrorInt = 16 [(validator.field) = {int_lt: 10, human_error: "My Custom Error"}]; - - // Strict floating-point inequality constraint tests. - // With this epsilon value, the limits become - // SomeFloat+0.05 > 0.35 - // SomeFloat-0.05 < 0.65 - double StrictSomeDouble = 17 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated double StrictSomeDoubleRep = 19 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated double StrictSomeDoubleRepNonNull = 20 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - float StrictSomeFloat = 21 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated float StrictSomeFloatRep = 22 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - repeated float StrictSomeFloatRepNonNull = 23 [(validator.field) = {float_gt: 0.35, float_lt: 0.65, float_epsilon: 0.05}]; - - // Non-strict floating-point inequality constraint tests. - double SomeDouble = 24 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated double SomeDoubleRep = 25 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated double SomeDoubleRepNonNull = 26 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - float SomeFloat = 27 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated float SomeFloatRep = 28 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - repeated float SomeFloatRepNonNull = 30 [(validator.field) = {float_gte: 0.25, float_lte: 0.75}]; - - // String not-empty constraint tests. - string SomeNonEmptyString = 31 [(validator.field) = {string_not_empty: true}]; - - // Repeated base-type without constraint tests. - repeated int32 RepeatedBaseType = 32; - - // Repeated element count constraint tests. - repeated int32 Repeated = 33 [(validator.field) = {repeated_count_min: 2, repeated_count_max: 5}]; - string SomeStringLtReq = 36 [(validator.field) = {length_gt: 2}]; - string SomeStringGtReq = 37 [(validator.field) = {length_lt: 12}]; - string SomeStringEqReq = 38 [(validator.field) = {length_eq: 10}]; - - bytes SomeBytesLtReq = 39 [(validator.field) = {length_gt: 5}]; - bytes SomeBytesGtReq = 40 [(validator.field) = {length_lt: 20}]; - bytes SomeBytesEqReq = 41 [(validator.field) = {length_eq: 12}]; -} diff --git a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_map.proto b/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_map.proto deleted file mode 100755 index f8799b1..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_map.proto +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -syntax = "proto3"; -package validatortest; - -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message ValueType { - string something = 1 ; -} - -// This needs to be able to compile. Fixes https://github.com/mwitkow/go-proto-validators/issues/1 -message ValidatorMapMessage3 { - map SomeStringMap = 1; - - message NestedType { - string something = 1 ; - } - - map SomeExtMap = 2; - map SomeNestedMap = 3; -} - - diff --git a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_oneof.proto b/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_oneof.proto deleted file mode 100755 index 2170ed5..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/test/validator_proto3_oneof.proto +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -syntax = "proto3"; -package validatortest; - -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; -import "github.com/mwitkow/go-proto-validators/validator.proto"; - -message ExternalMsg { - string Identifier = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}]; - int64 SomeValue = 2 [(validator.field) = {int_gt: 0, int_lt: 100}]; -} - -message OneOfMessage3 { - uint32 SomeInt = 1 [(validator.field) = {int_gt: 10}]; - - oneof type { - ExternalMsg one_msg = 2; - uint32 one_int = 3 [(validator.field) = {int_gt: 20}]; - uint32 two_int = 4 [(validator.field) = {int_gt: 100}]; - } - - oneof something { - uint32 three_int = 5 [(validator.field) = {int_gt: 20}]; - uint32 four_int = 6 [(validator.field) = {int_gt: 100}]; - } -} \ No newline at end of file diff --git a/examples/github.com/mwitkow/go-proto-validators/validator.pb.go b/examples/github.com/mwitkow/go-proto-validators/validator.pb.go deleted file mode 100755 index 755e6ed..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/validator.pb.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: validator.proto -// DO NOT EDIT! - -/* -Package validator is a generated protocol buffer package. - -It is generated from these files: - validator.proto - -It has these top-level messages: - FieldValidator -*/ -package validator - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -type FieldValidator struct { - // Uses a Golang RE2-syntax regex to match the field contents. - Regex *string `protobuf:"bytes,1,opt,name=regex" json:"regex,omitempty"` - // Field value of integer strictly greater than this value. - IntGt *int64 `protobuf:"varint,2,opt,name=int_gt,json=intGt" json:"int_gt,omitempty"` - // Field value of integer strictly smaller than this value. - IntLt *int64 `protobuf:"varint,3,opt,name=int_lt,json=intLt" json:"int_lt,omitempty"` - // Used for nested message types, requires that the message type exists. - MsgExists *bool `protobuf:"varint,4,opt,name=msg_exists,json=msgExists" json:"msg_exists,omitempty"` - // Human error specifies a user-customizable error that is visible to the user. - HumanError *string `protobuf:"bytes,5,opt,name=human_error,json=humanError" json:"human_error,omitempty"` - // Field value of double strictly greater than this value. - // Note that this value can only take on a valid floating point - // value. Use together with float_epsilon if you need something more specific. - FloatGt *float64 `protobuf:"fixed64,6,opt,name=float_gt,json=floatGt" json:"float_gt,omitempty"` - // Field value of double strictly smaller than this value. - // Note that this value can only take on a valid floating point - // value. Use together with float_epsilon if you need something more specific. - FloatLt *float64 `protobuf:"fixed64,7,opt,name=float_lt,json=floatLt" json:"float_lt,omitempty"` - // Field value of double describing the epsilon within which - // any comparison should be considered to be true. For example, - // when using float_gt = 0.35, using a float_epsilon of 0.05 - // would mean that any value above 0.30 is acceptable. It can be - // thought of as a {float_value_condition} +- {float_epsilon}. - // If unset, no correction for floating point inaccuracies in - // comparisons will be attempted. - FloatEpsilon *float64 `protobuf:"fixed64,8,opt,name=float_epsilon,json=floatEpsilon" json:"float_epsilon,omitempty"` - // Floating-point value compared to which the field content should be greater or equal. - FloatGte *float64 `protobuf:"fixed64,9,opt,name=float_gte,json=floatGte" json:"float_gte,omitempty"` - // Floating-point value compared to which the field content should be smaller or equal. - FloatLte *float64 `protobuf:"fixed64,10,opt,name=float_lte,json=floatLte" json:"float_lte,omitempty"` - // Used for string fields, requires the string to be not empty (i.e different from ""). - StringNotEmpty *bool `protobuf:"varint,11,opt,name=string_not_empty,json=stringNotEmpty" json:"string_not_empty,omitempty"` - // Repeated field with at least this number of elements. - RepeatedCountMin *int64 `protobuf:"varint,12,opt,name=repeated_count_min,json=repeatedCountMin" json:"repeated_count_min,omitempty"` - // Repeated field with at most this number of elements. - RepeatedCountMax *int64 `protobuf:"varint,13,opt,name=repeated_count_max,json=repeatedCountMax" json:"repeated_count_max,omitempty"` - // Field value of length greater than this value. - LengthGt *int64 `protobuf:"varint,14,opt,name=length_gt,json=lengthGt" json:"length_gt,omitempty"` - // Field value of length smaller than this value. - LengthLt *int64 `protobuf:"varint,15,opt,name=length_lt,json=lengthLt" json:"length_lt,omitempty"` - // Field value of integer strictly equal this value. - LengthEq *int64 `protobuf:"varint,16,opt,name=length_eq,json=lengthEq" json:"length_eq,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FieldValidator) Reset() { *m = FieldValidator{} } -func (m *FieldValidator) String() string { return proto.CompactTextString(m) } -func (*FieldValidator) ProtoMessage() {} -func (*FieldValidator) Descriptor() ([]byte, []int) { return fileDescriptorValidator, []int{0} } - -func (m *FieldValidator) GetRegex() string { - if m != nil && m.Regex != nil { - return *m.Regex - } - return "" -} - -func (m *FieldValidator) GetIntGt() int64 { - if m != nil && m.IntGt != nil { - return *m.IntGt - } - return 0 -} - -func (m *FieldValidator) GetIntLt() int64 { - if m != nil && m.IntLt != nil { - return *m.IntLt - } - return 0 -} - -func (m *FieldValidator) GetMsgExists() bool { - if m != nil && m.MsgExists != nil { - return *m.MsgExists - } - return false -} - -func (m *FieldValidator) GetHumanError() string { - if m != nil && m.HumanError != nil { - return *m.HumanError - } - return "" -} - -func (m *FieldValidator) GetFloatGt() float64 { - if m != nil && m.FloatGt != nil { - return *m.FloatGt - } - return 0 -} - -func (m *FieldValidator) GetFloatLt() float64 { - if m != nil && m.FloatLt != nil { - return *m.FloatLt - } - return 0 -} - -func (m *FieldValidator) GetFloatEpsilon() float64 { - if m != nil && m.FloatEpsilon != nil { - return *m.FloatEpsilon - } - return 0 -} - -func (m *FieldValidator) GetFloatGte() float64 { - if m != nil && m.FloatGte != nil { - return *m.FloatGte - } - return 0 -} - -func (m *FieldValidator) GetFloatLte() float64 { - if m != nil && m.FloatLte != nil { - return *m.FloatLte - } - return 0 -} - -func (m *FieldValidator) GetStringNotEmpty() bool { - if m != nil && m.StringNotEmpty != nil { - return *m.StringNotEmpty - } - return false -} - -func (m *FieldValidator) GetRepeatedCountMin() int64 { - if m != nil && m.RepeatedCountMin != nil { - return *m.RepeatedCountMin - } - return 0 -} - -func (m *FieldValidator) GetRepeatedCountMax() int64 { - if m != nil && m.RepeatedCountMax != nil { - return *m.RepeatedCountMax - } - return 0 -} - -func (m *FieldValidator) GetLengthGt() int64 { - if m != nil && m.LengthGt != nil { - return *m.LengthGt - } - return 0 -} - -func (m *FieldValidator) GetLengthLt() int64 { - if m != nil && m.LengthLt != nil { - return *m.LengthLt - } - return 0 -} - -func (m *FieldValidator) GetLengthEq() int64 { - if m != nil && m.LengthEq != nil { - return *m.LengthEq - } - return 0 -} - -var E_Field = &proto.ExtensionDesc{ - ExtendedType: (*google_protobuf.FieldOptions)(nil), - ExtensionType: (*FieldValidator)(nil), - Field: 65020, - Name: "validator.field", - Tag: "bytes,65020,opt,name=field", - Filename: "validator.proto", -} - -func init() { - proto.RegisterType((*FieldValidator)(nil), "validator.FieldValidator") - proto.RegisterExtension(E_Field) -} - -func init() { proto.RegisterFile("validator.proto", fileDescriptorValidator) } - -var fileDescriptorValidator = []byte{ - // 392 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x6c, 0x92, 0xcf, 0x8f, 0x93, 0x40, - 0x14, 0xc7, 0x83, 0xbb, 0xec, 0xc2, 0xb0, 0xdb, 0x6d, 0x26, 0x9a, 0x4c, 0x35, 0x8d, 0x44, 0x2f, - 0x1c, 0x0c, 0x4d, 0x3c, 0x7a, 0xd4, 0x60, 0x2f, 0xf8, 0x23, 0x1c, 0x3c, 0x78, 0x21, 0x58, 0x5e, - 0xa7, 0x93, 0x0c, 0x33, 0x74, 0xe6, 0xd5, 0xe0, 0x3f, 0xe0, 0x3f, 0xad, 0x07, 0xc3, 0x20, 0x85, - 0x4d, 0x7a, 0x9c, 0xcf, 0xe7, 0xcb, 0x1b, 0x78, 0x7c, 0xc9, 0xc3, 0xcf, 0x4a, 0x8a, 0xba, 0x42, - 0x6d, 0xd2, 0xd6, 0x68, 0xd4, 0x34, 0x3c, 0x83, 0xe7, 0x31, 0xd7, 0x9a, 0x4b, 0xd8, 0x38, 0xf1, - 0xe3, 0xb4, 0xdf, 0xd4, 0x60, 0x77, 0x46, 0xb4, 0xe7, 0xf0, 0xab, 0xdf, 0xd7, 0x64, 0xf1, 0x51, - 0x80, 0xac, 0xbf, 0x8d, 0x0f, 0xd1, 0xa7, 0xc4, 0x37, 0xc0, 0xa1, 0x63, 0x5e, 0xec, 0x25, 0x61, - 0x31, 0x1c, 0xe8, 0x33, 0x72, 0x23, 0x14, 0x96, 0x1c, 0xd9, 0x93, 0xd8, 0x4b, 0xae, 0x0a, 0x5f, - 0x28, 0xdc, 0xe2, 0x88, 0x25, 0xb2, 0xab, 0x33, 0xce, 0x91, 0xae, 0x09, 0x69, 0x2c, 0x2f, 0xa1, - 0x13, 0x16, 0x2d, 0xbb, 0x8e, 0xbd, 0x24, 0x28, 0xc2, 0xc6, 0xf2, 0xcc, 0x01, 0xfa, 0x92, 0x44, - 0x87, 0x53, 0x53, 0xa9, 0x12, 0x8c, 0xd1, 0x86, 0xf9, 0xee, 0x22, 0xe2, 0x50, 0xd6, 0x13, 0xba, - 0x22, 0xc1, 0x5e, 0xea, 0xca, 0xdd, 0x77, 0x13, 0x7b, 0x89, 0x57, 0xdc, 0xba, 0xf3, 0x16, 0x27, - 0x25, 0x91, 0xdd, 0xce, 0x54, 0x8e, 0xf4, 0x35, 0xb9, 0x1f, 0x14, 0xb4, 0x56, 0x48, 0xad, 0x58, - 0xe0, 0xfc, 0x9d, 0x83, 0xd9, 0xc0, 0xe8, 0x0b, 0x12, 0x8e, 0xa3, 0x81, 0x85, 0x2e, 0x10, 0xfc, - 0x9f, 0x0d, 0x93, 0x94, 0x08, 0x8c, 0xcc, 0x64, 0x8e, 0x40, 0x13, 0xb2, 0xb4, 0x68, 0x84, 0xe2, - 0xa5, 0xd2, 0x58, 0x42, 0xd3, 0xe2, 0x2f, 0x16, 0xb9, 0x4f, 0x5b, 0x0c, 0xfc, 0xb3, 0xc6, 0xac, - 0xa7, 0xf4, 0x0d, 0xa1, 0x06, 0x5a, 0xa8, 0x10, 0xea, 0x72, 0xa7, 0x4f, 0x0a, 0xcb, 0x46, 0x28, - 0x76, 0xe7, 0x36, 0xb4, 0x1c, 0xcd, 0x87, 0x5e, 0x7c, 0x12, 0xea, 0x52, 0xba, 0xea, 0xd8, 0xfd, - 0xa5, 0x74, 0xd5, 0xf5, 0xaf, 0x28, 0x41, 0x71, 0x3c, 0xf4, 0xbb, 0x59, 0xb8, 0x50, 0x30, 0x80, - 0x2d, 0xce, 0xa4, 0x44, 0xf6, 0x30, 0x97, 0xf9, 0x5c, 0xc2, 0x91, 0x2d, 0xe7, 0x32, 0x3b, 0xbe, - 0xfb, 0x4a, 0xfc, 0x7d, 0xdf, 0x03, 0xba, 0x4e, 0x87, 0xd2, 0xa4, 0x63, 0x69, 0x52, 0xd7, 0x8f, - 0x2f, 0x2d, 0x0a, 0xad, 0x2c, 0xfb, 0xfb, 0xa7, 0xff, 0xd1, 0xd1, 0xdb, 0x55, 0x3a, 0xf5, 0xee, - 0x71, 0x81, 0x8a, 0x61, 0xd0, 0xfb, 0xe8, 0xfb, 0xd4, 0xc4, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, - 0xec, 0x56, 0x30, 0x88, 0xa6, 0x02, 0x00, 0x00, -} diff --git a/examples/github.com/mwitkow/go-proto-validators/validator.proto b/examples/github.com/mwitkow/go-proto-validators/validator.proto deleted file mode 100755 index 88f19a6..0000000 --- a/examples/github.com/mwitkow/go-proto-validators/validator.proto +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -// Protocol Buffers extensions for defining auto-generateable validators for messages. - -// TODO(mwitkow): Add example. - - -syntax = "proto2"; -package validator; - -import "google/protobuf/descriptor.proto"; - -option go_package = "validator"; - -// TODO(mwitkow): Email protobuf-global-extension-registry@google.com to get an extension ID. - -extend google.protobuf.FieldOptions { - optional FieldValidator field = 65020; -} - -message FieldValidator { - // Uses a Golang RE2-syntax regex to match the field contents. - optional string regex = 1; - // Field value of integer strictly greater than this value. - optional int64 int_gt = 2; - // Field value of integer strictly smaller than this value. - optional int64 int_lt = 3; - // Used for nested message types, requires that the message type exists. - optional bool msg_exists = 4; - // Human error specifies a user-customizable error that is visible to the user. - optional string human_error = 5; - // Field value of double strictly greater than this value. - // Note that this value can only take on a valid floating point - // value. Use together with float_epsilon if you need something more specific. - optional double float_gt = 6; - // Field value of double strictly smaller than this value. - // Note that this value can only take on a valid floating point - // value. Use together with float_epsilon if you need something more specific. - optional double float_lt = 7; - // Field value of double describing the epsilon within which - // any comparison should be considered to be true. For example, - // when using float_gt = 0.35, using a float_epsilon of 0.05 - // would mean that any value above 0.30 is acceptable. It can be - // thought of as a {float_value_condition} +- {float_epsilon}. - // If unset, no correction for floating point inaccuracies in - // comparisons will be attempted. - optional double float_epsilon = 8; - // Floating-point value compared to which the field content should be greater or equal. - optional double float_gte = 9; - // Floating-point value compared to which the field content should be smaller or equal. - optional double float_lte = 10; - // Used for string fields, requires the string to be not empty (i.e different from ""). - optional bool string_not_empty = 11; - // Repeated field with at least this number of elements. - optional int64 repeated_count_min = 12; - // Repeated field with at most this number of elements. - optional int64 repeated_count_max = 13; - // Field value of length greater than this value. - optional int64 length_gt = 14; - // Field value of length smaller than this value. - optional int64 length_lt = 15; - // Field value of integer strictly equal this value. - optional int64 length_eq = 16; - -} diff --git a/examples/golang.org/x/net/context/context.go b/examples/golang.org/x/net/context/context.go deleted file mode 100755 index a3c021d..0000000 --- a/examples/golang.org/x/net/context/context.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// As of Go 1.7 this package is available in the standard library under the -// name context. https://golang.org/pkg/context. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context // import "golang.org/x/net/context" - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} diff --git a/examples/golang.org/x/net/context/context_test.go b/examples/golang.org/x/net/context/context_test.go deleted file mode 100755 index 6284413..0000000 --- a/examples/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(3*timeUnit)) - testDeadline(c, 2*timeUnit, t) -} - -func TestTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 1*timeUnit) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o = otherContext{c} - c, _ = WithTimeout(o, 3*timeUnit) - testDeadline(c, 2*timeUnit, t) -} - -func TestCanceledTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 2*timeUnit) - o := otherContext{c} - c, cancel := WithTimeout(o, 4*timeUnit) - cancel() - time.Sleep(1 * timeUnit) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 16, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TODO(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + 100*time.Millisecond): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/examples/golang.org/x/net/context/ctxhttp/ctxhttp.go b/examples/golang.org/x/net/context/ctxhttp/ctxhttp.go deleted file mode 100755 index 606cf1f..0000000 --- a/examples/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -// Package ctxhttp provides helper functions for performing context-aware HTTP requests. -package ctxhttp // import "golang.org/x/net/context/ctxhttp" - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -// Do sends an HTTP request with the provided http.Client and returns -// an HTTP response. -// -// If the client is nil, http.DefaultClient is used. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req.WithContext(ctx)) - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - if err != nil { - select { - case <-ctx.Done(): - err = ctx.Err() - default: - } - } - return resp, err -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go b/examples/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go deleted file mode 100755 index 72411b1..0000000 --- a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !plan9,go1.7 - -package ctxhttp - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" - - "context" -) - -func TestGo17Context(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "ok") - })) - defer ts.Close() - ctx := context.Background() - resp, err := Get(ctx, http.DefaultClient, ts.URL) - if resp == nil || err != nil { - t.Fatalf("error received from client: %v %v", err, resp) - } - resp.Body.Close() -} diff --git a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go b/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go deleted file mode 100755 index 926870c..0000000 --- a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package ctxhttp // import "golang.org/x/net/context/ctxhttp" - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -func nop() {} - -var ( - testHookContextDoneBeforeHeaders = nop - testHookDoReturned = nop - testHookDidBodyClose = nop -) - -// Do sends an HTTP request with the provided http.Client and returns an HTTP response. -// If the client is nil, http.DefaultClient is used. -// If the context is canceled or times out, ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - - // TODO(djd): Respect any existing value of req.Cancel. - cancel := make(chan struct{}) - req.Cancel = cancel - - type responseAndError struct { - resp *http.Response - err error - } - result := make(chan responseAndError, 1) - - // Make local copies of test hooks closed over by goroutines below. - // Prevents data races in tests. - testHookDoReturned := testHookDoReturned - testHookDidBodyClose := testHookDidBodyClose - - go func() { - resp, err := client.Do(req) - testHookDoReturned() - result <- responseAndError{resp, err} - }() - - var resp *http.Response - - select { - case <-ctx.Done(): - testHookContextDoneBeforeHeaders() - close(cancel) - // Clean up after the goroutine calling client.Do: - go func() { - if r := <-result; r.resp != nil { - testHookDidBodyClose() - r.resp.Body.Close() - } - }() - return nil, ctx.Err() - case r := <-result: - var err error - resp, err = r.resp, r.err - if err != nil { - return resp, err - } - } - - c := make(chan struct{}) - go func() { - select { - case <-ctx.Done(): - close(cancel) - case <-c: - // The response's Body is closed. - } - }() - resp.Body = ¬ifyingReader{resp.Body, c} - - return resp, nil -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} - -// notifyingReader is an io.ReadCloser that closes the notify channel after -// Close is called or a Read fails on the underlying ReadCloser. -type notifyingReader struct { - io.ReadCloser - notify chan<- struct{} -} - -func (r *notifyingReader) Read(p []byte) (int, error) { - n, err := r.ReadCloser.Read(p) - if err != nil && r.notify != nil { - close(r.notify) - r.notify = nil - } - return n, err -} - -func (r *notifyingReader) Close() error { - err := r.ReadCloser.Close() - if r.notify != nil { - close(r.notify) - r.notify = nil - } - return err -} diff --git a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go b/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go deleted file mode 100755 index 9159cf0..0000000 --- a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !plan9,!go1.7 - -package ctxhttp - -import ( - "net" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" - - "golang.org/x/net/context" -) - -// golang.org/issue/14065 -func TestClosesResponseBodyOnCancel(t *testing.T) { - defer func() { testHookContextDoneBeforeHeaders = nop }() - defer func() { testHookDoReturned = nop }() - defer func() { testHookDidBodyClose = nop }() - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - defer ts.Close() - - ctx, cancel := context.WithCancel(context.Background()) - - // closed when Do enters select case <-ctx.Done() - enteredDonePath := make(chan struct{}) - - testHookContextDoneBeforeHeaders = func() { - close(enteredDonePath) - } - - testHookDoReturned = func() { - // We now have the result (the Flush'd headers) at least, - // so we can cancel the request. - cancel() - - // But block the client.Do goroutine from sending - // until Do enters into the <-ctx.Done() path, since - // otherwise if both channels are readable, select - // picks a random one. - <-enteredDonePath - } - - sawBodyClose := make(chan struct{}) - testHookDidBodyClose = func() { close(sawBodyClose) } - - tr := &http.Transport{} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - req, _ := http.NewRequest("GET", ts.URL, nil) - _, doErr := Do(ctx, c, req) - - select { - case <-sawBodyClose: - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for body to close") - } - - if doErr != ctx.Err() { - t.Errorf("Do error = %v; want %v", doErr, ctx.Err()) - } -} - -type noteCloseConn struct { - net.Conn - onceClose sync.Once - closefn func() -} - -func (c *noteCloseConn) Close() error { - c.onceClose.Do(c.closefn) - return c.Conn.Close() -} diff --git a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_test.go b/examples/golang.org/x/net/context/ctxhttp/ctxhttp_test.go deleted file mode 100755 index 1e41551..0000000 --- a/examples/golang.org/x/net/context/ctxhttp/ctxhttp_test.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !plan9 - -package ctxhttp - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "golang.org/x/net/context" -) - -const ( - requestDuration = 100 * time.Millisecond - requestBody = "ok" -) - -func okHandler(w http.ResponseWriter, r *http.Request) { - time.Sleep(requestDuration) - io.WriteString(w, requestBody) -} - -func TestNoTimeout(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(okHandler)) - defer ts.Close() - - ctx := context.Background() - res, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(slurp) != requestBody { - t.Errorf("body = %q; want %q", slurp, requestBody) - } -} - -func TestCancelBeforeHeaders(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - - blockServer := make(chan struct{}) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - cancel() - <-blockServer - io.WriteString(w, requestBody) - })) - defer ts.Close() - defer close(blockServer) - - res, err := Get(ctx, nil, ts.URL) - if err == nil { - res.Body.Close() - t.Fatal("Get returned unexpected nil error") - } - if err != context.Canceled { - t.Errorf("err = %v; want %v", err, context.Canceled) - } -} - -func TestCancelAfterHangingRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.(http.Flusher).Flush() - <-w.(http.CloseNotifier).CloseNotify() - })) - defer ts.Close() - - ctx, cancel := context.WithCancel(context.Background()) - resp, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatalf("unexpected error in Get: %v", err) - } - - // Cancel befer reading the body. - // Reading Request.Body should fail, since the request was - // canceled before anything was written. - cancel() - - done := make(chan struct{}) - - go func() { - b, err := ioutil.ReadAll(resp.Body) - if len(b) != 0 || err == nil { - t.Errorf(`Read got (%q, %v); want ("", error)`, b, err) - } - close(done) - }() - - select { - case <-time.After(1 * time.Second): - t.Errorf("Test timed out") - case <-done: - } -} diff --git a/examples/golang.org/x/net/context/go17.go b/examples/golang.org/x/net/context/go17.go deleted file mode 100755 index d20f52b..0000000 --- a/examples/golang.org/x/net/context/go17.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package context - -import ( - "context" // standard library's context, as of Go 1.7 - "time" -) - -var ( - todo = context.TODO() - background = context.Background() -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = context.Canceled - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = context.DeadlineExceeded - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - ctx, f := context.WithCancel(parent) - return ctx, CancelFunc(f) -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - ctx, f := context.WithDeadline(parent, deadline) - return ctx, CancelFunc(f) -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return context.WithValue(parent, key, val) -} diff --git a/examples/golang.org/x/net/context/go19.go b/examples/golang.org/x/net/context/go19.go deleted file mode 100755 index d88bd1d..0000000 --- a/examples/golang.org/x/net/context/go19.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package context - -import "context" // standard library's context, as of Go 1.7 - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context = context.Context - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc = context.CancelFunc diff --git a/examples/golang.org/x/net/context/pre_go17.go b/examples/golang.org/x/net/context/pre_go17.go deleted file mode 100755 index 0f35592..0000000 --- a/examples/golang.org/x/net/context/pre_go17.go +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, c) - return c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - *cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/examples/golang.org/x/net/context/pre_go19.go b/examples/golang.org/x/net/context/pre_go19.go deleted file mode 100755 index b105f80..0000000 --- a/examples/golang.org/x/net/context/pre_go19.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.9 - -package context - -import "time" - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out chan<- Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() diff --git a/examples/golang.org/x/net/context/withtimeout_test.go b/examples/golang.org/x/net/context/withtimeout_test.go deleted file mode 100755 index e6f5669..0000000 --- a/examples/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -// This example passes a context with a timeout to tell a blocking function that -// it should abandon its work after the timeout elapses. -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - - select { - case <-time.After(1 * time.Second): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - - // Output: - // context deadline exceeded -} diff --git a/examples/golang.org/x/net/http2/.gitignore b/examples/golang.org/x/net/http2/.gitignore deleted file mode 100755 index 190f122..0000000 --- a/examples/golang.org/x/net/http2/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*~ -h2i/h2i diff --git a/examples/golang.org/x/net/http2/Dockerfile b/examples/golang.org/x/net/http2/Dockerfile deleted file mode 100644 index 53fc525..0000000 --- a/examples/golang.org/x/net/http2/Dockerfile +++ /dev/null @@ -1,51 +0,0 @@ -# -# This Dockerfile builds a recent curl with HTTP/2 client support, using -# a recent nghttp2 build. -# -# See the Makefile for how to tag it. If Docker and that image is found, the -# Go tests use this curl binary for integration tests. -# - -FROM ubuntu:trusty - -RUN apt-get update && \ - apt-get upgrade -y && \ - apt-get install -y git-core build-essential wget - -RUN apt-get install -y --no-install-recommends \ - autotools-dev libtool pkg-config zlib1g-dev \ - libcunit1-dev libssl-dev libxml2-dev libevent-dev \ - automake autoconf - -# The list of packages nghttp2 recommends for h2load: -RUN apt-get install -y --no-install-recommends make binutils \ - autoconf automake autotools-dev \ - libtool pkg-config zlib1g-dev libcunit1-dev libssl-dev libxml2-dev \ - libev-dev libevent-dev libjansson-dev libjemalloc-dev \ - cython python3.4-dev python-setuptools - -# Note: setting NGHTTP2_VER before the git clone, so an old git clone isn't cached: -ENV NGHTTP2_VER 895da9a -RUN cd /root && git clone https://github.com/tatsuhiro-t/nghttp2.git - -WORKDIR /root/nghttp2 -RUN git reset --hard $NGHTTP2_VER -RUN autoreconf -i -RUN automake -RUN autoconf -RUN ./configure -RUN make -RUN make install - -WORKDIR /root -RUN wget http://curl.haxx.se/download/curl-7.45.0.tar.gz -RUN tar -zxvf curl-7.45.0.tar.gz -WORKDIR /root/curl-7.45.0 -RUN ./configure --with-ssl --with-nghttp2=/usr/local -RUN make -RUN make install -RUN ldconfig - -CMD ["-h"] -ENTRYPOINT ["/usr/local/bin/curl"] - diff --git a/examples/golang.org/x/net/http2/Makefile b/examples/golang.org/x/net/http2/Makefile deleted file mode 100644 index 55fd826..0000000 --- a/examples/golang.org/x/net/http2/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -curlimage: - docker build -t gohttp2/curl . - diff --git a/examples/golang.org/x/net/http2/README b/examples/golang.org/x/net/http2/README deleted file mode 100644 index 360d5aa..0000000 --- a/examples/golang.org/x/net/http2/README +++ /dev/null @@ -1,20 +0,0 @@ -This is a work-in-progress HTTP/2 implementation for Go. - -It will eventually live in the Go standard library and won't require -any changes to your code to use. It will just be automatic. - -Status: - -* The server support is pretty good. A few things are missing - but are being worked on. -* The client work has just started but shares a lot of code - is coming along much quicker. - -Docs are at https://godoc.org/golang.org/x/net/http2 - -Demo test server at https://http2.golang.org/ - -Help & bug reports welcome! - -Contributing: https://golang.org/doc/contribute.html -Bugs: https://golang.org/issue/new?title=x/net/http2:+ diff --git a/examples/golang.org/x/net/http2/ciphers.go b/examples/golang.org/x/net/http2/ciphers.go deleted file mode 100644 index c9a0cf3..0000000 --- a/examples/golang.org/x/net/http2/ciphers.go +++ /dev/null @@ -1,641 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -// A list of the possible cipher suite ids. Taken from -// https://www.iana.org/assignments/tls-parameters/tls-parameters.txt - -const ( - cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000 - cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001 - cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002 - cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003 - cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004 - cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 - cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006 - cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007 - cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008 - cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009 - cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A - cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B - cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C - cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D - cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E - cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F - cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010 - cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011 - cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012 - cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013 - cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014 - cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015 - cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016 - cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017 - cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018 - cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019 - cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A - cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B - // Reserved uint16 = 0x001C-1D - cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F - cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020 - cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021 - cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022 - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023 - cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024 - cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025 - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026 - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027 - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028 - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029 - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B - cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C - cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D - cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E - cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030 - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031 - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032 - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033 - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034 - cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036 - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037 - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038 - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039 - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A - cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C - cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040 - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041 - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042 - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043 - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044 - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045 - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046 - // Reserved uint16 = 0x0047-4F - // Reserved uint16 = 0x0050-58 - // Reserved uint16 = 0x0059-5C - // Unassigned uint16 = 0x005D-5F - // Reserved uint16 = 0x0060-66 - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067 - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068 - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069 - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D - // Unassigned uint16 = 0x006E-83 - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084 - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085 - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086 - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087 - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088 - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089 - cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A - cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B - cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C - cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D - cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E - cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090 - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091 - cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092 - cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093 - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094 - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095 - cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096 - cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097 - cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098 - cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099 - cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A - cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B - cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C - cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D - cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E - cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F - cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0 - cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1 - cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2 - cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3 - cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4 - cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5 - cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6 - cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7 - cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8 - cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9 - cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA - cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB - cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC - cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD - cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE - cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF - cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0 - cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1 - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2 - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3 - cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4 - cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5 - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6 - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7 - cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8 - cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9 - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0 - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1 - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2 - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3 - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4 - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5 - // Unassigned uint16 = 0x00C6-FE - cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF - // Unassigned uint16 = 0x01-55,* - cipher_TLS_FALLBACK_SCSV uint16 = 0x5600 - // Unassigned uint16 = 0x5601 - 0xC000 - cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001 - cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002 - cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003 - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004 - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005 - cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006 - cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007 - cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008 - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009 - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A - cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B - cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C - cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F - cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010 - cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011 - cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012 - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013 - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014 - cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015 - cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016 - cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017 - cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018 - cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019 - cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A - cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B - cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C - cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D - cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E - cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F - cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020 - cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021 - cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022 - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023 - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024 - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025 - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026 - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027 - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028 - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029 - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C - cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D - cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E - cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F - cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030 - cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031 - cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032 - cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033 - cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034 - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035 - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036 - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037 - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038 - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039 - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B - cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C - cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D - cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E - cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F - cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040 - cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041 - cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042 - cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043 - cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044 - cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045 - cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046 - cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047 - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048 - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049 - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B - cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C - cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D - cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E - cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F - cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050 - cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051 - cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052 - cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053 - cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054 - cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055 - cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056 - cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057 - cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058 - cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059 - cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A - cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F - cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060 - cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061 - cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062 - cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063 - cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064 - cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065 - cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066 - cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067 - cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068 - cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069 - cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A - cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B - cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C - cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D - cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E - cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F - cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070 - cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071 - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072 - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073 - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074 - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075 - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076 - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077 - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078 - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079 - cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A - cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080 - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081 - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082 - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083 - cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084 - cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085 - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086 - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087 - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088 - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089 - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D - cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E - cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F - cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090 - cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091 - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092 - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093 - cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094 - cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095 - cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096 - cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097 - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098 - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099 - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B - cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C - cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D - cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E - cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F - cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0 - cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1 - cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2 - cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3 - cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4 - cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5 - cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6 - cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7 - cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8 - cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9 - cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA - cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF - // Unassigned uint16 = 0xC0B0-FF - // Unassigned uint16 = 0xC1-CB,* - // Unassigned uint16 = 0xCC00-A7 - cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8 - cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9 - cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA - cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB - cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC - cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD - cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE -) - -// isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. -// References: -// https://tools.ietf.org/html/rfc7540#appendix-A -// Reject cipher suites from Appendix A. -// "This list includes those cipher suites that do not -// offer an ephemeral key exchange and those that are -// based on the TLS null, stream or block cipher type" -func isBadCipher(cipher uint16) bool { - switch cipher { - case cipher_TLS_NULL_WITH_NULL_NULL, - cipher_TLS_RSA_WITH_NULL_MD5, - cipher_TLS_RSA_WITH_NULL_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_RSA_WITH_RC4_128_MD5, - cipher_TLS_RSA_WITH_RC4_128_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_RSA_WITH_IDEA_CBC_SHA, - cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_RSA_WITH_DES_CBC_SHA, - cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_DH_anon_WITH_RC4_128_MD5, - cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_anon_WITH_DES_CBC_SHA, - cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_SHA, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_RC4_128_SHA, - cipher_TLS_KRB5_WITH_IDEA_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_MD5, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5, - cipher_TLS_KRB5_WITH_RC4_128_MD5, - cipher_TLS_KRB5_WITH_IDEA_CBC_MD5, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_PSK_WITH_NULL_SHA, - cipher_TLS_DHE_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_NULL_SHA256, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_PSK_WITH_RC4_128_SHA, - cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_RC4_128_SHA, - cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_anon_WITH_SEED_CBC_SHA, - cipher_TLS_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_PSK_WITH_NULL_SHA256, - cipher_TLS_PSK_WITH_NULL_SHA384, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_NULL_SHA256, - cipher_TLS_DHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_NULL_SHA256, - cipher_TLS_RSA_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV, - cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_NULL_SHA, - cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_NULL_SHA, - cipher_TLS_ECDH_anon_WITH_RC4_128_SHA, - cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_AES_128_CCM, - cipher_TLS_RSA_WITH_AES_256_CCM, - cipher_TLS_RSA_WITH_AES_128_CCM_8, - cipher_TLS_RSA_WITH_AES_256_CCM_8, - cipher_TLS_PSK_WITH_AES_128_CCM, - cipher_TLS_PSK_WITH_AES_256_CCM, - cipher_TLS_PSK_WITH_AES_128_CCM_8, - cipher_TLS_PSK_WITH_AES_256_CCM_8: - return true - default: - return false - } -} diff --git a/examples/golang.org/x/net/http2/ciphers_test.go b/examples/golang.org/x/net/http2/ciphers_test.go deleted file mode 100644 index 764bbc8..0000000 --- a/examples/golang.org/x/net/http2/ciphers_test.go +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "testing" - -func TestIsBadCipherBad(t *testing.T) { - for _, c := range badCiphers { - if !isBadCipher(c) { - t.Errorf("Wrong result for isBadCipher(%d), want true", c) - } - } -} - -// verify we don't give false positives on ciphers not on blacklist -func TestIsBadCipherGood(t *testing.T) { - goodCiphers := map[uint16]string{ - cipher_TLS_DHE_RSA_WITH_AES_256_CCM: "cipher_TLS_DHE_RSA_WITH_AES_256_CCM", - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM: "cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM", - cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: "cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", - } - for c, name := range goodCiphers { - if isBadCipher(c) { - t.Errorf("Wrong result for isBadCipher(%d) %s, want false", c, name) - } - } -} - -// copied from https://http2.github.io/http2-spec/#BadCipherSuites, -var badCiphers = []uint16{ - cipher_TLS_NULL_WITH_NULL_NULL, - cipher_TLS_RSA_WITH_NULL_MD5, - cipher_TLS_RSA_WITH_NULL_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_RSA_WITH_RC4_128_MD5, - cipher_TLS_RSA_WITH_RC4_128_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_RSA_WITH_IDEA_CBC_SHA, - cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_RSA_WITH_DES_CBC_SHA, - cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_DH_anon_WITH_RC4_128_MD5, - cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_anon_WITH_DES_CBC_SHA, - cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_SHA, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_RC4_128_SHA, - cipher_TLS_KRB5_WITH_IDEA_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_MD5, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5, - cipher_TLS_KRB5_WITH_RC4_128_MD5, - cipher_TLS_KRB5_WITH_IDEA_CBC_MD5, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_PSK_WITH_NULL_SHA, - cipher_TLS_DHE_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_NULL_SHA256, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_PSK_WITH_RC4_128_SHA, - cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_RC4_128_SHA, - cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_anon_WITH_SEED_CBC_SHA, - cipher_TLS_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_PSK_WITH_NULL_SHA256, - cipher_TLS_PSK_WITH_NULL_SHA384, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_NULL_SHA256, - cipher_TLS_DHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_NULL_SHA256, - cipher_TLS_RSA_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV, - cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_NULL_SHA, - cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_NULL_SHA, - cipher_TLS_ECDH_anon_WITH_RC4_128_SHA, - cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_AES_128_CCM, - cipher_TLS_RSA_WITH_AES_256_CCM, - cipher_TLS_RSA_WITH_AES_128_CCM_8, - cipher_TLS_RSA_WITH_AES_256_CCM_8, - cipher_TLS_PSK_WITH_AES_128_CCM, - cipher_TLS_PSK_WITH_AES_256_CCM, - cipher_TLS_PSK_WITH_AES_128_CCM_8, - cipher_TLS_PSK_WITH_AES_256_CCM_8, -} diff --git a/examples/golang.org/x/net/http2/client_conn_pool.go b/examples/golang.org/x/net/http2/client_conn_pool.go deleted file mode 100644 index f4d9b5e..0000000 --- a/examples/golang.org/x/net/http2/client_conn_pool.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Transport code's client connection pooling. - -package http2 - -import ( - "crypto/tls" - "net/http" - "sync" -) - -// ClientConnPool manages a pool of HTTP/2 client connections. -type ClientConnPool interface { - GetClientConn(req *http.Request, addr string) (*ClientConn, error) - MarkDead(*ClientConn) -} - -// clientConnPoolIdleCloser is the interface implemented by ClientConnPool -// implementations which can close their idle connections. -type clientConnPoolIdleCloser interface { - ClientConnPool - closeIdleConnections() -} - -var ( - _ clientConnPoolIdleCloser = (*clientConnPool)(nil) - _ clientConnPoolIdleCloser = noDialClientConnPool{} -) - -// TODO: use singleflight for dialing and addConnCalls? -type clientConnPool struct { - t *Transport - - mu sync.Mutex // TODO: maybe switch to RWMutex - // TODO: add support for sharing conns based on cert names - // (e.g. share conn for googleapis.com and appspot.com) - conns map[string][]*ClientConn // key is host:port - dialing map[string]*dialCall // currently in-flight dials - keys map[*ClientConn][]string - addConnCalls map[string]*addConnCall // in-flight addConnIfNeede calls -} - -func (p *clientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { - return p.getClientConn(req, addr, dialOnMiss) -} - -const ( - dialOnMiss = true - noDialOnMiss = false -) - -// shouldTraceGetConn reports whether getClientConn should call any -// ClientTrace.GetConn hook associated with the http.Request. -// -// This complexity is needed to avoid double calls of the GetConn hook -// during the back-and-forth between net/http and x/net/http2 (when the -// net/http.Transport is upgraded to also speak http2), as well as support -// the case where x/net/http2 is being used directly. -func (p *clientConnPool) shouldTraceGetConn(st clientConnIdleState) bool { - // If our Transport wasn't made via ConfigureTransport, always - // trace the GetConn hook if provided, because that means the - // http2 package is being used directly and it's the one - // dialing, as opposed to net/http. - if _, ok := p.t.ConnPool.(noDialClientConnPool); !ok { - return true - } - // Otherwise, only use the GetConn hook if this connection has - // been used previously for other requests. For fresh - // connections, the net/http package does the dialing. - return !st.freshConn -} - -func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMiss bool) (*ClientConn, error) { - if isConnectionCloseRequest(req) && dialOnMiss { - // It gets its own connection. - traceGetConn(req, addr) - const singleUse = true - cc, err := p.t.dialClientConn(addr, singleUse) - if err != nil { - return nil, err - } - return cc, nil - } - p.mu.Lock() - for _, cc := range p.conns[addr] { - if st := cc.idleState(); st.canTakeNewRequest { - if p.shouldTraceGetConn(st) { - traceGetConn(req, addr) - } - p.mu.Unlock() - return cc, nil - } - } - if !dialOnMiss { - p.mu.Unlock() - return nil, ErrNoCachedConn - } - traceGetConn(req, addr) - call := p.getStartDialLocked(addr) - p.mu.Unlock() - <-call.done - return call.res, call.err -} - -// dialCall is an in-flight Transport dial call to a host. -type dialCall struct { - p *clientConnPool - done chan struct{} // closed when done - res *ClientConn // valid after done is closed - err error // valid after done is closed -} - -// requires p.mu is held. -func (p *clientConnPool) getStartDialLocked(addr string) *dialCall { - if call, ok := p.dialing[addr]; ok { - // A dial is already in-flight. Don't start another. - return call - } - call := &dialCall{p: p, done: make(chan struct{})} - if p.dialing == nil { - p.dialing = make(map[string]*dialCall) - } - p.dialing[addr] = call - go call.dial(addr) - return call -} - -// run in its own goroutine. -func (c *dialCall) dial(addr string) { - const singleUse = false // shared conn - c.res, c.err = c.p.t.dialClientConn(addr, singleUse) - close(c.done) - - c.p.mu.Lock() - delete(c.p.dialing, addr) - if c.err == nil { - c.p.addConnLocked(addr, c.res) - } - c.p.mu.Unlock() -} - -// addConnIfNeeded makes a NewClientConn out of c if a connection for key doesn't -// already exist. It coalesces concurrent calls with the same key. -// This is used by the http1 Transport code when it creates a new connection. Because -// the http1 Transport doesn't de-dup TCP dials to outbound hosts (because it doesn't know -// the protocol), it can get into a situation where it has multiple TLS connections. -// This code decides which ones live or die. -// The return value used is whether c was used. -// c is never closed. -func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) (used bool, err error) { - p.mu.Lock() - for _, cc := range p.conns[key] { - if cc.CanTakeNewRequest() { - p.mu.Unlock() - return false, nil - } - } - call, dup := p.addConnCalls[key] - if !dup { - if p.addConnCalls == nil { - p.addConnCalls = make(map[string]*addConnCall) - } - call = &addConnCall{ - p: p, - done: make(chan struct{}), - } - p.addConnCalls[key] = call - go call.run(t, key, c) - } - p.mu.Unlock() - - <-call.done - if call.err != nil { - return false, call.err - } - return !dup, nil -} - -type addConnCall struct { - p *clientConnPool - done chan struct{} // closed when done - err error -} - -func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) { - cc, err := t.NewClientConn(tc) - - p := c.p - p.mu.Lock() - if err != nil { - c.err = err - } else { - p.addConnLocked(key, cc) - } - delete(p.addConnCalls, key) - p.mu.Unlock() - close(c.done) -} - -func (p *clientConnPool) addConn(key string, cc *ClientConn) { - p.mu.Lock() - p.addConnLocked(key, cc) - p.mu.Unlock() -} - -// p.mu must be held -func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) { - for _, v := range p.conns[key] { - if v == cc { - return - } - } - if p.conns == nil { - p.conns = make(map[string][]*ClientConn) - } - if p.keys == nil { - p.keys = make(map[*ClientConn][]string) - } - p.conns[key] = append(p.conns[key], cc) - p.keys[cc] = append(p.keys[cc], key) -} - -func (p *clientConnPool) MarkDead(cc *ClientConn) { - p.mu.Lock() - defer p.mu.Unlock() - for _, key := range p.keys[cc] { - vv, ok := p.conns[key] - if !ok { - continue - } - newList := filterOutClientConn(vv, cc) - if len(newList) > 0 { - p.conns[key] = newList - } else { - delete(p.conns, key) - } - } - delete(p.keys, cc) -} - -func (p *clientConnPool) closeIdleConnections() { - p.mu.Lock() - defer p.mu.Unlock() - // TODO: don't close a cc if it was just added to the pool - // milliseconds ago and has never been used. There's currently - // a small race window with the HTTP/1 Transport's integration - // where it can add an idle conn just before using it, and - // somebody else can concurrently call CloseIdleConns and - // break some caller's RoundTrip. - for _, vv := range p.conns { - for _, cc := range vv { - cc.closeIfIdle() - } - } -} - -func filterOutClientConn(in []*ClientConn, exclude *ClientConn) []*ClientConn { - out := in[:0] - for _, v := range in { - if v != exclude { - out = append(out, v) - } - } - // If we filtered it out, zero out the last item to prevent - // the GC from seeing it. - if len(in) != len(out) { - in[len(in)-1] = nil - } - return out -} - -// noDialClientConnPool is an implementation of http2.ClientConnPool -// which never dials. We let the HTTP/1.1 client dial and use its TLS -// connection instead. -type noDialClientConnPool struct{ *clientConnPool } - -func (p noDialClientConnPool) GetClientConn(req *http.Request, addr string) (*ClientConn, error) { - return p.getClientConn(req, addr, noDialOnMiss) -} diff --git a/examples/golang.org/x/net/http2/configure_transport.go b/examples/golang.org/x/net/http2/configure_transport.go deleted file mode 100644 index 6356b32..0000000 --- a/examples/golang.org/x/net/http2/configure_transport.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.6 - -package http2 - -import ( - "crypto/tls" - "fmt" - "net/http" -) - -func configureTransport(t1 *http.Transport) (*Transport, error) { - connPool := new(clientConnPool) - t2 := &Transport{ - ConnPool: noDialClientConnPool{connPool}, - t1: t1, - } - connPool.t = t2 - if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil { - return nil, err - } - if t1.TLSClientConfig == nil { - t1.TLSClientConfig = new(tls.Config) - } - if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") { - t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...) - } - if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") { - t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1") - } - upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper { - addr := authorityAddr("https", authority) - if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil { - go c.Close() - return erringRoundTripper{err} - } else if !used { - // Turns out we don't need this c. - // For example, two goroutines made requests to the same host - // at the same time, both kicking off TCP dials. (since protocol - // was unknown) - go c.Close() - } - return t2 - } - if m := t1.TLSNextProto; len(m) == 0 { - t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{ - "h2": upgradeFn, - } - } else { - m["h2"] = upgradeFn - } - return t2, nil -} - -// registerHTTPSProtocol calls Transport.RegisterProtocol but -// converting panics into errors. -func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) { - defer func() { - if e := recover(); e != nil { - err = fmt.Errorf("%v", e) - } - }() - t.RegisterProtocol("https", rt) - return nil -} - -// noDialH2RoundTripper is a RoundTripper which only tries to complete the request -// if there's already has a cached connection to the host. -// (The field is exported so it can be accessed via reflect from net/http; tested -// by TestNoDialH2RoundTripperType) -type noDialH2RoundTripper struct{ *Transport } - -func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - res, err := rt.Transport.RoundTrip(req) - if isNoCachedConnError(err) { - return nil, http.ErrSkipAltProtocol - } - return res, err -} diff --git a/examples/golang.org/x/net/http2/databuffer.go b/examples/golang.org/x/net/http2/databuffer.go deleted file mode 100644 index a3067f8..0000000 --- a/examples/golang.org/x/net/http2/databuffer.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "errors" - "fmt" - "sync" -) - -// Buffer chunks are allocated from a pool to reduce pressure on GC. -// The maximum wasted space per dataBuffer is 2x the largest size class, -// which happens when the dataBuffer has multiple chunks and there is -// one unread byte in both the first and last chunks. We use a few size -// classes to minimize overheads for servers that typically receive very -// small request bodies. -// -// TODO: Benchmark to determine if the pools are necessary. The GC may have -// improved enough that we can instead allocate chunks like this: -// make([]byte, max(16<<10, expectedBytesRemaining)) -var ( - dataChunkSizeClasses = []int{ - 1 << 10, - 2 << 10, - 4 << 10, - 8 << 10, - 16 << 10, - } - dataChunkPools = [...]sync.Pool{ - {New: func() interface{} { return make([]byte, 1<<10) }}, - {New: func() interface{} { return make([]byte, 2<<10) }}, - {New: func() interface{} { return make([]byte, 4<<10) }}, - {New: func() interface{} { return make([]byte, 8<<10) }}, - {New: func() interface{} { return make([]byte, 16<<10) }}, - } -) - -func getDataBufferChunk(size int64) []byte { - i := 0 - for ; i < len(dataChunkSizeClasses)-1; i++ { - if size <= int64(dataChunkSizeClasses[i]) { - break - } - } - return dataChunkPools[i].Get().([]byte) -} - -func putDataBufferChunk(p []byte) { - for i, n := range dataChunkSizeClasses { - if len(p) == n { - dataChunkPools[i].Put(p) - return - } - } - panic(fmt.Sprintf("unexpected buffer len=%v", len(p))) -} - -// dataBuffer is an io.ReadWriter backed by a list of data chunks. -// Each dataBuffer is used to read DATA frames on a single stream. -// The buffer is divided into chunks so the server can limit the -// total memory used by a single connection without limiting the -// request body size on any single stream. -type dataBuffer struct { - chunks [][]byte - r int // next byte to read is chunks[0][r] - w int // next byte to write is chunks[len(chunks)-1][w] - size int // total buffered bytes - expected int64 // we expect at least this many bytes in future Write calls (ignored if <= 0) -} - -var errReadEmpty = errors.New("read from empty dataBuffer") - -// Read copies bytes from the buffer into p. -// It is an error to read when no data is available. -func (b *dataBuffer) Read(p []byte) (int, error) { - if b.size == 0 { - return 0, errReadEmpty - } - var ntotal int - for len(p) > 0 && b.size > 0 { - readFrom := b.bytesFromFirstChunk() - n := copy(p, readFrom) - p = p[n:] - ntotal += n - b.r += n - b.size -= n - // If the first chunk has been consumed, advance to the next chunk. - if b.r == len(b.chunks[0]) { - putDataBufferChunk(b.chunks[0]) - end := len(b.chunks) - 1 - copy(b.chunks[:end], b.chunks[1:]) - b.chunks[end] = nil - b.chunks = b.chunks[:end] - b.r = 0 - } - } - return ntotal, nil -} - -func (b *dataBuffer) bytesFromFirstChunk() []byte { - if len(b.chunks) == 1 { - return b.chunks[0][b.r:b.w] - } - return b.chunks[0][b.r:] -} - -// Len returns the number of bytes of the unread portion of the buffer. -func (b *dataBuffer) Len() int { - return b.size -} - -// Write appends p to the buffer. -func (b *dataBuffer) Write(p []byte) (int, error) { - ntotal := len(p) - for len(p) > 0 { - // If the last chunk is empty, allocate a new chunk. Try to allocate - // enough to fully copy p plus any additional bytes we expect to - // receive. However, this may allocate less than len(p). - want := int64(len(p)) - if b.expected > want { - want = b.expected - } - chunk := b.lastChunkOrAlloc(want) - n := copy(chunk[b.w:], p) - p = p[n:] - b.w += n - b.size += n - b.expected -= int64(n) - } - return ntotal, nil -} - -func (b *dataBuffer) lastChunkOrAlloc(want int64) []byte { - if len(b.chunks) != 0 { - last := b.chunks[len(b.chunks)-1] - if b.w < len(last) { - return last - } - } - chunk := getDataBufferChunk(want) - b.chunks = append(b.chunks, chunk) - b.w = 0 - return chunk -} diff --git a/examples/golang.org/x/net/http2/databuffer_test.go b/examples/golang.org/x/net/http2/databuffer_test.go deleted file mode 100644 index 028e12e..0000000 --- a/examples/golang.org/x/net/http2/databuffer_test.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package http2 - -import ( - "bytes" - "fmt" - "reflect" - "testing" -) - -func fmtDataChunk(chunk []byte) string { - out := "" - var last byte - var count int - for _, c := range chunk { - if c != last { - if count > 0 { - out += fmt.Sprintf(" x %d ", count) - count = 0 - } - out += string([]byte{c}) - last = c - } - count++ - } - if count > 0 { - out += fmt.Sprintf(" x %d", count) - } - return out -} - -func fmtDataChunks(chunks [][]byte) string { - var out string - for _, chunk := range chunks { - out += fmt.Sprintf("{%q}", fmtDataChunk(chunk)) - } - return out -} - -func testDataBuffer(t *testing.T, wantBytes []byte, setup func(t *testing.T) *dataBuffer) { - // Run setup, then read the remaining bytes from the dataBuffer and check - // that they match wantBytes. We use different read sizes to check corner - // cases in Read. - for _, readSize := range []int{1, 2, 1 * 1024, 32 * 1024} { - t.Run(fmt.Sprintf("ReadSize=%d", readSize), func(t *testing.T) { - b := setup(t) - buf := make([]byte, readSize) - var gotRead bytes.Buffer - for { - n, err := b.Read(buf) - gotRead.Write(buf[:n]) - if err == errReadEmpty { - break - } - if err != nil { - t.Fatalf("error after %v bytes: %v", gotRead.Len(), err) - } - } - if got, want := gotRead.Bytes(), wantBytes; !bytes.Equal(got, want) { - t.Errorf("FinalRead=%q, want %q", fmtDataChunk(got), fmtDataChunk(want)) - } - }) - } -} - -func TestDataBufferAllocation(t *testing.T) { - writes := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024-1), - []byte("a"), - bytes.Repeat([]byte("b"), 4*1024-1), - []byte("b"), - bytes.Repeat([]byte("c"), 8*1024-1), - []byte("c"), - bytes.Repeat([]byte("d"), 16*1024-1), - []byte("d"), - bytes.Repeat([]byte("e"), 32*1024), - } - var wantRead bytes.Buffer - for _, p := range writes { - wantRead.Write(p) - } - - testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { - b := &dataBuffer{} - for _, p := range writes { - if n, err := b.Write(p); n != len(p) || err != nil { - t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) - } - } - want := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024), - bytes.Repeat([]byte("b"), 4*1024), - bytes.Repeat([]byte("c"), 8*1024), - bytes.Repeat([]byte("d"), 16*1024), - bytes.Repeat([]byte("e"), 16*1024), - bytes.Repeat([]byte("e"), 16*1024), - } - if !reflect.DeepEqual(b.chunks, want) { - t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) - } - return b - }) -} - -func TestDataBufferAllocationWithExpected(t *testing.T) { - writes := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024), // allocates 16KB - bytes.Repeat([]byte("b"), 14*1024), - bytes.Repeat([]byte("c"), 15*1024), // allocates 16KB more - bytes.Repeat([]byte("d"), 2*1024), - bytes.Repeat([]byte("e"), 1*1024), // overflows 32KB expectation, allocates just 1KB - } - var wantRead bytes.Buffer - for _, p := range writes { - wantRead.Write(p) - } - - testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { - b := &dataBuffer{expected: 32 * 1024} - for _, p := range writes { - if n, err := b.Write(p); n != len(p) || err != nil { - t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) - } - } - want := [][]byte{ - append(bytes.Repeat([]byte("a"), 1*1024), append(bytes.Repeat([]byte("b"), 14*1024), bytes.Repeat([]byte("c"), 1*1024)...)...), - append(bytes.Repeat([]byte("c"), 14*1024), bytes.Repeat([]byte("d"), 2*1024)...), - bytes.Repeat([]byte("e"), 1*1024), - } - if !reflect.DeepEqual(b.chunks, want) { - t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) - } - return b - }) -} - -func TestDataBufferWriteAfterPartialRead(t *testing.T) { - testDataBuffer(t, []byte("cdxyz"), func(t *testing.T) *dataBuffer { - b := &dataBuffer{} - if n, err := b.Write([]byte("abcd")); n != 4 || err != nil { - t.Fatalf("Write(\"abcd\")=%v,%v want 4,nil", n, err) - } - p := make([]byte, 2) - if n, err := b.Read(p); n != 2 || err != nil || !bytes.Equal(p, []byte("ab")) { - t.Fatalf("Read()=%q,%v,%v want \"ab\",2,nil", p, n, err) - } - if n, err := b.Write([]byte("xyz")); n != 3 || err != nil { - t.Fatalf("Write(\"xyz\")=%v,%v want 3,nil", n, err) - } - return b - }) -} diff --git a/examples/golang.org/x/net/http2/errors.go b/examples/golang.org/x/net/http2/errors.go deleted file mode 100644 index 71f2c46..0000000 --- a/examples/golang.org/x/net/http2/errors.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "errors" - "fmt" -) - -// An ErrCode is an unsigned 32-bit error code as defined in the HTTP/2 spec. -type ErrCode uint32 - -const ( - ErrCodeNo ErrCode = 0x0 - ErrCodeProtocol ErrCode = 0x1 - ErrCodeInternal ErrCode = 0x2 - ErrCodeFlowControl ErrCode = 0x3 - ErrCodeSettingsTimeout ErrCode = 0x4 - ErrCodeStreamClosed ErrCode = 0x5 - ErrCodeFrameSize ErrCode = 0x6 - ErrCodeRefusedStream ErrCode = 0x7 - ErrCodeCancel ErrCode = 0x8 - ErrCodeCompression ErrCode = 0x9 - ErrCodeConnect ErrCode = 0xa - ErrCodeEnhanceYourCalm ErrCode = 0xb - ErrCodeInadequateSecurity ErrCode = 0xc - ErrCodeHTTP11Required ErrCode = 0xd -) - -var errCodeName = map[ErrCode]string{ - ErrCodeNo: "NO_ERROR", - ErrCodeProtocol: "PROTOCOL_ERROR", - ErrCodeInternal: "INTERNAL_ERROR", - ErrCodeFlowControl: "FLOW_CONTROL_ERROR", - ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT", - ErrCodeStreamClosed: "STREAM_CLOSED", - ErrCodeFrameSize: "FRAME_SIZE_ERROR", - ErrCodeRefusedStream: "REFUSED_STREAM", - ErrCodeCancel: "CANCEL", - ErrCodeCompression: "COMPRESSION_ERROR", - ErrCodeConnect: "CONNECT_ERROR", - ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM", - ErrCodeInadequateSecurity: "INADEQUATE_SECURITY", - ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED", -} - -func (e ErrCode) String() string { - if s, ok := errCodeName[e]; ok { - return s - } - return fmt.Sprintf("unknown error code 0x%x", uint32(e)) -} - -// ConnectionError is an error that results in the termination of the -// entire connection. -type ConnectionError ErrCode - -func (e ConnectionError) Error() string { return fmt.Sprintf("connection error: %s", ErrCode(e)) } - -// StreamError is an error that only affects one stream within an -// HTTP/2 connection. -type StreamError struct { - StreamID uint32 - Code ErrCode - Cause error // optional additional detail -} - -func streamError(id uint32, code ErrCode) StreamError { - return StreamError{StreamID: id, Code: code} -} - -func (e StreamError) Error() string { - if e.Cause != nil { - return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause) - } - return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code) -} - -// 6.9.1 The Flow Control Window -// "If a sender receives a WINDOW_UPDATE that causes a flow control -// window to exceed this maximum it MUST terminate either the stream -// or the connection, as appropriate. For streams, [...]; for the -// connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code." -type goAwayFlowError struct{} - -func (goAwayFlowError) Error() string { return "connection exceeded flow control window size" } - -// connError represents an HTTP/2 ConnectionError error code, along -// with a string (for debugging) explaining why. -// -// Errors of this type are only returned by the frame parser functions -// and converted into ConnectionError(Code), after stashing away -// the Reason into the Framer's errDetail field, accessible via -// the (*Framer).ErrorDetail method. -type connError struct { - Code ErrCode // the ConnectionError error code - Reason string // additional reason -} - -func (e connError) Error() string { - return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason) -} - -type pseudoHeaderError string - -func (e pseudoHeaderError) Error() string { - return fmt.Sprintf("invalid pseudo-header %q", string(e)) -} - -type duplicatePseudoHeaderError string - -func (e duplicatePseudoHeaderError) Error() string { - return fmt.Sprintf("duplicate pseudo-header %q", string(e)) -} - -type headerFieldNameError string - -func (e headerFieldNameError) Error() string { - return fmt.Sprintf("invalid header field name %q", string(e)) -} - -type headerFieldValueError string - -func (e headerFieldValueError) Error() string { - return fmt.Sprintf("invalid header field value %q", string(e)) -} - -var ( - errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers") - errPseudoAfterRegular = errors.New("pseudo header field after regular") -) diff --git a/examples/golang.org/x/net/http2/errors_test.go b/examples/golang.org/x/net/http2/errors_test.go deleted file mode 100644 index da5c58c..0000000 --- a/examples/golang.org/x/net/http2/errors_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "testing" - -func TestErrCodeString(t *testing.T) { - tests := []struct { - err ErrCode - want string - }{ - {ErrCodeProtocol, "PROTOCOL_ERROR"}, - {0xd, "HTTP_1_1_REQUIRED"}, - {0xf, "unknown error code 0xf"}, - } - for i, tt := range tests { - got := tt.err.String() - if got != tt.want { - t.Errorf("%d. Error = %q; want %q", i, got, tt.want) - } - } -} diff --git a/examples/golang.org/x/net/http2/flow.go b/examples/golang.org/x/net/http2/flow.go deleted file mode 100644 index cea601f..0000000 --- a/examples/golang.org/x/net/http2/flow.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Flow control - -package http2 - -// flow is the flow control window's size. -type flow struct { - // n is the number of DATA bytes we're allowed to send. - // A flow is kept both on a conn and a per-stream. - n int32 - - // conn points to the shared connection-level flow that is - // shared by all streams on that conn. It is nil for the flow - // that's on the conn directly. - conn *flow -} - -func (f *flow) setConnFlow(cf *flow) { f.conn = cf } - -func (f *flow) available() int32 { - n := f.n - if f.conn != nil && f.conn.n < n { - n = f.conn.n - } - return n -} - -func (f *flow) take(n int32) { - if n > f.available() { - panic("internal error: took too much") - } - f.n -= n - if f.conn != nil { - f.conn.n -= n - } -} - -// add adds n bytes (positive or negative) to the flow control window. -// It returns false if the sum would exceed 2^31-1. -func (f *flow) add(n int32) bool { - sum := f.n + n - if (sum > n) == (f.n > 0) { - f.n = sum - return true - } - return false -} diff --git a/examples/golang.org/x/net/http2/flow_test.go b/examples/golang.org/x/net/http2/flow_test.go deleted file mode 100644 index 7ae82c7..0000000 --- a/examples/golang.org/x/net/http2/flow_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "testing" - -func TestFlow(t *testing.T) { - var st flow - var conn flow - st.add(3) - conn.add(2) - - if got, want := st.available(), int32(3); got != want { - t.Errorf("available = %d; want %d", got, want) - } - st.setConnFlow(&conn) - if got, want := st.available(), int32(2); got != want { - t.Errorf("after parent setup, available = %d; want %d", got, want) - } - - st.take(2) - if got, want := conn.available(), int32(0); got != want { - t.Errorf("after taking 2, conn = %d; want %d", got, want) - } - if got, want := st.available(), int32(0); got != want { - t.Errorf("after taking 2, stream = %d; want %d", got, want) - } -} - -func TestFlowAdd(t *testing.T) { - var f flow - if !f.add(1) { - t.Fatal("failed to add 1") - } - if !f.add(-1) { - t.Fatal("failed to add -1") - } - if got, want := f.available(), int32(0); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - if !f.add(1<<31 - 1) { - t.Fatal("failed to add 2^31-1") - } - if got, want := f.available(), int32(1<<31-1); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - if f.add(1) { - t.Fatal("adding 1 to max shouldn't be allowed") - } -} - -func TestFlowAddOverflow(t *testing.T) { - var f flow - if !f.add(0) { - t.Fatal("failed to add 0") - } - if !f.add(-1) { - t.Fatal("failed to add -1") - } - if !f.add(0) { - t.Fatal("failed to add 0") - } - if !f.add(1) { - t.Fatal("failed to add 1") - } - if !f.add(1) { - t.Fatal("failed to add 1") - } - if !f.add(0) { - t.Fatal("failed to add 0") - } - if !f.add(-3) { - t.Fatal("failed to add -3") - } - if got, want := f.available(), int32(-2); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - if !f.add(1<<31 - 1) { - t.Fatal("failed to add 2^31-1") - } - if got, want := f.available(), int32(1+-3+(1<<31-1)); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - -} diff --git a/examples/golang.org/x/net/http2/frame.go b/examples/golang.org/x/net/http2/frame.go deleted file mode 100644 index e325007..0000000 --- a/examples/golang.org/x/net/http2/frame.go +++ /dev/null @@ -1,1579 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "log" - "strings" - "sync" - - "golang.org/x/net/http/httpguts" - "golang.org/x/net/http2/hpack" -) - -const frameHeaderLen = 9 - -var padZeros = make([]byte, 255) // zeros for padding - -// A FrameType is a registered frame type as defined in -// http://http2.github.io/http2-spec/#rfc.section.11.2 -type FrameType uint8 - -const ( - FrameData FrameType = 0x0 - FrameHeaders FrameType = 0x1 - FramePriority FrameType = 0x2 - FrameRSTStream FrameType = 0x3 - FrameSettings FrameType = 0x4 - FramePushPromise FrameType = 0x5 - FramePing FrameType = 0x6 - FrameGoAway FrameType = 0x7 - FrameWindowUpdate FrameType = 0x8 - FrameContinuation FrameType = 0x9 -) - -var frameName = map[FrameType]string{ - FrameData: "DATA", - FrameHeaders: "HEADERS", - FramePriority: "PRIORITY", - FrameRSTStream: "RST_STREAM", - FrameSettings: "SETTINGS", - FramePushPromise: "PUSH_PROMISE", - FramePing: "PING", - FrameGoAway: "GOAWAY", - FrameWindowUpdate: "WINDOW_UPDATE", - FrameContinuation: "CONTINUATION", -} - -func (t FrameType) String() string { - if s, ok := frameName[t]; ok { - return s - } - return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t)) -} - -// Flags is a bitmask of HTTP/2 flags. -// The meaning of flags varies depending on the frame type. -type Flags uint8 - -// Has reports whether f contains all (0 or more) flags in v. -func (f Flags) Has(v Flags) bool { - return (f & v) == v -} - -// Frame-specific FrameHeader flag bits. -const ( - // Data Frame - FlagDataEndStream Flags = 0x1 - FlagDataPadded Flags = 0x8 - - // Headers Frame - FlagHeadersEndStream Flags = 0x1 - FlagHeadersEndHeaders Flags = 0x4 - FlagHeadersPadded Flags = 0x8 - FlagHeadersPriority Flags = 0x20 - - // Settings Frame - FlagSettingsAck Flags = 0x1 - - // Ping Frame - FlagPingAck Flags = 0x1 - - // Continuation Frame - FlagContinuationEndHeaders Flags = 0x4 - - FlagPushPromiseEndHeaders Flags = 0x4 - FlagPushPromisePadded Flags = 0x8 -) - -var flagName = map[FrameType]map[Flags]string{ - FrameData: { - FlagDataEndStream: "END_STREAM", - FlagDataPadded: "PADDED", - }, - FrameHeaders: { - FlagHeadersEndStream: "END_STREAM", - FlagHeadersEndHeaders: "END_HEADERS", - FlagHeadersPadded: "PADDED", - FlagHeadersPriority: "PRIORITY", - }, - FrameSettings: { - FlagSettingsAck: "ACK", - }, - FramePing: { - FlagPingAck: "ACK", - }, - FrameContinuation: { - FlagContinuationEndHeaders: "END_HEADERS", - }, - FramePushPromise: { - FlagPushPromiseEndHeaders: "END_HEADERS", - FlagPushPromisePadded: "PADDED", - }, -} - -// a frameParser parses a frame given its FrameHeader and payload -// bytes. The length of payload will always equal fh.Length (which -// might be 0). -type frameParser func(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) - -var frameParsers = map[FrameType]frameParser{ - FrameData: parseDataFrame, - FrameHeaders: parseHeadersFrame, - FramePriority: parsePriorityFrame, - FrameRSTStream: parseRSTStreamFrame, - FrameSettings: parseSettingsFrame, - FramePushPromise: parsePushPromise, - FramePing: parsePingFrame, - FrameGoAway: parseGoAwayFrame, - FrameWindowUpdate: parseWindowUpdateFrame, - FrameContinuation: parseContinuationFrame, -} - -func typeFrameParser(t FrameType) frameParser { - if f := frameParsers[t]; f != nil { - return f - } - return parseUnknownFrame -} - -// A FrameHeader is the 9 byte header of all HTTP/2 frames. -// -// See http://http2.github.io/http2-spec/#FrameHeader -type FrameHeader struct { - valid bool // caller can access []byte fields in the Frame - - // Type is the 1 byte frame type. There are ten standard frame - // types, but extension frame types may be written by WriteRawFrame - // and will be returned by ReadFrame (as UnknownFrame). - Type FrameType - - // Flags are the 1 byte of 8 potential bit flags per frame. - // They are specific to the frame type. - Flags Flags - - // Length is the length of the frame, not including the 9 byte header. - // The maximum size is one byte less than 16MB (uint24), but only - // frames up to 16KB are allowed without peer agreement. - Length uint32 - - // StreamID is which stream this frame is for. Certain frames - // are not stream-specific, in which case this field is 0. - StreamID uint32 -} - -// Header returns h. It exists so FrameHeaders can be embedded in other -// specific frame types and implement the Frame interface. -func (h FrameHeader) Header() FrameHeader { return h } - -func (h FrameHeader) String() string { - var buf bytes.Buffer - buf.WriteString("[FrameHeader ") - h.writeDebug(&buf) - buf.WriteByte(']') - return buf.String() -} - -func (h FrameHeader) writeDebug(buf *bytes.Buffer) { - buf.WriteString(h.Type.String()) - if h.Flags != 0 { - buf.WriteString(" flags=") - set := 0 - for i := uint8(0); i < 8; i++ { - if h.Flags&(1< 1 { - buf.WriteByte('|') - } - name := flagName[h.Type][Flags(1<>24), - byte(streamID>>16), - byte(streamID>>8), - byte(streamID)) -} - -func (f *Framer) endWrite() error { - // Now that we know the final size, fill in the FrameHeader in - // the space previously reserved for it. Abuse append. - length := len(f.wbuf) - frameHeaderLen - if length >= (1 << 24) { - return ErrFrameTooLarge - } - _ = append(f.wbuf[:0], - byte(length>>16), - byte(length>>8), - byte(length)) - if f.logWrites { - f.logWrite() - } - - n, err := f.w.Write(f.wbuf) - if err == nil && n != len(f.wbuf) { - err = io.ErrShortWrite - } - return err -} - -func (f *Framer) logWrite() { - if f.debugFramer == nil { - f.debugFramerBuf = new(bytes.Buffer) - f.debugFramer = NewFramer(nil, f.debugFramerBuf) - f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below - // Let us read anything, even if we accidentally wrote it - // in the wrong order: - f.debugFramer.AllowIllegalReads = true - } - f.debugFramerBuf.Write(f.wbuf) - fr, err := f.debugFramer.ReadFrame() - if err != nil { - f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f) - return - } - f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr)) -} - -func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) } -func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) } -func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) } -func (f *Framer) writeUint32(v uint32) { - f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - -const ( - minMaxFrameSize = 1 << 14 - maxFrameSize = 1<<24 - 1 -) - -// SetReuseFrames allows the Framer to reuse Frames. -// If called on a Framer, Frames returned by calls to ReadFrame are only -// valid until the next call to ReadFrame. -func (fr *Framer) SetReuseFrames() { - if fr.frameCache != nil { - return - } - fr.frameCache = &frameCache{} -} - -type frameCache struct { - dataFrame DataFrame -} - -func (fc *frameCache) getDataFrame() *DataFrame { - if fc == nil { - return &DataFrame{} - } - return &fc.dataFrame -} - -// NewFramer returns a Framer that writes frames to w and reads them from r. -func NewFramer(w io.Writer, r io.Reader) *Framer { - fr := &Framer{ - w: w, - r: r, - logReads: logFrameReads, - logWrites: logFrameWrites, - debugReadLoggerf: log.Printf, - debugWriteLoggerf: log.Printf, - } - fr.getReadBuf = func(size uint32) []byte { - if cap(fr.readBuf) >= int(size) { - return fr.readBuf[:size] - } - fr.readBuf = make([]byte, size) - return fr.readBuf - } - fr.SetMaxReadFrameSize(maxFrameSize) - return fr -} - -// SetMaxReadFrameSize sets the maximum size of a frame -// that will be read by a subsequent call to ReadFrame. -// It is the caller's responsibility to advertise this -// limit with a SETTINGS frame. -func (fr *Framer) SetMaxReadFrameSize(v uint32) { - if v > maxFrameSize { - v = maxFrameSize - } - fr.maxReadSize = v -} - -// ErrorDetail returns a more detailed error of the last error -// returned by Framer.ReadFrame. For instance, if ReadFrame -// returns a StreamError with code PROTOCOL_ERROR, ErrorDetail -// will say exactly what was invalid. ErrorDetail is not guaranteed -// to return a non-nil value and like the rest of the http2 package, -// its return value is not protected by an API compatibility promise. -// ErrorDetail is reset after the next call to ReadFrame. -func (fr *Framer) ErrorDetail() error { - return fr.errDetail -} - -// ErrFrameTooLarge is returned from Framer.ReadFrame when the peer -// sends a frame that is larger than declared with SetMaxReadFrameSize. -var ErrFrameTooLarge = errors.New("http2: frame too large") - -// terminalReadFrameError reports whether err is an unrecoverable -// error from ReadFrame and no other frames should be read. -func terminalReadFrameError(err error) bool { - if _, ok := err.(StreamError); ok { - return false - } - return err != nil -} - -// ReadFrame reads a single frame. The returned Frame is only valid -// until the next call to ReadFrame. -// -// If the frame is larger than previously set with SetMaxReadFrameSize, the -// returned error is ErrFrameTooLarge. Other errors may be of type -// ConnectionError, StreamError, or anything else from the underlying -// reader. -func (fr *Framer) ReadFrame() (Frame, error) { - fr.errDetail = nil - if fr.lastFrame != nil { - fr.lastFrame.invalidate() - } - fh, err := readFrameHeader(fr.headerBuf[:], fr.r) - if err != nil { - return nil, err - } - if fh.Length > fr.maxReadSize { - return nil, ErrFrameTooLarge - } - payload := fr.getReadBuf(fh.Length) - if _, err := io.ReadFull(fr.r, payload); err != nil { - return nil, err - } - f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, payload) - if err != nil { - if ce, ok := err.(connError); ok { - return nil, fr.connError(ce.Code, ce.Reason) - } - return nil, err - } - if err := fr.checkFrameOrder(f); err != nil { - return nil, err - } - if fr.logReads { - fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f)) - } - if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil { - return fr.readMetaFrame(f.(*HeadersFrame)) - } - return f, nil -} - -// connError returns ConnectionError(code) but first -// stashes away a public reason to the caller can optionally relay it -// to the peer before hanging up on them. This might help others debug -// their implementations. -func (fr *Framer) connError(code ErrCode, reason string) error { - fr.errDetail = errors.New(reason) - return ConnectionError(code) -} - -// checkFrameOrder reports an error if f is an invalid frame to return -// next from ReadFrame. Mostly it checks whether HEADERS and -// CONTINUATION frames are contiguous. -func (fr *Framer) checkFrameOrder(f Frame) error { - last := fr.lastFrame - fr.lastFrame = f - if fr.AllowIllegalReads { - return nil - } - - fh := f.Header() - if fr.lastHeaderStream != 0 { - if fh.Type != FrameContinuation { - return fr.connError(ErrCodeProtocol, - fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d", - fh.Type, fh.StreamID, - last.Header().Type, fr.lastHeaderStream)) - } - if fh.StreamID != fr.lastHeaderStream { - return fr.connError(ErrCodeProtocol, - fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d", - fh.StreamID, fr.lastHeaderStream)) - } - } else if fh.Type == FrameContinuation { - return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID)) - } - - switch fh.Type { - case FrameHeaders, FrameContinuation: - if fh.Flags.Has(FlagHeadersEndHeaders) { - fr.lastHeaderStream = 0 - } else { - fr.lastHeaderStream = fh.StreamID - } - } - - return nil -} - -// A DataFrame conveys arbitrary, variable-length sequences of octets -// associated with a stream. -// See http://http2.github.io/http2-spec/#rfc.section.6.1 -type DataFrame struct { - FrameHeader - data []byte -} - -func (f *DataFrame) StreamEnded() bool { - return f.FrameHeader.Flags.Has(FlagDataEndStream) -} - -// Data returns the frame's data octets, not including any padding -// size byte or padding suffix bytes. -// The caller must not retain the returned memory past the next -// call to ReadFrame. -func (f *DataFrame) Data() []byte { - f.checkValid() - return f.data -} - -func parseDataFrame(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) { - if fh.StreamID == 0 { - // DATA frames MUST be associated with a stream. If a - // DATA frame is received whose stream identifier - // field is 0x0, the recipient MUST respond with a - // connection error (Section 5.4.1) of type - // PROTOCOL_ERROR. - return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"} - } - f := fc.getDataFrame() - f.FrameHeader = fh - - var padSize byte - if fh.Flags.Has(FlagDataPadded) { - var err error - payload, padSize, err = readByte(payload) - if err != nil { - return nil, err - } - } - if int(padSize) > len(payload) { - // If the length of the padding is greater than the - // length of the frame payload, the recipient MUST - // treat this as a connection error. - // Filed: https://github.com/http2/http2-spec/issues/610 - return nil, connError{ErrCodeProtocol, "pad size larger than data payload"} - } - f.data = payload[:len(payload)-int(padSize)] - return f, nil -} - -var ( - errStreamID = errors.New("invalid stream ID") - errDepStreamID = errors.New("invalid dependent stream ID") - errPadLength = errors.New("pad length too large") - errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled") -) - -func validStreamIDOrZero(streamID uint32) bool { - return streamID&(1<<31) == 0 -} - -func validStreamID(streamID uint32) bool { - return streamID != 0 && streamID&(1<<31) == 0 -} - -// WriteData writes a DATA frame. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility not to violate the maximum frame size -// and to not call other Write methods concurrently. -func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error { - return f.WriteDataPadded(streamID, endStream, data, nil) -} - -// WriteData writes a DATA frame with optional padding. -// -// If pad is nil, the padding bit is not sent. -// The length of pad must not exceed 255 bytes. -// The bytes of pad must all be zero, unless f.AllowIllegalWrites is set. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility not to violate the maximum frame size -// and to not call other Write methods concurrently. -func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error { - if !validStreamID(streamID) && !f.AllowIllegalWrites { - return errStreamID - } - if len(pad) > 0 { - if len(pad) > 255 { - return errPadLength - } - if !f.AllowIllegalWrites { - for _, b := range pad { - if b != 0 { - // "Padding octets MUST be set to zero when sending." - return errPadBytes - } - } - } - } - var flags Flags - if endStream { - flags |= FlagDataEndStream - } - if pad != nil { - flags |= FlagDataPadded - } - f.startWrite(FrameData, flags, streamID) - if pad != nil { - f.wbuf = append(f.wbuf, byte(len(pad))) - } - f.wbuf = append(f.wbuf, data...) - f.wbuf = append(f.wbuf, pad...) - return f.endWrite() -} - -// A SettingsFrame conveys configuration parameters that affect how -// endpoints communicate, such as preferences and constraints on peer -// behavior. -// -// See http://http2.github.io/http2-spec/#SETTINGS -type SettingsFrame struct { - FrameHeader - p []byte -} - -func parseSettingsFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 { - // When this (ACK 0x1) bit is set, the payload of the - // SETTINGS frame MUST be empty. Receipt of a - // SETTINGS frame with the ACK flag set and a length - // field value other than 0 MUST be treated as a - // connection error (Section 5.4.1) of type - // FRAME_SIZE_ERROR. - return nil, ConnectionError(ErrCodeFrameSize) - } - if fh.StreamID != 0 { - // SETTINGS frames always apply to a connection, - // never a single stream. The stream identifier for a - // SETTINGS frame MUST be zero (0x0). If an endpoint - // receives a SETTINGS frame whose stream identifier - // field is anything other than 0x0, the endpoint MUST - // respond with a connection error (Section 5.4.1) of - // type PROTOCOL_ERROR. - return nil, ConnectionError(ErrCodeProtocol) - } - if len(p)%6 != 0 { - // Expecting even number of 6 byte settings. - return nil, ConnectionError(ErrCodeFrameSize) - } - f := &SettingsFrame{FrameHeader: fh, p: p} - if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 { - // Values above the maximum flow control window size of 2^31 - 1 MUST - // be treated as a connection error (Section 5.4.1) of type - // FLOW_CONTROL_ERROR. - return nil, ConnectionError(ErrCodeFlowControl) - } - return f, nil -} - -func (f *SettingsFrame) IsAck() bool { - return f.FrameHeader.Flags.Has(FlagSettingsAck) -} - -func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) { - f.checkValid() - buf := f.p - for len(buf) > 0 { - settingID := SettingID(binary.BigEndian.Uint16(buf[:2])) - if settingID == s { - return binary.BigEndian.Uint32(buf[2:6]), true - } - buf = buf[6:] - } - return 0, false -} - -// ForeachSetting runs fn for each setting. -// It stops and returns the first error. -func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error { - f.checkValid() - buf := f.p - for len(buf) > 0 { - if err := fn(Setting{ - SettingID(binary.BigEndian.Uint16(buf[:2])), - binary.BigEndian.Uint32(buf[2:6]), - }); err != nil { - return err - } - buf = buf[6:] - } - return nil -} - -// WriteSettings writes a SETTINGS frame with zero or more settings -// specified and the ACK bit not set. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WriteSettings(settings ...Setting) error { - f.startWrite(FrameSettings, 0, 0) - for _, s := range settings { - f.writeUint16(uint16(s.ID)) - f.writeUint32(s.Val) - } - return f.endWrite() -} - -// WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WriteSettingsAck() error { - f.startWrite(FrameSettings, FlagSettingsAck, 0) - return f.endWrite() -} - -// A PingFrame is a mechanism for measuring a minimal round trip time -// from the sender, as well as determining whether an idle connection -// is still functional. -// See http://http2.github.io/http2-spec/#rfc.section.6.7 -type PingFrame struct { - FrameHeader - Data [8]byte -} - -func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) } - -func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) { - if len(payload) != 8 { - return nil, ConnectionError(ErrCodeFrameSize) - } - if fh.StreamID != 0 { - return nil, ConnectionError(ErrCodeProtocol) - } - f := &PingFrame{FrameHeader: fh} - copy(f.Data[:], payload) - return f, nil -} - -func (f *Framer) WritePing(ack bool, data [8]byte) error { - var flags Flags - if ack { - flags = FlagPingAck - } - f.startWrite(FramePing, flags, 0) - f.writeBytes(data[:]) - return f.endWrite() -} - -// A GoAwayFrame informs the remote peer to stop creating streams on this connection. -// See http://http2.github.io/http2-spec/#rfc.section.6.8 -type GoAwayFrame struct { - FrameHeader - LastStreamID uint32 - ErrCode ErrCode - debugData []byte -} - -// DebugData returns any debug data in the GOAWAY frame. Its contents -// are not defined. -// The caller must not retain the returned memory past the next -// call to ReadFrame. -func (f *GoAwayFrame) DebugData() []byte { - f.checkValid() - return f.debugData -} - -func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - if fh.StreamID != 0 { - return nil, ConnectionError(ErrCodeProtocol) - } - if len(p) < 8 { - return nil, ConnectionError(ErrCodeFrameSize) - } - return &GoAwayFrame{ - FrameHeader: fh, - LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1), - ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])), - debugData: p[8:], - }, nil -} - -func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error { - f.startWrite(FrameGoAway, 0, 0) - f.writeUint32(maxStreamID & (1<<31 - 1)) - f.writeUint32(uint32(code)) - f.writeBytes(debugData) - return f.endWrite() -} - -// An UnknownFrame is the frame type returned when the frame type is unknown -// or no specific frame type parser exists. -type UnknownFrame struct { - FrameHeader - p []byte -} - -// Payload returns the frame's payload (after the header). It is not -// valid to call this method after a subsequent call to -// Framer.ReadFrame, nor is it valid to retain the returned slice. -// The memory is owned by the Framer and is invalidated when the next -// frame is read. -func (f *UnknownFrame) Payload() []byte { - f.checkValid() - return f.p -} - -func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - return &UnknownFrame{fh, p}, nil -} - -// A WindowUpdateFrame is used to implement flow control. -// See http://http2.github.io/http2-spec/#rfc.section.6.9 -type WindowUpdateFrame struct { - FrameHeader - Increment uint32 // never read with high bit set -} - -func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - if len(p) != 4 { - return nil, ConnectionError(ErrCodeFrameSize) - } - inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit - if inc == 0 { - // A receiver MUST treat the receipt of a - // WINDOW_UPDATE frame with an flow control window - // increment of 0 as a stream error (Section 5.4.2) of - // type PROTOCOL_ERROR; errors on the connection flow - // control window MUST be treated as a connection - // error (Section 5.4.1). - if fh.StreamID == 0 { - return nil, ConnectionError(ErrCodeProtocol) - } - return nil, streamError(fh.StreamID, ErrCodeProtocol) - } - return &WindowUpdateFrame{ - FrameHeader: fh, - Increment: inc, - }, nil -} - -// WriteWindowUpdate writes a WINDOW_UPDATE frame. -// The increment value must be between 1 and 2,147,483,647, inclusive. -// If the Stream ID is zero, the window update applies to the -// connection as a whole. -func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error { - // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets." - if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites { - return errors.New("illegal window increment value") - } - f.startWrite(FrameWindowUpdate, 0, streamID) - f.writeUint32(incr) - return f.endWrite() -} - -// A HeadersFrame is used to open a stream and additionally carries a -// header block fragment. -type HeadersFrame struct { - FrameHeader - - // Priority is set if FlagHeadersPriority is set in the FrameHeader. - Priority PriorityParam - - headerFragBuf []byte // not owned -} - -func (f *HeadersFrame) HeaderBlockFragment() []byte { - f.checkValid() - return f.headerFragBuf -} - -func (f *HeadersFrame) HeadersEnded() bool { - return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders) -} - -func (f *HeadersFrame) StreamEnded() bool { - return f.FrameHeader.Flags.Has(FlagHeadersEndStream) -} - -func (f *HeadersFrame) HasPriority() bool { - return f.FrameHeader.Flags.Has(FlagHeadersPriority) -} - -func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) { - hf := &HeadersFrame{ - FrameHeader: fh, - } - if fh.StreamID == 0 { - // HEADERS frames MUST be associated with a stream. If a HEADERS frame - // is received whose stream identifier field is 0x0, the recipient MUST - // respond with a connection error (Section 5.4.1) of type - // PROTOCOL_ERROR. - return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"} - } - var padLength uint8 - if fh.Flags.Has(FlagHeadersPadded) { - if p, padLength, err = readByte(p); err != nil { - return - } - } - if fh.Flags.Has(FlagHeadersPriority) { - var v uint32 - p, v, err = readUint32(p) - if err != nil { - return nil, err - } - hf.Priority.StreamDep = v & 0x7fffffff - hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set - p, hf.Priority.Weight, err = readByte(p) - if err != nil { - return nil, err - } - } - if len(p)-int(padLength) <= 0 { - return nil, streamError(fh.StreamID, ErrCodeProtocol) - } - hf.headerFragBuf = p[:len(p)-int(padLength)] - return hf, nil -} - -// HeadersFrameParam are the parameters for writing a HEADERS frame. -type HeadersFrameParam struct { - // StreamID is the required Stream ID to initiate. - StreamID uint32 - // BlockFragment is part (or all) of a Header Block. - BlockFragment []byte - - // EndStream indicates that the header block is the last that - // the endpoint will send for the identified stream. Setting - // this flag causes the stream to enter one of "half closed" - // states. - EndStream bool - - // EndHeaders indicates that this frame contains an entire - // header block and is not followed by any - // CONTINUATION frames. - EndHeaders bool - - // PadLength is the optional number of bytes of zeros to add - // to this frame. - PadLength uint8 - - // Priority, if non-zero, includes stream priority information - // in the HEADER frame. - Priority PriorityParam -} - -// WriteHeaders writes a single HEADERS frame. -// -// This is a low-level header writing method. Encoding headers and -// splitting them into any necessary CONTINUATION frames is handled -// elsewhere. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WriteHeaders(p HeadersFrameParam) error { - if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { - return errStreamID - } - var flags Flags - if p.PadLength != 0 { - flags |= FlagHeadersPadded - } - if p.EndStream { - flags |= FlagHeadersEndStream - } - if p.EndHeaders { - flags |= FlagHeadersEndHeaders - } - if !p.Priority.IsZero() { - flags |= FlagHeadersPriority - } - f.startWrite(FrameHeaders, flags, p.StreamID) - if p.PadLength != 0 { - f.writeByte(p.PadLength) - } - if !p.Priority.IsZero() { - v := p.Priority.StreamDep - if !validStreamIDOrZero(v) && !f.AllowIllegalWrites { - return errDepStreamID - } - if p.Priority.Exclusive { - v |= 1 << 31 - } - f.writeUint32(v) - f.writeByte(p.Priority.Weight) - } - f.wbuf = append(f.wbuf, p.BlockFragment...) - f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) - return f.endWrite() -} - -// A PriorityFrame specifies the sender-advised priority of a stream. -// See http://http2.github.io/http2-spec/#rfc.section.6.3 -type PriorityFrame struct { - FrameHeader - PriorityParam -} - -// PriorityParam are the stream prioritzation parameters. -type PriorityParam struct { - // StreamDep is a 31-bit stream identifier for the - // stream that this stream depends on. Zero means no - // dependency. - StreamDep uint32 - - // Exclusive is whether the dependency is exclusive. - Exclusive bool - - // Weight is the stream's zero-indexed weight. It should be - // set together with StreamDep, or neither should be set. Per - // the spec, "Add one to the value to obtain a weight between - // 1 and 256." - Weight uint8 -} - -func (p PriorityParam) IsZero() bool { - return p == PriorityParam{} -} - -func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) { - if fh.StreamID == 0 { - return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"} - } - if len(payload) != 5 { - return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))} - } - v := binary.BigEndian.Uint32(payload[:4]) - streamID := v & 0x7fffffff // mask off high bit - return &PriorityFrame{ - FrameHeader: fh, - PriorityParam: PriorityParam{ - Weight: payload[4], - StreamDep: streamID, - Exclusive: streamID != v, // was high bit set? - }, - }, nil -} - -// WritePriority writes a PRIORITY frame. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error { - if !validStreamID(streamID) && !f.AllowIllegalWrites { - return errStreamID - } - if !validStreamIDOrZero(p.StreamDep) { - return errDepStreamID - } - f.startWrite(FramePriority, 0, streamID) - v := p.StreamDep - if p.Exclusive { - v |= 1 << 31 - } - f.writeUint32(v) - f.writeByte(p.Weight) - return f.endWrite() -} - -// A RSTStreamFrame allows for abnormal termination of a stream. -// See http://http2.github.io/http2-spec/#rfc.section.6.4 -type RSTStreamFrame struct { - FrameHeader - ErrCode ErrCode -} - -func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - if len(p) != 4 { - return nil, ConnectionError(ErrCodeFrameSize) - } - if fh.StreamID == 0 { - return nil, ConnectionError(ErrCodeProtocol) - } - return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil -} - -// WriteRSTStream writes a RST_STREAM frame. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error { - if !validStreamID(streamID) && !f.AllowIllegalWrites { - return errStreamID - } - f.startWrite(FrameRSTStream, 0, streamID) - f.writeUint32(uint32(code)) - return f.endWrite() -} - -// A ContinuationFrame is used to continue a sequence of header block fragments. -// See http://http2.github.io/http2-spec/#rfc.section.6.10 -type ContinuationFrame struct { - FrameHeader - headerFragBuf []byte -} - -func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) { - if fh.StreamID == 0 { - return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"} - } - return &ContinuationFrame{fh, p}, nil -} - -func (f *ContinuationFrame) HeaderBlockFragment() []byte { - f.checkValid() - return f.headerFragBuf -} - -func (f *ContinuationFrame) HeadersEnded() bool { - return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders) -} - -// WriteContinuation writes a CONTINUATION frame. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error { - if !validStreamID(streamID) && !f.AllowIllegalWrites { - return errStreamID - } - var flags Flags - if endHeaders { - flags |= FlagContinuationEndHeaders - } - f.startWrite(FrameContinuation, flags, streamID) - f.wbuf = append(f.wbuf, headerBlockFragment...) - return f.endWrite() -} - -// A PushPromiseFrame is used to initiate a server stream. -// See http://http2.github.io/http2-spec/#rfc.section.6.6 -type PushPromiseFrame struct { - FrameHeader - PromiseID uint32 - headerFragBuf []byte // not owned -} - -func (f *PushPromiseFrame) HeaderBlockFragment() []byte { - f.checkValid() - return f.headerFragBuf -} - -func (f *PushPromiseFrame) HeadersEnded() bool { - return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders) -} - -func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) { - pp := &PushPromiseFrame{ - FrameHeader: fh, - } - if pp.StreamID == 0 { - // PUSH_PROMISE frames MUST be associated with an existing, - // peer-initiated stream. The stream identifier of a - // PUSH_PROMISE frame indicates the stream it is associated - // with. If the stream identifier field specifies the value - // 0x0, a recipient MUST respond with a connection error - // (Section 5.4.1) of type PROTOCOL_ERROR. - return nil, ConnectionError(ErrCodeProtocol) - } - // The PUSH_PROMISE frame includes optional padding. - // Padding fields and flags are identical to those defined for DATA frames - var padLength uint8 - if fh.Flags.Has(FlagPushPromisePadded) { - if p, padLength, err = readByte(p); err != nil { - return - } - } - - p, pp.PromiseID, err = readUint32(p) - if err != nil { - return - } - pp.PromiseID = pp.PromiseID & (1<<31 - 1) - - if int(padLength) > len(p) { - // like the DATA frame, error out if padding is longer than the body. - return nil, ConnectionError(ErrCodeProtocol) - } - pp.headerFragBuf = p[:len(p)-int(padLength)] - return pp, nil -} - -// PushPromiseParam are the parameters for writing a PUSH_PROMISE frame. -type PushPromiseParam struct { - // StreamID is the required Stream ID to initiate. - StreamID uint32 - - // PromiseID is the required Stream ID which this - // Push Promises - PromiseID uint32 - - // BlockFragment is part (or all) of a Header Block. - BlockFragment []byte - - // EndHeaders indicates that this frame contains an entire - // header block and is not followed by any - // CONTINUATION frames. - EndHeaders bool - - // PadLength is the optional number of bytes of zeros to add - // to this frame. - PadLength uint8 -} - -// WritePushPromise writes a single PushPromise Frame. -// -// As with Header Frames, This is the low level call for writing -// individual frames. Continuation frames are handled elsewhere. -// -// It will perform exactly one Write to the underlying Writer. -// It is the caller's responsibility to not call other Write methods concurrently. -func (f *Framer) WritePushPromise(p PushPromiseParam) error { - if !validStreamID(p.StreamID) && !f.AllowIllegalWrites { - return errStreamID - } - var flags Flags - if p.PadLength != 0 { - flags |= FlagPushPromisePadded - } - if p.EndHeaders { - flags |= FlagPushPromiseEndHeaders - } - f.startWrite(FramePushPromise, flags, p.StreamID) - if p.PadLength != 0 { - f.writeByte(p.PadLength) - } - if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites { - return errStreamID - } - f.writeUint32(p.PromiseID) - f.wbuf = append(f.wbuf, p.BlockFragment...) - f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...) - return f.endWrite() -} - -// WriteRawFrame writes a raw frame. This can be used to write -// extension frames unknown to this package. -func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error { - f.startWrite(t, flags, streamID) - f.writeBytes(payload) - return f.endWrite() -} - -func readByte(p []byte) (remain []byte, b byte, err error) { - if len(p) == 0 { - return nil, 0, io.ErrUnexpectedEOF - } - return p[1:], p[0], nil -} - -func readUint32(p []byte) (remain []byte, v uint32, err error) { - if len(p) < 4 { - return nil, 0, io.ErrUnexpectedEOF - } - return p[4:], binary.BigEndian.Uint32(p[:4]), nil -} - -type streamEnder interface { - StreamEnded() bool -} - -type headersEnder interface { - HeadersEnded() bool -} - -type headersOrContinuation interface { - headersEnder - HeaderBlockFragment() []byte -} - -// A MetaHeadersFrame is the representation of one HEADERS frame and -// zero or more contiguous CONTINUATION frames and the decoding of -// their HPACK-encoded contents. -// -// This type of frame does not appear on the wire and is only returned -// by the Framer when Framer.ReadMetaHeaders is set. -type MetaHeadersFrame struct { - *HeadersFrame - - // Fields are the fields contained in the HEADERS and - // CONTINUATION frames. The underlying slice is owned by the - // Framer and must not be retained after the next call to - // ReadFrame. - // - // Fields are guaranteed to be in the correct http2 order and - // not have unknown pseudo header fields or invalid header - // field names or values. Required pseudo header fields may be - // missing, however. Use the MetaHeadersFrame.Pseudo accessor - // method access pseudo headers. - Fields []hpack.HeaderField - - // Truncated is whether the max header list size limit was hit - // and Fields is incomplete. The hpack decoder state is still - // valid, however. - Truncated bool -} - -// PseudoValue returns the given pseudo header field's value. -// The provided pseudo field should not contain the leading colon. -func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string { - for _, hf := range mh.Fields { - if !hf.IsPseudo() { - return "" - } - if hf.Name[1:] == pseudo { - return hf.Value - } - } - return "" -} - -// RegularFields returns the regular (non-pseudo) header fields of mh. -// The caller does not own the returned slice. -func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField { - for i, hf := range mh.Fields { - if !hf.IsPseudo() { - return mh.Fields[i:] - } - } - return nil -} - -// PseudoFields returns the pseudo header fields of mh. -// The caller does not own the returned slice. -func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField { - for i, hf := range mh.Fields { - if !hf.IsPseudo() { - return mh.Fields[:i] - } - } - return mh.Fields -} - -func (mh *MetaHeadersFrame) checkPseudos() error { - var isRequest, isResponse bool - pf := mh.PseudoFields() - for i, hf := range pf { - switch hf.Name { - case ":method", ":path", ":scheme", ":authority": - isRequest = true - case ":status": - isResponse = true - default: - return pseudoHeaderError(hf.Name) - } - // Check for duplicates. - // This would be a bad algorithm, but N is 4. - // And this doesn't allocate. - for _, hf2 := range pf[:i] { - if hf.Name == hf2.Name { - return duplicatePseudoHeaderError(hf.Name) - } - } - } - if isRequest && isResponse { - return errMixPseudoHeaderTypes - } - return nil -} - -func (fr *Framer) maxHeaderStringLen() int { - v := fr.maxHeaderListSize() - if uint32(int(v)) == v { - return int(v) - } - // They had a crazy big number for MaxHeaderBytes anyway, - // so give them unlimited header lengths: - return 0 -} - -// readMetaFrame returns 0 or more CONTINUATION frames from fr and -// merge them into into the provided hf and returns a MetaHeadersFrame -// with the decoded hpack values. -func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { - if fr.AllowIllegalReads { - return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders") - } - mh := &MetaHeadersFrame{ - HeadersFrame: hf, - } - var remainSize = fr.maxHeaderListSize() - var sawRegular bool - - var invalid error // pseudo header field errors - hdec := fr.ReadMetaHeaders - hdec.SetEmitEnabled(true) - hdec.SetMaxStringLength(fr.maxHeaderStringLen()) - hdec.SetEmitFunc(func(hf hpack.HeaderField) { - if VerboseLogs && fr.logReads { - fr.debugReadLoggerf("http2: decoded hpack field %+v", hf) - } - if !httpguts.ValidHeaderFieldValue(hf.Value) { - invalid = headerFieldValueError(hf.Value) - } - isPseudo := strings.HasPrefix(hf.Name, ":") - if isPseudo { - if sawRegular { - invalid = errPseudoAfterRegular - } - } else { - sawRegular = true - if !validWireHeaderFieldName(hf.Name) { - invalid = headerFieldNameError(hf.Name) - } - } - - if invalid != nil { - hdec.SetEmitEnabled(false) - return - } - - size := hf.Size() - if size > remainSize { - hdec.SetEmitEnabled(false) - mh.Truncated = true - return - } - remainSize -= size - - mh.Fields = append(mh.Fields, hf) - }) - // Lose reference to MetaHeadersFrame: - defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {}) - - var hc headersOrContinuation = hf - for { - frag := hc.HeaderBlockFragment() - if _, err := hdec.Write(frag); err != nil { - return nil, ConnectionError(ErrCodeCompression) - } - - if hc.HeadersEnded() { - break - } - if f, err := fr.ReadFrame(); err != nil { - return nil, err - } else { - hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder - } - } - - mh.HeadersFrame.headerFragBuf = nil - mh.HeadersFrame.invalidate() - - if err := hdec.Close(); err != nil { - return nil, ConnectionError(ErrCodeCompression) - } - if invalid != nil { - fr.errDetail = invalid - if VerboseLogs { - log.Printf("http2: invalid header: %v", invalid) - } - return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid} - } - if err := mh.checkPseudos(); err != nil { - fr.errDetail = err - if VerboseLogs { - log.Printf("http2: invalid pseudo headers: %v", err) - } - return nil, StreamError{mh.StreamID, ErrCodeProtocol, err} - } - return mh, nil -} - -func summarizeFrame(f Frame) string { - var buf bytes.Buffer - f.Header().writeDebug(&buf) - switch f := f.(type) { - case *SettingsFrame: - n := 0 - f.ForeachSetting(func(s Setting) error { - n++ - if n == 1 { - buf.WriteString(", settings:") - } - fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val) - return nil - }) - if n > 0 { - buf.Truncate(buf.Len() - 1) // remove trailing comma - } - case *DataFrame: - data := f.Data() - const max = 256 - if len(data) > max { - data = data[:max] - } - fmt.Fprintf(&buf, " data=%q", data) - if len(f.Data()) > max { - fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max) - } - case *WindowUpdateFrame: - if f.StreamID == 0 { - buf.WriteString(" (conn)") - } - fmt.Fprintf(&buf, " incr=%v", f.Increment) - case *PingFrame: - fmt.Fprintf(&buf, " ping=%q", f.Data[:]) - case *GoAwayFrame: - fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q", - f.LastStreamID, f.ErrCode, f.debugData) - case *RSTStreamFrame: - fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode) - } - return buf.String() -} diff --git a/examples/golang.org/x/net/http2/frame_test.go b/examples/golang.org/x/net/http2/frame_test.go deleted file mode 100644 index 37266bc..0000000 --- a/examples/golang.org/x/net/http2/frame_test.go +++ /dev/null @@ -1,1191 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" - "testing" - "unsafe" - - "golang.org/x/net/http2/hpack" -) - -func testFramer() (*Framer, *bytes.Buffer) { - buf := new(bytes.Buffer) - return NewFramer(buf, buf), buf -} - -func TestFrameSizes(t *testing.T) { - // Catch people rearranging the FrameHeader fields. - if got, want := int(unsafe.Sizeof(FrameHeader{})), 12; got != want { - t.Errorf("FrameHeader size = %d; want %d", got, want) - } -} - -func TestFrameTypeString(t *testing.T) { - tests := []struct { - ft FrameType - want string - }{ - {FrameData, "DATA"}, - {FramePing, "PING"}, - {FrameGoAway, "GOAWAY"}, - {0xf, "UNKNOWN_FRAME_TYPE_15"}, - } - - for i, tt := range tests { - got := tt.ft.String() - if got != tt.want { - t.Errorf("%d. String(FrameType %d) = %q; want %q", i, int(tt.ft), got, tt.want) - } - } -} - -func TestWriteRST(t *testing.T) { - fr, buf := testFramer() - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - var errCode uint32 = 7<<24 + 6<<16 + 5<<8 + 4 - fr.WriteRSTStream(streamID, ErrCode(errCode)) - const wantEnc = "\x00\x00\x04\x03\x00\x01\x02\x03\x04\x07\x06\x05\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &RSTStreamFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x3, - Flags: 0x0, - Length: 0x4, - StreamID: 0x1020304, - }, - ErrCode: 0x7060504, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestWriteData(t *testing.T) { - fr, buf := testFramer() - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - data := []byte("ABC") - fr.WriteData(streamID, true, data) - const wantEnc = "\x00\x00\x03\x00\x01\x01\x02\x03\x04ABC" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - df, ok := f.(*DataFrame) - if !ok { - t.Fatalf("got %T; want *DataFrame", f) - } - if !bytes.Equal(df.Data(), data) { - t.Errorf("got %q; want %q", df.Data(), data) - } - if f.Header().Flags&1 == 0 { - t.Errorf("didn't see END_STREAM flag") - } -} - -func TestWriteDataPadded(t *testing.T) { - tests := [...]struct { - streamID uint32 - endStream bool - data []byte - pad []byte - wantHeader FrameHeader - }{ - // Unpadded: - 0: { - streamID: 1, - endStream: true, - data: []byte("foo"), - pad: nil, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataEndStream, - Length: 3, - StreamID: 1, - }, - }, - - // Padded bit set, but no padding: - 1: { - streamID: 1, - endStream: true, - data: []byte("foo"), - pad: []byte{}, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataEndStream | FlagDataPadded, - Length: 4, - StreamID: 1, - }, - }, - - // Padded bit set, with padding: - 2: { - streamID: 1, - endStream: false, - data: []byte("foo"), - pad: []byte{0, 0, 0}, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataPadded, - Length: 7, - StreamID: 1, - }, - }, - } - for i, tt := range tests { - fr, _ := testFramer() - fr.WriteDataPadded(tt.streamID, tt.endStream, tt.data, tt.pad) - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("%d. ReadFrame: %v", i, err) - continue - } - got := f.Header() - tt.wantHeader.valid = true - if got != tt.wantHeader { - t.Errorf("%d. read %+v; want %+v", i, got, tt.wantHeader) - continue - } - df := f.(*DataFrame) - if !bytes.Equal(df.Data(), tt.data) { - t.Errorf("%d. got %q; want %q", i, df.Data(), tt.data) - } - } -} - -func TestWriteHeaders(t *testing.T) { - tests := []struct { - name string - p HeadersFrameParam - wantEnc string - wantFrame *HeadersFrame - }{ - { - "basic", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - Priority: PriorityParam{}, - }, - "\x00\x00\x03\x01\x00\x00\x00\x00*abc", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Length: uint32(len("abc")), - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "basic + end flags", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - Priority: PriorityParam{}, - }, - "\x00\x00\x03\x01\x05\x00\x00\x00*abc", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders, - Length: uint32(len("abc")), - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "with padding", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 5, - Priority: PriorityParam{}, - }, - "\x00\x00\t\x01\r\x00\x00\x00*\x05abc\x00\x00\x00\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded, - Length: uint32(1 + len("abc") + 5), // pad length + contents + padding - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "with priority", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 2, - Priority: PriorityParam{ - StreamDep: 15, - Exclusive: true, - Weight: 127, - }, - }, - "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x0f\u007fabc\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, - Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding - }, - Priority: PriorityParam{ - StreamDep: 15, - Exclusive: true, - Weight: 127, - }, - headerFragBuf: []byte("abc"), - }, - }, - { - "with priority stream dep zero", // golang.org/issue/15444 - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 2, - Priority: PriorityParam{ - StreamDep: 0, - Exclusive: true, - Weight: 127, - }, - }, - "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x00\u007fabc\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, - Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding - }, - Priority: PriorityParam{ - StreamDep: 0, - Exclusive: true, - Weight: 127, - }, - headerFragBuf: []byte("abc"), - }, - }, - } - for _, tt := range tests { - fr, buf := testFramer() - if err := fr.WriteHeaders(tt.p); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - if buf.String() != tt.wantEnc { - t.Errorf("test %q: encoded %q; want %q", tt.name, buf.Bytes(), tt.wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWriteInvalidStreamDep(t *testing.T) { - fr, _ := testFramer() - err := fr.WriteHeaders(HeadersFrameParam{ - StreamID: 42, - Priority: PriorityParam{ - StreamDep: 1 << 31, - }, - }) - if err != errDepStreamID { - t.Errorf("header error = %v; want %q", err, errDepStreamID) - } - - err = fr.WritePriority(2, PriorityParam{StreamDep: 1 << 31}) - if err != errDepStreamID { - t.Errorf("priority error = %v; want %q", err, errDepStreamID) - } -} - -func TestWriteContinuation(t *testing.T) { - const streamID = 42 - tests := []struct { - name string - end bool - frag []byte - - wantFrame *ContinuationFrame - }{ - { - "not end", - false, - []byte("abc"), - &ContinuationFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: streamID, - Type: FrameContinuation, - Length: uint32(len("abc")), - }, - headerFragBuf: []byte("abc"), - }, - }, - { - "end", - true, - []byte("def"), - &ContinuationFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: streamID, - Type: FrameContinuation, - Flags: FlagContinuationEndHeaders, - Length: uint32(len("def")), - }, - headerFragBuf: []byte("def"), - }, - }, - } - for _, tt := range tests { - fr, _ := testFramer() - if err := fr.WriteContinuation(streamID, tt.end, tt.frag); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - fr.AllowIllegalReads = true - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWritePriority(t *testing.T) { - const streamID = 42 - tests := []struct { - name string - priority PriorityParam - wantFrame *PriorityFrame - }{ - { - "not exclusive", - PriorityParam{ - StreamDep: 2, - Exclusive: false, - Weight: 127, - }, - &PriorityFrame{ - FrameHeader{ - valid: true, - StreamID: streamID, - Type: FramePriority, - Length: 5, - }, - PriorityParam{ - StreamDep: 2, - Exclusive: false, - Weight: 127, - }, - }, - }, - - { - "exclusive", - PriorityParam{ - StreamDep: 3, - Exclusive: true, - Weight: 77, - }, - &PriorityFrame{ - FrameHeader{ - valid: true, - StreamID: streamID, - Type: FramePriority, - Length: 5, - }, - PriorityParam{ - StreamDep: 3, - Exclusive: true, - Weight: 77, - }, - }, - }, - } - for _, tt := range tests { - fr, _ := testFramer() - if err := fr.WritePriority(streamID, tt.priority); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWriteSettings(t *testing.T) { - fr, buf := testFramer() - settings := []Setting{{1, 2}, {3, 4}} - fr.WriteSettings(settings...) - const wantEnc = "\x00\x00\f\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00\x00\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - t.Fatalf("Got a %T; want a SettingsFrame", f) - } - var got []Setting - sf.ForeachSetting(func(s Setting) error { - got = append(got, s) - valBack, ok := sf.Value(s.ID) - if !ok || valBack != s.Val { - t.Errorf("Value(%d) = %v, %v; want %v, true", s.ID, valBack, ok, s.Val) - } - return nil - }) - if !reflect.DeepEqual(settings, got) { - t.Errorf("Read settings %+v != written settings %+v", got, settings) - } -} - -func TestWriteSettingsAck(t *testing.T) { - fr, buf := testFramer() - fr.WriteSettingsAck() - const wantEnc = "\x00\x00\x00\x04\x01\x00\x00\x00\x00" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } -} - -func TestWriteWindowUpdate(t *testing.T) { - fr, buf := testFramer() - const streamID = 1<<24 + 2<<16 + 3<<8 + 4 - const incr = 7<<24 + 6<<16 + 5<<8 + 4 - if err := fr.WriteWindowUpdate(streamID, incr); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\x04\x08\x00\x01\x02\x03\x04\x07\x06\x05\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &WindowUpdateFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x8, - Flags: 0x0, - Length: 0x4, - StreamID: 0x1020304, - }, - Increment: 0x7060504, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestWritePing(t *testing.T) { testWritePing(t, false) } -func TestWritePingAck(t *testing.T) { testWritePing(t, true) } - -func testWritePing(t *testing.T, ack bool) { - fr, buf := testFramer() - if err := fr.WritePing(ack, [8]byte{1, 2, 3, 4, 5, 6, 7, 8}); err != nil { - t.Fatal(err) - } - var wantFlags Flags - if ack { - wantFlags = FlagPingAck - } - var wantEnc = "\x00\x00\x08\x06" + string(wantFlags) + "\x00\x00\x00\x00" + "\x01\x02\x03\x04\x05\x06\x07\x08" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &PingFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x6, - Flags: wantFlags, - Length: 0x8, - StreamID: 0, - }, - Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestReadFrameHeader(t *testing.T) { - tests := []struct { - in string - want FrameHeader - }{ - {in: "\x00\x00\x00" + "\x00" + "\x00" + "\x00\x00\x00\x00", want: FrameHeader{}}, - {in: "\x01\x02\x03" + "\x04" + "\x05" + "\x06\x07\x08\x09", want: FrameHeader{ - Length: 66051, Type: 4, Flags: 5, StreamID: 101124105, - }}, - // Ignore high bit: - {in: "\xff\xff\xff" + "\xff" + "\xff" + "\xff\xff\xff\xff", want: FrameHeader{ - Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, - {in: "\xff\xff\xff" + "\xff" + "\xff" + "\x7f\xff\xff\xff", want: FrameHeader{ - Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, - } - for i, tt := range tests { - got, err := readFrameHeader(make([]byte, 9), strings.NewReader(tt.in)) - if err != nil { - t.Errorf("%d. readFrameHeader(%q) = %v", i, tt.in, err) - continue - } - tt.want.valid = true - if got != tt.want { - t.Errorf("%d. readFrameHeader(%q) = %+v; want %+v", i, tt.in, got, tt.want) - } - } -} - -func TestReadWriteFrameHeader(t *testing.T) { - tests := []struct { - len uint32 - typ FrameType - flags Flags - streamID uint32 - }{ - {len: 0, typ: 255, flags: 1, streamID: 0}, - {len: 0, typ: 255, flags: 1, streamID: 1}, - {len: 0, typ: 255, flags: 1, streamID: 255}, - {len: 0, typ: 255, flags: 1, streamID: 256}, - {len: 0, typ: 255, flags: 1, streamID: 65535}, - {len: 0, typ: 255, flags: 1, streamID: 65536}, - - {len: 0, typ: 1, flags: 255, streamID: 1}, - {len: 255, typ: 1, flags: 255, streamID: 1}, - {len: 256, typ: 1, flags: 255, streamID: 1}, - {len: 65535, typ: 1, flags: 255, streamID: 1}, - {len: 65536, typ: 1, flags: 255, streamID: 1}, - {len: 16777215, typ: 1, flags: 255, streamID: 1}, - } - for _, tt := range tests { - fr, buf := testFramer() - fr.startWrite(tt.typ, tt.flags, tt.streamID) - fr.writeBytes(make([]byte, tt.len)) - fr.endWrite() - fh, err := ReadFrameHeader(buf) - if err != nil { - t.Errorf("ReadFrameHeader(%+v) = %v", tt, err) - continue - } - if fh.Type != tt.typ || fh.Flags != tt.flags || fh.Length != tt.len || fh.StreamID != tt.streamID { - t.Errorf("ReadFrameHeader(%+v) = %+v; mismatch", tt, fh) - } - } - -} - -func TestWriteTooLargeFrame(t *testing.T) { - fr, _ := testFramer() - fr.startWrite(0, 1, 1) - fr.writeBytes(make([]byte, 1<<24)) - err := fr.endWrite() - if err != ErrFrameTooLarge { - t.Errorf("endWrite = %v; want errFrameTooLarge", err) - } -} - -func TestWriteGoAway(t *testing.T) { - const debug = "foo" - fr, buf := testFramer() - if err := fr.WriteGoAway(0x01020304, 0x05060708, []byte(debug)); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\v\a\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08" + debug - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &GoAwayFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x7, - Flags: 0, - Length: uint32(4 + 4 + len(debug)), - StreamID: 0, - }, - LastStreamID: 0x01020304, - ErrCode: 0x05060708, - debugData: []byte(debug), - } - if !reflect.DeepEqual(f, want) { - t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) - } - if got := string(f.(*GoAwayFrame).DebugData()); got != debug { - t.Errorf("debug data = %q; want %q", got, debug) - } -} - -func TestWritePushPromise(t *testing.T) { - pp := PushPromiseParam{ - StreamID: 42, - PromiseID: 42, - BlockFragment: []byte("abc"), - } - fr, buf := testFramer() - if err := fr.WritePushPromise(pp); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\x07\x05\x00\x00\x00\x00*\x00\x00\x00*abc" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - _, ok := f.(*PushPromiseFrame) - if !ok { - t.Fatalf("got %T; want *PushPromiseFrame", f) - } - want := &PushPromiseFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x5, - Flags: 0x0, - Length: 0x7, - StreamID: 42, - }, - PromiseID: 42, - headerFragBuf: []byte("abc"), - } - if !reflect.DeepEqual(f, want) { - t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) - } -} - -// test checkFrameOrder and that HEADERS and CONTINUATION frames can't be intermingled. -func TestReadFrameOrder(t *testing.T) { - head := func(f *Framer, id uint32, end bool) { - f.WriteHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: []byte("foo"), // unused, but non-empty - EndHeaders: end, - }) - } - cont := func(f *Framer, id uint32, end bool) { - f.WriteContinuation(id, end, []byte("foo")) - } - - tests := [...]struct { - name string - w func(*Framer) - atLeast int - wantErr string - }{ - 0: { - w: func(f *Framer) { - head(f, 1, true) - }, - }, - 1: { - w: func(f *Framer) { - head(f, 1, true) - head(f, 2, true) - }, - }, - 2: { - wantErr: "got HEADERS for stream 2; expected CONTINUATION following HEADERS for stream 1", - w: func(f *Framer) { - head(f, 1, false) - head(f, 2, true) - }, - }, - 3: { - wantErr: "got DATA for stream 1; expected CONTINUATION following HEADERS for stream 1", - w: func(f *Framer) { - head(f, 1, false) - }, - }, - 4: { - w: func(f *Framer) { - head(f, 1, false) - cont(f, 1, true) - head(f, 2, true) - }, - }, - 5: { - wantErr: "got CONTINUATION for stream 2; expected stream 1", - w: func(f *Framer) { - head(f, 1, false) - cont(f, 2, true) - head(f, 2, true) - }, - }, - 6: { - wantErr: "unexpected CONTINUATION for stream 1", - w: func(f *Framer) { - cont(f, 1, true) - }, - }, - 7: { - wantErr: "unexpected CONTINUATION for stream 1", - w: func(f *Framer) { - cont(f, 1, false) - }, - }, - 8: { - wantErr: "HEADERS frame with stream ID 0", - w: func(f *Framer) { - head(f, 0, true) - }, - }, - 9: { - wantErr: "CONTINUATION frame with stream ID 0", - w: func(f *Framer) { - cont(f, 0, true) - }, - }, - 10: { - wantErr: "unexpected CONTINUATION for stream 1", - atLeast: 5, - w: func(f *Framer) { - head(f, 1, false) - cont(f, 1, false) - cont(f, 1, false) - cont(f, 1, false) - cont(f, 1, true) - cont(f, 1, false) - }, - }, - } - for i, tt := range tests { - buf := new(bytes.Buffer) - f := NewFramer(buf, buf) - f.AllowIllegalWrites = true - tt.w(f) - f.WriteData(1, true, nil) // to test transition away from last step - - var err error - n := 0 - var log bytes.Buffer - for { - var got Frame - got, err = f.ReadFrame() - fmt.Fprintf(&log, " read %v, %v\n", got, err) - if err != nil { - break - } - n++ - } - if err == io.EOF { - err = nil - } - ok := tt.wantErr == "" - if ok && err != nil { - t.Errorf("%d. after %d good frames, ReadFrame = %v; want success\n%s", i, n, err, log.Bytes()) - continue - } - if !ok && err != ConnectionError(ErrCodeProtocol) { - t.Errorf("%d. after %d good frames, ReadFrame = %v; want ConnectionError(ErrCodeProtocol)\n%s", i, n, err, log.Bytes()) - continue - } - if !((f.errDetail == nil && tt.wantErr == "") || (fmt.Sprint(f.errDetail) == tt.wantErr)) { - t.Errorf("%d. framer eror = %q; want %q\n%s", i, f.errDetail, tt.wantErr, log.Bytes()) - } - if n < tt.atLeast { - t.Errorf("%d. framer only read %d frames; want at least %d\n%s", i, n, tt.atLeast, log.Bytes()) - } - } -} - -func TestMetaFrameHeader(t *testing.T) { - write := func(f *Framer, frags ...[]byte) { - for i, frag := range frags { - end := (i == len(frags)-1) - if i == 0 { - f.WriteHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: frag, - EndHeaders: end, - }) - } else { - f.WriteContinuation(1, end, frag) - } - } - } - - want := func(flags Flags, length uint32, pairs ...string) *MetaHeadersFrame { - mh := &MetaHeadersFrame{ - HeadersFrame: &HeadersFrame{ - FrameHeader: FrameHeader{ - Type: FrameHeaders, - Flags: flags, - Length: length, - StreamID: 1, - }, - }, - Fields: []hpack.HeaderField(nil), - } - for len(pairs) > 0 { - mh.Fields = append(mh.Fields, hpack.HeaderField{ - Name: pairs[0], - Value: pairs[1], - }) - pairs = pairs[2:] - } - return mh - } - truncated := func(mh *MetaHeadersFrame) *MetaHeadersFrame { - mh.Truncated = true - return mh - } - - const noFlags Flags = 0 - - oneKBString := strings.Repeat("a", 1<<10) - - tests := [...]struct { - name string - w func(*Framer) - want interface{} // *MetaHeaderFrame or error - wantErrReason string - maxHeaderListSize uint32 - }{ - 0: { - name: "single_headers", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/") - write(f, all) - }, - want: want(FlagHeadersEndHeaders, 2, ":method", "GET", ":path", "/"), - }, - 1: { - name: "with_continuation", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") - write(f, all[:1], all[1:]) - }, - want: want(noFlags, 1, ":method", "GET", ":path", "/", "foo", "bar"), - }, - 2: { - name: "with_two_continuation", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") - write(f, all[:2], all[2:4], all[4:]) - }, - want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", "bar"), - }, - 3: { - name: "big_string_okay", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) - write(f, all[:2], all[2:]) - }, - want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", oneKBString), - }, - 4: { - name: "big_string_error", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) - write(f, all[:2], all[2:]) - }, - maxHeaderListSize: (1 << 10) / 2, - want: ConnectionError(ErrCodeCompression), - }, - 5: { - name: "max_header_list_truncated", - w: func(f *Framer) { - var he hpackEncoder - var pairs = []string{":method", "GET", ":path", "/"} - for i := 0; i < 100; i++ { - pairs = append(pairs, "foo", "bar") - } - all := he.encodeHeaderRaw(t, pairs...) - write(f, all[:2], all[2:]) - }, - maxHeaderListSize: (1 << 10) / 2, - want: truncated(want(noFlags, 2, - ":method", "GET", - ":path", "/", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", // 11 - )), - }, - 6: { - name: "pseudo_order", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - "foo", "bar", - ":path", "/", // bogus - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "pseudo header field after regular", - }, - 7: { - name: "pseudo_unknown", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":unknown", "foo", // bogus - "foo", "bar", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid pseudo-header \":unknown\"", - }, - 8: { - name: "pseudo_mix_request_response", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - ":status", "100", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "mix of request and response pseudo headers", - }, - 9: { - name: "pseudo_dup", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - ":method", "POST", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "duplicate pseudo-header \":method\"", - }, - 10: { - name: "trailer_okay_no_pseudo", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "foo", "bar")) }, - want: want(FlagHeadersEndHeaders, 8, "foo", "bar"), - }, - 11: { - name: "invalid_field_name", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "CapitalBad", "x")) }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid header field name \"CapitalBad\"", - }, - 12: { - name: "invalid_field_value", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "key", "bad_null\x00")) }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid header field value \"bad_null\\x00\"", - }, - } - for i, tt := range tests { - buf := new(bytes.Buffer) - f := NewFramer(buf, buf) - f.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) - f.MaxHeaderListSize = tt.maxHeaderListSize - tt.w(f) - - name := tt.name - if name == "" { - name = fmt.Sprintf("test index %d", i) - } - - var got interface{} - var err error - got, err = f.ReadFrame() - if err != nil { - got = err - - // Ignore the StreamError.Cause field, if it matches the wantErrReason. - // The test table above predates the Cause field. - if se, ok := err.(StreamError); ok && se.Cause != nil && se.Cause.Error() == tt.wantErrReason { - se.Cause = nil - got = se - } - } - if !reflect.DeepEqual(got, tt.want) { - if mhg, ok := got.(*MetaHeadersFrame); ok { - if mhw, ok := tt.want.(*MetaHeadersFrame); ok { - hg := mhg.HeadersFrame - hw := mhw.HeadersFrame - if hg != nil && hw != nil && !reflect.DeepEqual(*hg, *hw) { - t.Errorf("%s: headers differ:\n got: %+v\nwant: %+v\n", name, *hg, *hw) - } - } - } - str := func(v interface{}) string { - if _, ok := v.(error); ok { - return fmt.Sprintf("error %v", v) - } else { - return fmt.Sprintf("value %#v", v) - } - } - t.Errorf("%s:\n got: %v\nwant: %s", name, str(got), str(tt.want)) - } - if tt.wantErrReason != "" && tt.wantErrReason != fmt.Sprint(f.errDetail) { - t.Errorf("%s: got error reason %q; want %q", name, f.errDetail, tt.wantErrReason) - } - } -} - -func TestSetReuseFrames(t *testing.T) { - fr, buf := testFramer() - fr.SetReuseFrames() - - // Check that DataFrames are reused. Note that - // SetReuseFrames only currently implements reuse of DataFrames. - firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("", 0, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("HHH", 3, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } -} - -func TestSetReuseFramesMoreThanOnce(t *testing.T) { - fr, buf := testFramer() - fr.SetReuseFrames() - - firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) - fr.SetReuseFrames() - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - // SetReuseFrames should be idempotent - fr.SetReuseFrames() - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } -} - -func TestNoSetReuseFrames(t *testing.T) { - fr, buf := testFramer() - const numNewDataFrames = 10 - dfSoFar := make([]interface{}, numNewDataFrames) - - // Check that DataFrames are not reused if SetReuseFrames wasn't called. - // SetReuseFrames only currently implements reuse of DataFrames. - for i := 0; i < numNewDataFrames; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - for _, item := range dfSoFar { - if df == item { - t.Errorf("Expected Framer to return new DataFrames since SetNoReuseFrames not set.") - } - } - dfSoFar[i] = df - } -} - -func readAndVerifyDataFrame(data string, length byte, fr *Framer, buf *bytes.Buffer, t *testing.T) *DataFrame { - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - fr.WriteData(streamID, true, []byte(data)) - wantEnc := "\x00\x00" + string(length) + "\x00\x01\x01\x02\x03\x04" + data - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - df, ok := f.(*DataFrame) - if !ok { - t.Fatalf("got %T; want *DataFrame", f) - } - if !bytes.Equal(df.Data(), []byte(data)) { - t.Errorf("got %q; want %q", df.Data(), []byte(data)) - } - if f.Header().Flags&1 == 0 { - t.Errorf("didn't see END_STREAM flag") - } - return df -} - -func encodeHeaderRaw(t *testing.T, pairs ...string) []byte { - var he hpackEncoder - return he.encodeHeaderRaw(t, pairs...) -} diff --git a/examples/golang.org/x/net/http2/go111.go b/examples/golang.org/x/net/http2/go111.go deleted file mode 100644 index 9749dc0..0000000 --- a/examples/golang.org/x/net/http2/go111.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.11 - -package http2 - -import "net/textproto" - -func traceHasWroteHeaderField(trace *clientTrace) bool { - return trace != nil && trace.WroteHeaderField != nil -} - -func traceWroteHeaderField(trace *clientTrace, k, v string) { - if trace != nil && trace.WroteHeaderField != nil { - trace.WroteHeaderField(k, []string{v}) - } -} - -func traceGot1xxResponseFunc(trace *clientTrace) func(int, textproto.MIMEHeader) error { - if trace != nil { - return trace.Got1xxResponse - } - return nil -} diff --git a/examples/golang.org/x/net/http2/go16.go b/examples/golang.org/x/net/http2/go16.go deleted file mode 100644 index 00b2e9e..0000000 --- a/examples/golang.org/x/net/http2/go16.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.6 - -package http2 - -import ( - "net/http" - "time" -) - -func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { - return t1.ExpectContinueTimeout -} diff --git a/examples/golang.org/x/net/http2/go17.go b/examples/golang.org/x/net/http2/go17.go deleted file mode 100644 index d957b7b..0000000 --- a/examples/golang.org/x/net/http2/go17.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package http2 - -import ( - "context" - "net" - "net/http" - "net/http/httptrace" - "time" -) - -type contextContext interface { - context.Context -} - -var errCanceled = context.Canceled - -func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { - ctx, cancel = context.WithCancel(context.Background()) - ctx = context.WithValue(ctx, http.LocalAddrContextKey, c.LocalAddr()) - if hs := opts.baseConfig(); hs != nil { - ctx = context.WithValue(ctx, http.ServerContextKey, hs) - } - return -} - -func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { - return context.WithCancel(ctx) -} - -func requestWithContext(req *http.Request, ctx contextContext) *http.Request { - return req.WithContext(ctx) -} - -type clientTrace httptrace.ClientTrace - -func reqContext(r *http.Request) context.Context { return r.Context() } - -func (t *Transport) idleConnTimeout() time.Duration { - if t.t1 != nil { - return t.t1.IdleConnTimeout - } - return 0 -} - -func setResponseUncompressed(res *http.Response) { res.Uncompressed = true } - -func traceGetConn(req *http.Request, hostPort string) { - trace := httptrace.ContextClientTrace(req.Context()) - if trace == nil || trace.GetConn == nil { - return - } - trace.GetConn(hostPort) -} - -func traceGotConn(req *http.Request, cc *ClientConn) { - trace := httptrace.ContextClientTrace(req.Context()) - if trace == nil || trace.GotConn == nil { - return - } - ci := httptrace.GotConnInfo{Conn: cc.tconn} - cc.mu.Lock() - ci.Reused = cc.nextStreamID > 1 - ci.WasIdle = len(cc.streams) == 0 && ci.Reused - if ci.WasIdle && !cc.lastActive.IsZero() { - ci.IdleTime = time.Now().Sub(cc.lastActive) - } - cc.mu.Unlock() - - trace.GotConn(ci) -} - -func traceWroteHeaders(trace *clientTrace) { - if trace != nil && trace.WroteHeaders != nil { - trace.WroteHeaders() - } -} - -func traceGot100Continue(trace *clientTrace) { - if trace != nil && trace.Got100Continue != nil { - trace.Got100Continue() - } -} - -func traceWait100Continue(trace *clientTrace) { - if trace != nil && trace.Wait100Continue != nil { - trace.Wait100Continue() - } -} - -func traceWroteRequest(trace *clientTrace, err error) { - if trace != nil && trace.WroteRequest != nil { - trace.WroteRequest(httptrace.WroteRequestInfo{Err: err}) - } -} - -func traceFirstResponseByte(trace *clientTrace) { - if trace != nil && trace.GotFirstResponseByte != nil { - trace.GotFirstResponseByte() - } -} - -func requestTrace(req *http.Request) *clientTrace { - trace := httptrace.ContextClientTrace(req.Context()) - return (*clientTrace)(trace) -} - -// Ping sends a PING frame to the server and waits for the ack. -func (cc *ClientConn) Ping(ctx context.Context) error { - return cc.ping(ctx) -} - -// Shutdown gracefully closes the client connection, waiting for running streams to complete. -func (cc *ClientConn) Shutdown(ctx context.Context) error { - return cc.shutdown(ctx) -} diff --git a/examples/golang.org/x/net/http2/go17_not18.go b/examples/golang.org/x/net/http2/go17_not18.go deleted file mode 100644 index b4c52ec..0000000 --- a/examples/golang.org/x/net/http2/go17_not18.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7,!go1.8 - -package http2 - -import "crypto/tls" - -// temporary copy of Go 1.7's private tls.Config.clone: -func cloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/examples/golang.org/x/net/http2/go18.go b/examples/golang.org/x/net/http2/go18.go deleted file mode 100644 index 4f30d22..0000000 --- a/examples/golang.org/x/net/http2/go18.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package http2 - -import ( - "crypto/tls" - "io" - "net/http" -) - -func cloneTLSConfig(c *tls.Config) *tls.Config { - c2 := c.Clone() - c2.GetClientCertificate = c.GetClientCertificate // golang.org/issue/19264 - return c2 -} - -var _ http.Pusher = (*responseWriter)(nil) - -// Push implements http.Pusher. -func (w *responseWriter) Push(target string, opts *http.PushOptions) error { - internalOpts := pushOptions{} - if opts != nil { - internalOpts.Method = opts.Method - internalOpts.Header = opts.Header - } - return w.push(target, internalOpts) -} - -func configureServer18(h1 *http.Server, h2 *Server) error { - if h2.IdleTimeout == 0 { - if h1.IdleTimeout != 0 { - h2.IdleTimeout = h1.IdleTimeout - } else { - h2.IdleTimeout = h1.ReadTimeout - } - } - return nil -} - -func shouldLogPanic(panicValue interface{}) bool { - return panicValue != nil && panicValue != http.ErrAbortHandler -} - -func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { - return req.GetBody -} - -func reqBodyIsNoBody(body io.ReadCloser) bool { - return body == http.NoBody -} - -func go18httpNoBody() io.ReadCloser { return http.NoBody } // for tests only diff --git a/examples/golang.org/x/net/http2/go18_test.go b/examples/golang.org/x/net/http2/go18_test.go deleted file mode 100644 index 30e3b03..0000000 --- a/examples/golang.org/x/net/http2/go18_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package http2 - -import ( - "crypto/tls" - "net/http" - "testing" - "time" -) - -// Tests that http2.Server.IdleTimeout is initialized from -// http.Server.{Idle,Read}Timeout. http.Server.IdleTimeout was -// added in Go 1.8. -func TestConfigureServerIdleTimeout_Go18(t *testing.T) { - const timeout = 5 * time.Second - const notThisOne = 1 * time.Second - - // With a zero http2.Server, verify that it copies IdleTimeout: - { - s1 := &http.Server{ - IdleTimeout: timeout, - ReadTimeout: notThisOne, - } - s2 := &Server{} - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } - - // And that it falls back to ReadTimeout: - { - s1 := &http.Server{ - ReadTimeout: timeout, - } - s2 := &Server{} - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } - - // Verify that s1's IdleTimeout doesn't overwrite an existing setting: - { - s1 := &http.Server{ - IdleTimeout: notThisOne, - } - s2 := &Server{ - IdleTimeout: timeout, - } - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } -} - -func TestCertClone(t *testing.T) { - c := &tls.Config{ - GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { - panic("shouldn't be called") - }, - } - c2 := cloneTLSConfig(c) - if c2.GetClientCertificate == nil { - t.Error("GetClientCertificate is nil") - } -} diff --git a/examples/golang.org/x/net/http2/go19.go b/examples/golang.org/x/net/http2/go19.go deleted file mode 100644 index 38124ba..0000000 --- a/examples/golang.org/x/net/http2/go19.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package http2 - -import ( - "net/http" -) - -func configureServer19(s *http.Server, conf *Server) error { - s.RegisterOnShutdown(conf.state.startGracefulShutdown) - return nil -} diff --git a/examples/golang.org/x/net/http2/go19_test.go b/examples/golang.org/x/net/http2/go19_test.go deleted file mode 100644 index 22b0006..0000000 --- a/examples/golang.org/x/net/http2/go19_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package http2 - -import ( - "context" - "net/http" - "reflect" - "testing" - "time" -) - -func TestServerGracefulShutdown(t *testing.T) { - var st *serverTester - handlerDone := make(chan struct{}) - st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - defer close(handlerDone) - go st.ts.Config.Shutdown(context.Background()) - - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } - if ga.LastStreamID != 1 { - t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID) - } - - w.Header().Set("x-foo", "bar") - }) - defer st.Close() - - st.greet() - st.bodylessReq1() - - select { - case <-handlerDone: - case <-time.After(5 * time.Second): - t.Fatalf("server did not shutdown?") - } - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"x-foo", "bar"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - - n, err := st.cc.Read([]byte{0}) - if n != 0 || err == nil { - t.Errorf("Read = %v, %v; want 0, non-nil", n, err) - } -} diff --git a/examples/golang.org/x/net/http2/gotrack.go b/examples/golang.org/x/net/http2/gotrack.go deleted file mode 100644 index 9933c9f..0000000 --- a/examples/golang.org/x/net/http2/gotrack.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Defensive debug-only utility to track that functions run on the -// goroutine that they're supposed to. - -package http2 - -import ( - "bytes" - "errors" - "fmt" - "os" - "runtime" - "strconv" - "sync" -) - -var DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1" - -type goroutineLock uint64 - -func newGoroutineLock() goroutineLock { - if !DebugGoroutines { - return 0 - } - return goroutineLock(curGoroutineID()) -} - -func (g goroutineLock) check() { - if !DebugGoroutines { - return - } - if curGoroutineID() != uint64(g) { - panic("running on the wrong goroutine") - } -} - -func (g goroutineLock) checkNotOn() { - if !DebugGoroutines { - return - } - if curGoroutineID() == uint64(g) { - panic("running on the wrong goroutine") - } -} - -var goroutineSpace = []byte("goroutine ") - -func curGoroutineID() uint64 { - bp := littleBuf.Get().(*[]byte) - defer littleBuf.Put(bp) - b := *bp - b = b[:runtime.Stack(b, false)] - // Parse the 4707 out of "goroutine 4707 [" - b = bytes.TrimPrefix(b, goroutineSpace) - i := bytes.IndexByte(b, ' ') - if i < 0 { - panic(fmt.Sprintf("No space found in %q", b)) - } - b = b[:i] - n, err := parseUintBytes(b, 10, 64) - if err != nil { - panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) - } - return n -} - -var littleBuf = sync.Pool{ - New: func() interface{} { - buf := make([]byte, 64) - return &buf - }, -} - -// parseUintBytes is like strconv.ParseUint, but using a []byte. -func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { - var cutoff, maxVal uint64 - - if bitSize == 0 { - bitSize = int(strconv.IntSize) - } - - s0 := s - switch { - case len(s) < 1: - err = strconv.ErrSyntax - goto Error - - case 2 <= base && base <= 36: - // valid base; nothing to do - - case base == 0: - // Look for octal, hex prefix. - switch { - case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): - base = 16 - s = s[2:] - if len(s) < 1 { - err = strconv.ErrSyntax - goto Error - } - case s[0] == '0': - base = 8 - default: - base = 10 - } - - default: - err = errors.New("invalid base " + strconv.Itoa(base)) - goto Error - } - - n = 0 - cutoff = cutoff64(base) - maxVal = 1<= base { - n = 0 - err = strconv.ErrSyntax - goto Error - } - - if n >= cutoff { - // n*base overflows - n = 1<<64 - 1 - err = strconv.ErrRange - goto Error - } - n *= uint64(base) - - n1 := n + uint64(v) - if n1 < n || n1 > maxVal { - // n+v overflows - n = 1<<64 - 1 - err = strconv.ErrRange - goto Error - } - n = n1 - } - - return n, nil - -Error: - return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} -} - -// Return the first number n such that n*base >= 1<<64. -func cutoff64(base int) uint64 { - if base < 2 { - return 0 - } - return (1<<64-1)/uint64(base) + 1 -} diff --git a/examples/golang.org/x/net/http2/gotrack_test.go b/examples/golang.org/x/net/http2/gotrack_test.go deleted file mode 100644 index 06db612..0000000 --- a/examples/golang.org/x/net/http2/gotrack_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "fmt" - "strings" - "testing" -) - -func TestGoroutineLock(t *testing.T) { - oldDebug := DebugGoroutines - DebugGoroutines = true - defer func() { DebugGoroutines = oldDebug }() - - g := newGoroutineLock() - g.check() - - sawPanic := make(chan interface{}) - go func() { - defer func() { sawPanic <- recover() }() - g.check() // should panic - }() - e := <-sawPanic - if e == nil { - t.Fatal("did not see panic from check in other goroutine") - } - if !strings.Contains(fmt.Sprint(e), "wrong goroutine") { - t.Errorf("expected on see panic about running on the wrong goroutine; got %v", e) - } -} diff --git a/examples/golang.org/x/net/http2/h2demo/.gitignore b/examples/golang.org/x/net/http2/h2demo/.gitignore deleted file mode 100644 index 8a1133f..0000000 --- a/examples/golang.org/x/net/http2/h2demo/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -h2demo -h2demo.linux -client-id.dat -client-secret.dat -token.dat -ca-certificates.crt diff --git a/examples/golang.org/x/net/http2/h2demo/Dockerfile b/examples/golang.org/x/net/http2/h2demo/Dockerfile deleted file mode 100644 index 9238673..0000000 --- a/examples/golang.org/x/net/http2/h2demo/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright 2018 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -FROM scratch -LABEL maintainer "golang-dev@googlegroups.com" - -COPY ca-certificates.crt /etc/ssl/certs/ -COPY h2demo / -ENTRYPOINT ["/h2demo", "-prod"] - diff --git a/examples/golang.org/x/net/http2/h2demo/Dockerfile.0 b/examples/golang.org/x/net/http2/h2demo/Dockerfile.0 deleted file mode 100644 index fd8435d..0000000 --- a/examples/golang.org/x/net/http2/h2demo/Dockerfile.0 +++ /dev/null @@ -1,134 +0,0 @@ -# Copyright 2018 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -FROM golang:1.9 -LABEL maintainer "golang-dev@googlegroups.com" - -ENV CGO_ENABLED=0 - -# BEGIN deps (run `make update-deps` to update) - -# Repo cloud.google.com/go at 1d0c2da (2018-01-30) -ENV REV=1d0c2da40456a9b47f5376165f275424acc15c09 -RUN go get -d cloud.google.com/go/compute/metadata `#and 6 other pkgs` &&\ - (cd /go/src/cloud.google.com/go && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo github.com/golang/protobuf at 9255415 (2018-01-25) -ENV REV=925541529c1fa6821df4e44ce2723319eb2be768 -RUN go get -d github.com/golang/protobuf/proto `#and 6 other pkgs` &&\ - (cd /go/src/github.com/golang/protobuf && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo github.com/googleapis/gax-go at 317e000 (2017-09-15) -ENV REV=317e0006254c44a0ac427cc52a0e083ff0b9622f -RUN go get -d github.com/googleapis/gax-go &&\ - (cd /go/src/github.com/googleapis/gax-go && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo go4.org at 034d17a (2017-05-25) -ENV REV=034d17a462f7b2dcd1a4a73553ec5357ff6e6c6e -RUN go get -d go4.org/syncutil/singleflight &&\ - (cd /go/src/go4.org && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo golang.org/x/build at 8aa9ee0 (2018-02-01) -ENV REV=8aa9ee0e557fd49c14113e5ba106e13a5b455460 -RUN go get -d golang.org/x/build/autocertcache &&\ - (cd /go/src/golang.org/x/build && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo golang.org/x/crypto at 1875d0a (2018-01-27) -ENV REV=1875d0a70c90e57f11972aefd42276df65e895b9 -RUN go get -d golang.org/x/crypto/acme `#and 2 other pkgs` &&\ - (cd /go/src/golang.org/x/crypto && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo golang.org/x/oauth2 at 30785a2 (2018-01-04) -ENV REV=30785a2c434e431ef7c507b54617d6a951d5f2b4 -RUN go get -d golang.org/x/oauth2 `#and 5 other pkgs` &&\ - (cd /go/src/golang.org/x/oauth2 && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo golang.org/x/text at e19ae14 (2017-12-27) -ENV REV=e19ae1496984b1c655b8044a65c0300a3c878dd3 -RUN go get -d golang.org/x/text/secure/bidirule `#and 4 other pkgs` &&\ - (cd /go/src/golang.org/x/text && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo google.golang.org/api at 7d0e2d3 (2018-01-30) -ENV REV=7d0e2d350555821bef5a5b8aecf0d12cc1def633 -RUN go get -d google.golang.org/api/gensupport `#and 9 other pkgs` &&\ - (cd /go/src/google.golang.org/api && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo google.golang.org/genproto at 4eb30f4 (2018-01-25) -ENV REV=4eb30f4778eed4c258ba66527a0d4f9ec8a36c45 -RUN go get -d google.golang.org/genproto/googleapis/api/annotations `#and 3 other pkgs` &&\ - (cd /go/src/google.golang.org/genproto && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Repo google.golang.org/grpc at 0bd008f (2018-01-25) -ENV REV=0bd008f5fadb62d228f12b18d016709e8139a7af -RUN go get -d google.golang.org/grpc `#and 23 other pkgs` &&\ - (cd /go/src/google.golang.org/grpc && (git cat-file -t $REV 2>/dev/null || git fetch -q origin $REV) && git reset --hard $REV) - -# Optimization to speed up iterative development, not necessary for correctness: -RUN go install cloud.google.com/go/compute/metadata \ - cloud.google.com/go/iam \ - cloud.google.com/go/internal \ - cloud.google.com/go/internal/optional \ - cloud.google.com/go/internal/version \ - cloud.google.com/go/storage \ - github.com/golang/protobuf/proto \ - github.com/golang/protobuf/protoc-gen-go/descriptor \ - github.com/golang/protobuf/ptypes \ - github.com/golang/protobuf/ptypes/any \ - github.com/golang/protobuf/ptypes/duration \ - github.com/golang/protobuf/ptypes/timestamp \ - github.com/googleapis/gax-go \ - go4.org/syncutil/singleflight \ - golang.org/x/build/autocertcache \ - golang.org/x/crypto/acme \ - golang.org/x/crypto/acme/autocert \ - golang.org/x/oauth2 \ - golang.org/x/oauth2/google \ - golang.org/x/oauth2/internal \ - golang.org/x/oauth2/jws \ - golang.org/x/oauth2/jwt \ - golang.org/x/text/secure/bidirule \ - golang.org/x/text/transform \ - golang.org/x/text/unicode/bidi \ - golang.org/x/text/unicode/norm \ - google.golang.org/api/gensupport \ - google.golang.org/api/googleapi \ - google.golang.org/api/googleapi/internal/uritemplates \ - google.golang.org/api/googleapi/transport \ - google.golang.org/api/internal \ - google.golang.org/api/iterator \ - google.golang.org/api/option \ - google.golang.org/api/storage/v1 \ - google.golang.org/api/transport/http \ - google.golang.org/genproto/googleapis/api/annotations \ - google.golang.org/genproto/googleapis/iam/v1 \ - google.golang.org/genproto/googleapis/rpc/status \ - google.golang.org/grpc \ - google.golang.org/grpc/balancer \ - google.golang.org/grpc/balancer/base \ - google.golang.org/grpc/balancer/roundrobin \ - google.golang.org/grpc/codes \ - google.golang.org/grpc/connectivity \ - google.golang.org/grpc/credentials \ - google.golang.org/grpc/encoding \ - google.golang.org/grpc/encoding/proto \ - google.golang.org/grpc/grpclb/grpc_lb_v1/messages \ - google.golang.org/grpc/grpclog \ - google.golang.org/grpc/internal \ - google.golang.org/grpc/keepalive \ - google.golang.org/grpc/metadata \ - google.golang.org/grpc/naming \ - google.golang.org/grpc/peer \ - google.golang.org/grpc/resolver \ - google.golang.org/grpc/resolver/dns \ - google.golang.org/grpc/resolver/passthrough \ - google.golang.org/grpc/stats \ - google.golang.org/grpc/status \ - google.golang.org/grpc/tap \ - google.golang.org/grpc/transport -# END deps - -COPY . /go/src/golang.org/x/net/ - -RUN go install -tags "h2demo netgo" -ldflags "-linkmode=external -extldflags '-static -pthread'" golang.org/x/net/http2/h2demo - diff --git a/examples/golang.org/x/net/http2/h2demo/Makefile b/examples/golang.org/x/net/http2/h2demo/Makefile deleted file mode 100644 index 306d198..0000000 --- a/examples/golang.org/x/net/http2/h2demo/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright 2018 The Go Authors. All rights reserved. -# Use of this source code is governed by a BSD-style -# license that can be found in the LICENSE file. - -MUTABLE_VERSION ?= latest -VERSION ?= $(shell git rev-parse --short HEAD) - -IMAGE_STAGING := gcr.io/go-dashboard-dev/h2demo -IMAGE_PROD := gcr.io/symbolic-datum-552/h2demo - -DOCKER_IMAGE_build0=build0/h2demo:latest -DOCKER_CTR_build0=h2demo-build0 - -build0: *.go Dockerfile.0 - docker build --force-rm -f Dockerfile.0 --tag=$(DOCKER_IMAGE_build0) ../.. - -h2demo: build0 - docker create --name $(DOCKER_CTR_build0) $(DOCKER_IMAGE_build0) - docker cp $(DOCKER_CTR_build0):/go/bin/$@ $@ - docker rm $(DOCKER_CTR_build0) - -ca-certificates.crt: - docker create --name $(DOCKER_CTR_build0) $(DOCKER_IMAGE_build0) - docker cp $(DOCKER_CTR_build0):/etc/ssl/certs/$@ $@ - docker rm $(DOCKER_CTR_build0) - -update-deps: - go install golang.org/x/build/cmd/gitlock - gitlock --update=Dockerfile.0 --ignore=golang.org/x/net --tags=h2demo golang.org/x/net/http2/h2demo - -docker-prod: Dockerfile h2demo ca-certificates.crt - docker build --force-rm --tag=$(IMAGE_PROD):$(VERSION) . - docker tag $(IMAGE_PROD):$(VERSION) $(IMAGE_PROD):$(MUTABLE_VERSION) -docker-staging: Dockerfile h2demo ca-certificates.crt - docker build --force-rm --tag=$(IMAGE_STAGING):$(VERSION) . - docker tag $(IMAGE_STAGING):$(VERSION) $(IMAGE_STAGING):$(MUTABLE_VERSION) - -push-prod: docker-prod - gcloud docker -- push $(IMAGE_PROD):$(MUTABLE_VERSION) - gcloud docker -- push $(IMAGE_PROD):$(VERSION) -push-staging: docker-staging - gcloud docker -- push $(IMAGE_STAGING):$(MUTABLE_VERSION) - gcloud docker -- push $(IMAGE_STAGING):$(VERSION) - -deploy-prod: push-prod - kubectl set image deployment/h2demo-deployment h2demo=$(IMAGE_PROD):$(VERSION) -deploy-staging: push-staging - kubectl set image deployment/h2demo-deployment h2demo=$(IMAGE_STAGING):$(VERSION) - -.PHONY: clean -clean: - $(RM) h2demo - $(RM) ca-certificates.crt - -FORCE: diff --git a/examples/golang.org/x/net/http2/h2demo/README b/examples/golang.org/x/net/http2/h2demo/README deleted file mode 100644 index 212a96f..0000000 --- a/examples/golang.org/x/net/http2/h2demo/README +++ /dev/null @@ -1,16 +0,0 @@ - -Client: - -- Firefox nightly with about:config network.http.spdy.enabled.http2draft set true - -- Chrome: go to chrome://flags/#enable-spdy4, save and restart (button at bottom) - -Make CA: -$ openssl genrsa -out rootCA.key 2048 -$ openssl req -x509 -new -nodes -key rootCA.key -days 1024 -out rootCA.pem -... install that to Firefox - -Make cert: -$ openssl genrsa -out server.key 2048 -$ openssl req -new -key server.key -out server.csr -$ openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 - - diff --git a/examples/golang.org/x/net/http2/h2demo/deployment-prod.yaml b/examples/golang.org/x/net/http2/h2demo/deployment-prod.yaml deleted file mode 100644 index a3a20a4..0000000 --- a/examples/golang.org/x/net/http2/h2demo/deployment-prod.yaml +++ /dev/null @@ -1,28 +0,0 @@ -apiVersion: extensions/v1beta1 -kind: Deployment -metadata: - name: h2demo-deployment -spec: - replicas: 1 - template: - metadata: - labels: - app: h2demo - annotations: - container.seccomp.security.alpha.kubernetes.io/h2demo: docker/default - container.apparmor.security.beta.kubernetes.io/h2demo: runtime/default - spec: - containers: - - name: h2demo - image: gcr.io/symbolic-datum-552/h2demo:latest - imagePullPolicy: Always - command: ["/h2demo", "-prod"] - ports: - - containerPort: 80 - - containerPort: 443 - resources: - requests: - cpu: "1" - memory: "1Gi" - limits: - memory: "2Gi" diff --git a/examples/golang.org/x/net/http2/h2demo/h2demo.go b/examples/golang.org/x/net/http2/h2demo/h2demo.go deleted file mode 100644 index ce842fd..0000000 --- a/examples/golang.org/x/net/http2/h2demo/h2demo.go +++ /dev/null @@ -1,543 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build h2demo - -package main - -import ( - "bytes" - "context" - "crypto/tls" - "flag" - "fmt" - "hash/crc32" - "image" - "image/jpeg" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "path" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "time" - - "cloud.google.com/go/storage" - "go4.org/syncutil/singleflight" - "golang.org/x/build/autocertcache" - "golang.org/x/crypto/acme/autocert" - "golang.org/x/net/http2" -) - -var ( - prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.") - - httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.") - httpAddr = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.") - - hostHTTP = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.") - hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.") -) - -func homeOldHTTP(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, ` - -

Go + HTTP/2

-

Welcome to the Go language's HTTP/2 demo & interop server.

-

Unfortunately, you're not using HTTP/2 right now. To do so:

-
    -
  • Use Firefox Nightly or go to about:config and enable "network.http.spdy.enabled.http2draft"
  • -
  • Use Google Chrome Canary and/or go to chrome://flags/#enable-spdy4 to Enable SPDY/4 (Chrome's name for HTTP/2)
  • -
-

See code & instructions for connecting at https://github.com/golang/net/tree/master/http2.

- -`) -} - -func home(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/" { - http.NotFound(w, r) - return - } - io.WriteString(w, ` - -

Go + HTTP/2

- -

Welcome to the Go language's HTTP/2 demo & interop server.

- -

Congratulations, you're using HTTP/2 right now.

- -

This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.

- -

-The code is at golang.org/x/net/http2 and -is used transparently by the Go standard library from Go 1.6 and later. -

- -

Contact info: bradfitz@golang.org, or file a bug.

- -

Handlers for testing

-
    -
  • GET /reqinfo to dump the request + headers received
  • -
  • GET /clockstream streams the current time every second
  • -
  • GET /gophertiles to see a page with a bunch of images
  • -
  • GET /serverpush to see a page with server push
  • -
  • GET /file/gopher.png for a small file (does If-Modified-Since, Content-Range, etc)
  • -
  • GET /file/go.src.tar.gz for a larger file (~10 MB)
  • -
  • GET /redirect to redirect back to / (this page)
  • -
  • GET /goroutines to see all active goroutines in this server
  • -
  • PUT something to /crc32 to get a count of number of bytes and its CRC-32
  • -
  • PUT something to /ECHO and it will be streamed back to you capitalized
  • -
- -`) -} - -func reqInfoHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain") - fmt.Fprintf(w, "Method: %s\n", r.Method) - fmt.Fprintf(w, "Protocol: %s\n", r.Proto) - fmt.Fprintf(w, "Host: %s\n", r.Host) - fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr) - fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI) - fmt.Fprintf(w, "URL: %#v\n", r.URL) - fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength) - fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close) - fmt.Fprintf(w, "TLS: %#v\n", r.TLS) - fmt.Fprintf(w, "\nHeaders:\n") - r.Header.Write(w) -} - -func crcHandler(w http.ResponseWriter, r *http.Request) { - if r.Method != "PUT" { - http.Error(w, "PUT required.", 400) - return - } - crc := crc32.NewIEEE() - n, err := io.Copy(crc, r.Body) - if err == nil { - w.Header().Set("Content-Type", "text/plain") - fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil)) - } -} - -type capitalizeReader struct { - r io.Reader -} - -func (cr capitalizeReader) Read(p []byte) (n int, err error) { - n, err = cr.r.Read(p) - for i, b := range p[:n] { - if b >= 'a' && b <= 'z' { - p[i] = b - ('a' - 'A') - } - } - return -} - -type flushWriter struct { - w io.Writer -} - -func (fw flushWriter) Write(p []byte) (n int, err error) { - n, err = fw.w.Write(p) - if f, ok := fw.w.(http.Flusher); ok { - f.Flush() - } - return -} - -func echoCapitalHandler(w http.ResponseWriter, r *http.Request) { - if r.Method != "PUT" { - http.Error(w, "PUT required.", 400) - return - } - io.Copy(flushWriter{w}, capitalizeReader{r.Body}) -} - -var ( - fsGrp singleflight.Group - fsMu sync.Mutex // guards fsCache - fsCache = map[string]http.Handler{} -) - -// fileServer returns a file-serving handler that proxies URL. -// It lazily fetches URL on the first access and caches its contents forever. -func fileServer(url string, latency time.Duration) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if latency > 0 { - time.Sleep(latency) - } - hi, err := fsGrp.Do(url, func() (interface{}, error) { - fsMu.Lock() - if h, ok := fsCache[url]; ok { - fsMu.Unlock() - return h, nil - } - fsMu.Unlock() - - res, err := http.Get(url) - if err != nil { - return nil, err - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - - modTime := time.Now() - var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp)) - }) - fsMu.Lock() - fsCache[url] = h - fsMu.Unlock() - return h, nil - }) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - hi.(http.Handler).ServeHTTP(w, r) - }) -} - -func clockStreamHandler(w http.ResponseWriter, r *http.Request) { - clientGone := w.(http.CloseNotifier).CloseNotify() - w.Header().Set("Content-Type", "text/plain") - ticker := time.NewTicker(1 * time.Second) - defer ticker.Stop() - fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n") - io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13)) - - for { - fmt.Fprintf(w, "%v\n", time.Now()) - w.(http.Flusher).Flush() - select { - case <-ticker.C: - case <-clientGone: - log.Printf("Client %v disconnected from the clock", r.RemoteAddr) - return - } - } -} - -func registerHandlers() { - tiles := newGopherTilesHandler() - push := newPushHandler() - - mux2 := http.NewServeMux() - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/gophertiles": - tiles.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x - return - case strings.HasPrefix(r.URL.Path, "/serverpush"): - push.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x - return - case r.TLS == nil: // do not allow HTTP/1.x for anything else - http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound) - return - } - if r.ProtoMajor == 1 { - if r.URL.Path == "/reqinfo" { - reqInfoHandler(w, r) - return - } - homeOldHTTP(w, r) - return - } - mux2.ServeHTTP(w, r) - }) - mux2.HandleFunc("/", home) - mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png", 0)) - mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz", 0)) - mux2.HandleFunc("/reqinfo", reqInfoHandler) - mux2.HandleFunc("/crc32", crcHandler) - mux2.HandleFunc("/ECHO", echoCapitalHandler) - mux2.HandleFunc("/clockstream", clockStreamHandler) - mux2.Handle("/gophertiles", tiles) - mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "/", http.StatusFound) - }) - stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`) - mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - buf := make([]byte, 2<<20) - w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil)) - }) -} - -var pushResources = map[string]http.Handler{ - "/serverpush/static/jquery.min.js": fileServer("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 100*time.Millisecond), - "/serverpush/static/godocs.js": fileServer("https://golang.org/lib/godoc/godocs.js", 100*time.Millisecond), - "/serverpush/static/playground.js": fileServer("https://golang.org/lib/godoc/playground.js", 100*time.Millisecond), - "/serverpush/static/style.css": fileServer("https://golang.org/lib/godoc/style.css", 100*time.Millisecond), -} - -func newPushHandler() http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - for path, handler := range pushResources { - if r.URL.Path == path { - handler.ServeHTTP(w, r) - return - } - } - - cacheBust := time.Now().UnixNano() - if pusher, ok := w.(http.Pusher); ok { - for path := range pushResources { - url := fmt.Sprintf("%s?%d", path, cacheBust) - if err := pusher.Push(url, nil); err != nil { - log.Printf("Failed to push %v: %v", path, err) - } - } - } - time.Sleep(100 * time.Millisecond) // fake network latency + parsing time - if err := pushTmpl.Execute(w, struct { - CacheBust int64 - HTTPSHost string - HTTPHost string - }{ - CacheBust: cacheBust, - HTTPSHost: httpsHost(), - HTTPHost: httpHost(), - }); err != nil { - log.Printf("Executing server push template: %v", err) - } - }) -} - -func newGopherTilesHandler() http.Handler { - const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg" - res, err := http.Get(gopherURL) - if err != nil { - log.Fatal(err) - } - if res.StatusCode != 200 { - log.Fatalf("Error fetching %s: %v", gopherURL, res.Status) - } - slurp, err := ioutil.ReadAll(res.Body) - res.Body.Close() - if err != nil { - log.Fatal(err) - } - im, err := jpeg.Decode(bytes.NewReader(slurp)) - if err != nil { - if len(slurp) > 1024 { - slurp = slurp[:1024] - } - log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp) - } - - type subImager interface { - SubImage(image.Rectangle) image.Image - } - const tileSize = 32 - xt := im.Bounds().Max.X / tileSize - yt := im.Bounds().Max.Y / tileSize - var tile [][][]byte // y -> x -> jpeg bytes - for yi := 0; yi < yt; yi++ { - var row [][]byte - for xi := 0; xi < xt; xi++ { - si := im.(subImager).SubImage(image.Rectangle{ - Min: image.Point{xi * tileSize, yi * tileSize}, - Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize}, - }) - buf := new(bytes.Buffer) - if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil { - log.Fatal(err) - } - row = append(row, buf.Bytes()) - } - tile = append(tile, row) - } - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ms, _ := strconv.Atoi(r.FormValue("latency")) - const nanosPerMilli = 1e6 - if r.FormValue("x") != "" { - x, _ := strconv.Atoi(r.FormValue("x")) - y, _ := strconv.Atoi(r.FormValue("y")) - if ms <= 1000 { - time.Sleep(time.Duration(ms) * nanosPerMilli) - } - if x >= 0 && x < xt && y >= 0 && y < yt { - http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x])) - return - } - } - io.WriteString(w, "") - fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:

", xt*yt) - for _, ms := range []int{0, 30, 200, 1000} { - d := time.Duration(ms) * nanosPerMilli - fmt.Fprintf(w, "[HTTP/2, %v latency] [HTTP/1, %v latency]
\n", - httpsHost(), ms, d, - httpHost(), ms, d, - ) - } - io.WriteString(w, "

\n") - cacheBust := time.Now().UnixNano() - for y := 0; y < yt; y++ { - for x := 0; x < xt; x++ { - fmt.Fprintf(w, "", - tileSize, tileSize, x, y, cacheBust, ms) - } - io.WriteString(w, "
\n") - } - io.WriteString(w, `

- -
<< Back to Go HTTP/2 demo server`) - }) -} - -func httpsHost() string { - if *hostHTTPS != "" { - return *hostHTTPS - } - if v := *httpsAddr; strings.HasPrefix(v, ":") { - return "localhost" + v - } else { - return v - } -} - -func httpHost() string { - if *hostHTTP != "" { - return *hostHTTP - } - if v := *httpAddr; strings.HasPrefix(v, ":") { - return "localhost" + v - } else { - return v - } -} - -func serveProdTLS(autocertManager *autocert.Manager) error { - srv := &http.Server{ - TLSConfig: &tls.Config{ - GetCertificate: autocertManager.GetCertificate, - }, - } - http2.ConfigureServer(srv, &http2.Server{ - NewWriteScheduler: func() http2.WriteScheduler { - return http2.NewPriorityWriteScheduler(nil) - }, - }) - ln, err := net.Listen("tcp", ":443") - if err != nil { - return err - } - return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig)) -} - -type tcpKeepAliveListener struct { - *net.TCPListener -} - -func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { - tc, err := ln.AcceptTCP() - if err != nil { - return - } - tc.SetKeepAlive(true) - tc.SetKeepAlivePeriod(3 * time.Minute) - return tc, nil -} - -func serveProd() error { - log.Printf("running in production mode") - - storageClient, err := storage.NewClient(context.Background()) - if err != nil { - log.Fatalf("storage.NewClient: %v", err) - } - autocertManager := &autocert.Manager{ - Prompt: autocert.AcceptTOS, - HostPolicy: autocert.HostWhitelist("http2.golang.org"), - Cache: autocertcache.NewGoogleCloudStorageCache(storageClient, "golang-h2demo-autocert"), - } - - errc := make(chan error, 2) - go func() { errc <- http.ListenAndServe(":80", autocertManager.HTTPHandler(http.DefaultServeMux)) }() - go func() { errc <- serveProdTLS(autocertManager) }() - return <-errc -} - -const idleTimeout = 5 * time.Minute -const activeTimeout = 10 * time.Minute - -// TODO: put this into the standard library and actually send -// PING frames and GOAWAY, etc: golang.org/issue/14204 -func idleTimeoutHook() func(net.Conn, http.ConnState) { - var mu sync.Mutex - m := map[net.Conn]*time.Timer{} - return func(c net.Conn, cs http.ConnState) { - mu.Lock() - defer mu.Unlock() - if t, ok := m[c]; ok { - delete(m, c) - t.Stop() - } - var d time.Duration - switch cs { - case http.StateNew, http.StateIdle: - d = idleTimeout - case http.StateActive: - d = activeTimeout - default: - return - } - m[c] = time.AfterFunc(d, func() { - log.Printf("closing idle conn %v after %v", c.RemoteAddr(), d) - go c.Close() - }) - } -} - -func main() { - var srv http.Server - flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.") - flag.Parse() - srv.Addr = *httpsAddr - srv.ConnState = idleTimeoutHook() - - registerHandlers() - - if *prod { - *hostHTTP = "http2.golang.org" - *hostHTTPS = "http2.golang.org" - log.Fatal(serveProd()) - } - - url := "https://" + httpsHost() + "/" - log.Printf("Listening on " + url) - http2.ConfigureServer(&srv, &http2.Server{}) - - if *httpAddr != "" { - go func() { - log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)") - log.Fatal(http.ListenAndServe(*httpAddr, nil)) - }() - } - - go func() { - log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key")) - }() - select {} -} diff --git a/examples/golang.org/x/net/http2/h2demo/launch.go b/examples/golang.org/x/net/http2/h2demo/launch.go deleted file mode 100644 index df0866a..0000000 --- a/examples/golang.org/x/net/http2/h2demo/launch.go +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "bufio" - "bytes" - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "os" - "strings" - "time" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - compute "google.golang.org/api/compute/v1" -) - -var ( - proj = flag.String("project", "symbolic-datum-552", "name of Project") - zone = flag.String("zone", "us-central1-a", "GCE zone") - mach = flag.String("machinetype", "n1-standard-1", "Machine type") - instName = flag.String("instance_name", "http2-demo", "Name of VM instance.") - sshPub = flag.String("ssh_public_key", "", "ssh public key file to authorize. Can modify later in Google's web UI anyway.") - staticIP = flag.String("static_ip", "130.211.116.44", "Static IP to use. If empty, automatic.") - - writeObject = flag.String("write_object", "", "If non-empty, a VM isn't created and the flag value is Google Cloud Storage bucket/object to write. The contents from stdin.") - publicObject = flag.Bool("write_object_is_public", false, "Whether the object created by --write_object should be public.") -) - -func readFile(v string) string { - slurp, err := ioutil.ReadFile(v) - if err != nil { - log.Fatalf("Error reading %s: %v", v, err) - } - return strings.TrimSpace(string(slurp)) -} - -var config = &oauth2.Config{ - // The client-id and secret should be for an "Installed Application" when using - // the CLI. Later we'll use a web application with a callback. - ClientID: readFile("client-id.dat"), - ClientSecret: readFile("client-secret.dat"), - Endpoint: google.Endpoint, - Scopes: []string{ - compute.DevstorageFullControlScope, - compute.ComputeScope, - "https://www.googleapis.com/auth/sqlservice", - "https://www.googleapis.com/auth/sqlservice.admin", - }, - RedirectURL: "urn:ietf:wg:oauth:2.0:oob", -} - -const baseConfig = `#cloud-config -coreos: - units: - - name: h2demo.service - command: start - content: | - [Unit] - Description=HTTP2 Demo - - [Service] - ExecStartPre=/bin/bash -c 'mkdir -p /opt/bin && curl -s -o /opt/bin/h2demo http://storage.googleapis.com/http2-demo-server-tls/h2demo && chmod +x /opt/bin/h2demo' - ExecStart=/opt/bin/h2demo --prod - RestartSec=5s - Restart=always - Type=simple - - [Install] - WantedBy=multi-user.target -` - -func main() { - flag.Parse() - if *proj == "" { - log.Fatalf("Missing --project flag") - } - prefix := "https://www.googleapis.com/compute/v1/projects/" + *proj - machType := prefix + "/zones/" + *zone + "/machineTypes/" + *mach - - const tokenFileName = "token.dat" - tokenFile := tokenCacheFile(tokenFileName) - tokenSource := oauth2.ReuseTokenSource(nil, tokenFile) - token, err := tokenSource.Token() - if err != nil { - if *writeObject != "" { - log.Fatalf("Can't use --write_object without a valid token.dat file already cached.") - } - log.Printf("Error getting token from %s: %v", tokenFileName, err) - log.Printf("Get auth code from %v", config.AuthCodeURL("my-state")) - fmt.Print("\nEnter auth code: ") - sc := bufio.NewScanner(os.Stdin) - sc.Scan() - authCode := strings.TrimSpace(sc.Text()) - token, err = config.Exchange(oauth2.NoContext, authCode) - if err != nil { - log.Fatalf("Error exchanging auth code for a token: %v", err) - } - if err := tokenFile.WriteToken(token); err != nil { - log.Fatalf("Error writing to %s: %v", tokenFileName, err) - } - tokenSource = oauth2.ReuseTokenSource(token, nil) - } - - oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource) - - if *writeObject != "" { - writeCloudStorageObject(oauthClient) - return - } - - computeService, _ := compute.New(oauthClient) - - natIP := *staticIP - if natIP == "" { - // Try to find it by name. - aggAddrList, err := computeService.Addresses.AggregatedList(*proj).Do() - if err != nil { - log.Fatal(err) - } - // http://godoc.org/code.google.com/p/google-api-go-client/compute/v1#AddressAggregatedList - IPLoop: - for _, asl := range aggAddrList.Items { - for _, addr := range asl.Addresses { - if addr.Name == *instName+"-ip" && addr.Status == "RESERVED" { - natIP = addr.Address - break IPLoop - } - } - } - } - - cloudConfig := baseConfig - if *sshPub != "" { - key := strings.TrimSpace(readFile(*sshPub)) - cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", key) - } - if os.Getenv("USER") == "bradfitz" { - cloudConfig += fmt.Sprintf("\nssh_authorized_keys:\n - %s\n", "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAwks9dwWKlRC+73gRbvYtVg0vdCwDSuIlyt4z6xa/YU/jTDynM4R4W10hm2tPjy8iR1k8XhDv4/qdxe6m07NjG/By1tkmGpm1mGwho4Pr5kbAAy/Qg+NLCSdAYnnE00FQEcFOC15GFVMOW2AzDGKisReohwH9eIzHPzdYQNPRWXE= bradfitz@papag.bradfitz.com") - } - const maxCloudConfig = 32 << 10 // per compute API docs - if len(cloudConfig) > maxCloudConfig { - log.Fatalf("cloud config length of %d bytes is over %d byte limit", len(cloudConfig), maxCloudConfig) - } - - instance := &compute.Instance{ - Name: *instName, - Description: "Go Builder", - MachineType: machType, - Disks: []*compute.AttachedDisk{instanceDisk(computeService)}, - Tags: &compute.Tags{ - Items: []string{"http-server", "https-server"}, - }, - Metadata: &compute.Metadata{ - Items: []*compute.MetadataItems{ - { - Key: "user-data", - Value: &cloudConfig, - }, - }, - }, - NetworkInterfaces: []*compute.NetworkInterface{ - { - AccessConfigs: []*compute.AccessConfig{ - { - Type: "ONE_TO_ONE_NAT", - Name: "External NAT", - NatIP: natIP, - }, - }, - Network: prefix + "/global/networks/default", - }, - }, - ServiceAccounts: []*compute.ServiceAccount{ - { - Email: "default", - Scopes: []string{ - compute.DevstorageFullControlScope, - compute.ComputeScope, - }, - }, - }, - } - - log.Printf("Creating instance...") - op, err := computeService.Instances.Insert(*proj, *zone, instance).Do() - if err != nil { - log.Fatalf("Failed to create instance: %v", err) - } - opName := op.Name - log.Printf("Created. Waiting on operation %v", opName) -OpLoop: - for { - time.Sleep(2 * time.Second) - op, err := computeService.ZoneOperations.Get(*proj, *zone, opName).Do() - if err != nil { - log.Fatalf("Failed to get op %s: %v", opName, err) - } - switch op.Status { - case "PENDING", "RUNNING": - log.Printf("Waiting on operation %v", opName) - continue - case "DONE": - if op.Error != nil { - for _, operr := range op.Error.Errors { - log.Printf("Error: %+v", operr) - } - log.Fatalf("Failed to start.") - } - log.Printf("Success. %+v", op) - break OpLoop - default: - log.Fatalf("Unknown status %q: %+v", op.Status, op) - } - } - - inst, err := computeService.Instances.Get(*proj, *zone, *instName).Do() - if err != nil { - log.Fatalf("Error getting instance after creation: %v", err) - } - ij, _ := json.MarshalIndent(inst, "", " ") - log.Printf("Instance: %s", ij) -} - -func instanceDisk(svc *compute.Service) *compute.AttachedDisk { - const imageURL = "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-stable-444-5-0-v20141016" - diskName := *instName + "-disk" - - return &compute.AttachedDisk{ - AutoDelete: true, - Boot: true, - Type: "PERSISTENT", - InitializeParams: &compute.AttachedDiskInitializeParams{ - DiskName: diskName, - SourceImage: imageURL, - DiskSizeGb: 50, - }, - } -} - -func writeCloudStorageObject(httpClient *http.Client) { - content := os.Stdin - const maxSlurp = 1 << 20 - var buf bytes.Buffer - n, err := io.CopyN(&buf, content, maxSlurp) - if err != nil && err != io.EOF { - log.Fatalf("Error reading from stdin: %v, %v", n, err) - } - contentType := http.DetectContentType(buf.Bytes()) - - req, err := http.NewRequest("PUT", "https://storage.googleapis.com/"+*writeObject, io.MultiReader(&buf, content)) - if err != nil { - log.Fatal(err) - } - req.Header.Set("x-goog-api-version", "2") - if *publicObject { - req.Header.Set("x-goog-acl", "public-read") - } - req.Header.Set("Content-Type", contentType) - res, err := httpClient.Do(req) - if err != nil { - log.Fatal(err) - } - if res.StatusCode != 200 { - res.Write(os.Stderr) - log.Fatalf("Failed.") - } - log.Printf("Success.") - os.Exit(0) -} - -type tokenCacheFile string - -func (f tokenCacheFile) Token() (*oauth2.Token, error) { - slurp, err := ioutil.ReadFile(string(f)) - if err != nil { - return nil, err - } - t := new(oauth2.Token) - if err := json.Unmarshal(slurp, t); err != nil { - return nil, err - } - return t, nil -} - -func (f tokenCacheFile) WriteToken(t *oauth2.Token) error { - jt, err := json.Marshal(t) - if err != nil { - return err - } - return ioutil.WriteFile(string(f), jt, 0600) -} diff --git a/examples/golang.org/x/net/http2/h2demo/rootCA.key b/examples/golang.org/x/net/http2/h2demo/rootCA.key deleted file mode 100644 index a15a6ab..0000000 --- a/examples/golang.org/x/net/http2/h2demo/rootCA.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSSR8Od0+9Q -62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoTZjkUygby -XDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYkJfODVGnV -mr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3mOoLb4yJ -JQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYWcaiW8LWZ -SUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABAoIBAFFHV7JMAqPWnMYA -nezY6J81v9+XN+7xABNWM2Q8uv4WdksbigGLTXR3/680Z2hXqJ7LMeC5XJACFT/e -/Gr0vmpgOCygnCPfjGehGKpavtfksXV3edikUlnCXsOP1C//c1bFL+sMYmFCVgTx -qYdDK8yKzXNGrKYT6q5YG7IglyRNV1rsQa8lM/5taFYiD1Ck/3tQi3YIq8Lcuser -hrxsMABcQ6mi+EIvG6Xr4mfJug0dGJMHG4RG1UGFQn6RXrQq2+q53fC8ZbVUSi0j -NQ918aKFzktwv+DouKU0ME4I9toks03gM860bAL7zCbKGmwR3hfgX/TqzVCWpG9E -LDVfvekCgYEA8fk9N53jbBRmULUGEf4qWypcLGiZnNU0OeXWpbPV9aa3H0VDytA7 -8fCN2dPAVDPqlthMDdVe983NCNwp2Yo8ZimDgowyIAKhdC25s1kejuaiH9OAPj3c -0f8KbriYX4n8zNHxFwK6Ae3pQ6EqOLJVCUsziUaZX9nyKY5aZlyX6xcCgYEAwjws -K62PjC64U5wYddNLp+kNdJ4edx+a7qBb3mEgPvSFT2RO3/xafJyG8kQB30Mfstjd -bRxyUV6N0vtX1zA7VQtRUAvfGCecpMo+VQZzcHXKzoRTnQ7eZg4Lmj5fQ9tOAKAo -QCVBoSW/DI4PZL26CAMDcAba4Pa22ooLapoRIQsCgYA6pIfkkbxLNkpxpt2YwLtt -Kr/590O7UaR9n6k8sW/aQBRDXNsILR1KDl2ifAIxpf9lnXgZJiwE7HiTfCAcW7c1 -nzwDCI0hWuHcMTS/NYsFYPnLsstyyjVZI3FY0h4DkYKV9Q9z3zJLQ2hz/nwoD3gy -b2pHC7giFcTts1VPV4Nt8wKBgHeFn4ihHJweg76vZz3Z78w7VNRWGFklUalVdDK7 -gaQ7w2y/ROn/146mo0OhJaXFIFRlrpvdzVrU3GDf2YXJYDlM5ZRkObwbZADjksev -WInzcgDy3KDg7WnPasRXbTfMU4t/AkW2p1QKbi3DnSVYuokDkbH2Beo45vxDxhKr -C69RAoGBAIyo3+OJenoZmoNzNJl2WPW5MeBUzSh8T/bgyjFTdqFHF5WiYRD/lfHj -x9Glyw2nutuT4hlOqHvKhgTYdDMsF2oQ72fe3v8Q5FU7FuKndNPEAyvKNXZaShVA -hnlhv5DjXKb0wFWnt5PCCiQLtzG0yyHaITrrEme7FikkIcTxaX/Y ------END RSA PRIVATE KEY----- diff --git a/examples/golang.org/x/net/http2/h2demo/rootCA.pem b/examples/golang.org/x/net/http2/h2demo/rootCA.pem deleted file mode 100644 index 3a323e7..0000000 --- a/examples/golang.org/x/net/http2/h2demo/rootCA.pem +++ /dev/null @@ -1,26 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEWjCCA0KgAwIBAgIJALfRlWsI8YQHMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNV -BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEUMBIG -A1UEChMLQnJhZGZpdHppbmMxEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsGCSqGSIb3 -DQEJARYOYnJhZEBkYW5nYS5jb20wHhcNMTQwNzE1MjA0NjA1WhcNMTcwNTA0MjA0 -NjA1WjB7MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBG -cmFuY2lzY28xFDASBgNVBAoTC0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhv -c3QxHTAbBgkqhkiG9w0BCQEWDmJyYWRAZGFuZ2EuY29tMIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEAt5fAjp4fTcekWUTfzsp0kyih1OYbsGL0KX1eRbSS -R8Od0+9Q62Hyny+GFwMTb4A/KU8mssoHvcceSAAbwfbxFK/+s51TobqUnORZrOoT -ZjkUygbyXDSK99YBbcR1Pip8vwMTm4XKuLtCigeBBdjjAQdgUO28LENGlsMnmeYk -JfODVGnVmr5Ltb9ANA8IKyTfsnHJ4iOCS/PlPbUj2q7YnoVLposUBMlgUb/CykX3 -mOoLb4yJJQyA/iST6ZxiIEj36D4yWZ5lg7YJl+UiiBQHGCnPdGyipqV06ex0heYW -caiW8LWZSUQ93jQ+WVCH8hT7DQO1dmsvUmXlq/JeAlwQ/QIDAQABo4HgMIHdMB0G -A1UdDgQWBBRcAROthS4P4U7vTfjByC569R7E6DCBrQYDVR0jBIGlMIGigBRcAROt -hS4P4U7vTfjByC569R7E6KF/pH0wezELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNB -MRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRQwEgYDVQQKEwtCcmFkZml0emluYzES -MBAGA1UEAxMJbG9jYWxob3N0MR0wGwYJKoZIhvcNAQkBFg5icmFkQGRhbmdhLmNv -bYIJALfRlWsI8YQHMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAG6h -U9f9sNH0/6oBbGGy2EVU0UgITUQIrFWo9rFkrW5k/XkDjQm+3lzjT0iGR4IxE/Ao -eU6sQhua7wrWeFEn47GL98lnCsJdD7oZNhFmQ95Tb/LnDUjs5Yj9brP0NWzXfYU4 -UK2ZnINJRcJpB8iRCaCxE8DdcUF0XqIEq6pA272snoLmiXLMvNl3kYEdm+je6voD -58SNVEUsztzQyXmJEhCpwVI0A6QCjzXj+qvpmw3ZZHi8JwXei8ZZBLTSFBki8Z7n -sH9BBH38/SzUmAN4QHSPy1gjqm00OAE8NaYDkh/bzE4d7mLGGMWp/WE3KPSu82HF -kPe6XoSbiLm/kxk32T0= ------END CERTIFICATE----- diff --git a/examples/golang.org/x/net/http2/h2demo/rootCA.srl b/examples/golang.org/x/net/http2/h2demo/rootCA.srl deleted file mode 100644 index 6db3891..0000000 --- a/examples/golang.org/x/net/http2/h2demo/rootCA.srl +++ /dev/null @@ -1 +0,0 @@ -E2CE26BF3285059C diff --git a/examples/golang.org/x/net/http2/h2demo/server.crt b/examples/golang.org/x/net/http2/h2demo/server.crt deleted file mode 100644 index c59059b..0000000 --- a/examples/golang.org/x/net/http2/h2demo/server.crt +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDPjCCAiYCCQDizia/MoUFnDANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJV -UzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xFDASBgNVBAoT -C0JyYWRmaXR6aW5jMRIwEAYDVQQDEwlsb2NhbGhvc3QxHTAbBgkqhkiG9w0BCQEW -DmJyYWRAZGFuZ2EuY29tMB4XDTE0MDcxNTIwNTAyN1oXDTE1MTEyNzIwNTAyN1ow -RzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMQswCQYDVQQHEwJTRjEeMBwGA1UE -ChMVYnJhZGZpdHogaHR0cDIgc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A -MIIBCgKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDifx2l -gZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1LmJ4c2 -dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nefb3HL -A7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55mjws -/vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/fz88 -F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABMA0GCSqGSIb3DQEBBQUAA4IB -AQC0zL+n/YpRZOdulSu9tS8FxrstXqGWoxfe+vIUgqfMZ5+0MkjJ/vW0FqlLDl2R -rn4XaR3e7FmWkwdDVbq/UB6lPmoAaFkCgh9/5oapMaclNVNnfF3fjCJfRr+qj/iD -EmJStTIN0ZuUjAlpiACmfnpEU55PafT5Zx+i1yE4FGjw8bJpFoyD4Hnm54nGjX19 -KeCuvcYFUPnBm3lcL0FalF2AjqV02WTHYNQk7YF/oeO7NKBoEgvGvKG3x+xaOeBI -dwvdq175ZsGul30h+QjrRlXhH/twcuaT3GSdoysDl9cCYE8f1Mk8PD6gan3uBCJU -90p6/CbU71bGbfpM2PHot2fm ------END CERTIFICATE----- diff --git a/examples/golang.org/x/net/http2/h2demo/server.key b/examples/golang.org/x/net/http2/h2demo/server.key deleted file mode 100644 index f329c14..0000000 --- a/examples/golang.org/x/net/http2/h2demo/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAs1Y9CyLFrdL8VQWN1WaifDqaZFnoqjHhCMlc1TfG2zA+InDi -fx2lgZD3o8FeNnAcfM2sPlk3+ZleOYw9P/CklFVDlvqmpCv9ss/BEp/dDaWvy1Lm -J4c2dbQJfmTxn7CV1H3TsVJvKdwFmdoABb41NoBp6+NNO7OtDyhbIMiCI0pL3Nef -b3HLA7hIMo3DYbORTtJLTIH9W8YKrEWL0lwHLrYFx/UdutZnv+HjdmO6vCN4na55 -mjws/vjKQUmc7xeY7Xe20xDEG2oDKVkL2eD7FfyrYMS3rO1ExP2KSqlXYG/1S9I/ -fz88F0GK7HX55b5WjZCl2J3ERVdnv/0MQv+sYQIDAQABAoIBADQ2spUwbY+bcz4p -3M66ECrNQTBggP40gYl2XyHxGGOu2xhZ94f9ELf1hjRWU2DUKWco1rJcdZClV6q3 -qwmXvcM2Q/SMS8JW0ImkNVl/0/NqPxGatEnj8zY30d/L8hGFb0orzFu/XYA5gCP4 -NbN2WrXgk3ZLeqwcNxHHtSiJWGJ/fPyeDWAu/apy75u9Xf2GlzBZmV6HYD9EfK80 -LTlI60f5FO487CrJnboL7ovPJrIHn+k05xRQqwma4orpz932rTXnTjs9Lg6KtbQN -a7PrqfAntIISgr11a66Mng3IYH1lYqJsWJJwX/xHT4WLEy0EH4/0+PfYemJekz2+ -Co62drECgYEA6O9zVJZXrLSDsIi54cfxA7nEZWm5CAtkYWeAHa4EJ+IlZ7gIf9sL -W8oFcEfFGpvwVqWZ+AsQ70dsjXAv3zXaG0tmg9FtqWp7pzRSMPidifZcQwWkKeTO -gJnFmnVyed8h6GfjTEu4gxo1/S5U0V+mYSha01z5NTnN6ltKx1Or3b0CgYEAxRgm -S30nZxnyg/V7ys61AZhst1DG2tkZXEMcA7dYhabMoXPJAP/EfhlWwpWYYUs/u0gS -Wwmf5IivX5TlYScgmkvb/NYz0u4ZmOXkLTnLPtdKKFXhjXJcHjUP67jYmOxNlJLp -V4vLRnFxTpffAV+OszzRxsXX6fvruwZBANYJeXUCgYBVouLFsFgfWGYp2rpr9XP4 -KK25kvrBqF6JKOIDB1zjxNJ3pUMKrl8oqccCFoCyXa4oTM2kUX0yWxHfleUjrMq4 -yimwQKiOZmV7fVLSSjSw6e/VfBd0h3gb82ygcplZkN0IclkwTY5SNKqwn/3y07V5 -drqdhkrgdJXtmQ6O5YYECQKBgATERcDToQ1USlI4sKrB/wyv1AlG8dg/IebiVJ4e -ZAyvcQmClFzq0qS+FiQUnB/WQw9TeeYrwGs1hxBHuJh16srwhLyDrbMvQP06qh8R -48F8UXXSRec22dV9MQphaROhu2qZdv1AC0WD3tqov6L33aqmEOi+xi8JgbT/PLk5 -c/c1AoGBAI1A/02ryksW6/wc7/6SP2M2rTy4m1sD/GnrTc67EHnRcVBdKO6qH2RY -nqC8YcveC2ZghgPTDsA3VGuzuBXpwY6wTyV99q6jxQJ6/xcrD9/NUG6Uwv/xfCxl -IJLeBYEqQundSSny3VtaAUK8Ul1nxpTvVRNwtcyWTo8RHAAyNPWd ------END RSA PRIVATE KEY----- diff --git a/examples/golang.org/x/net/http2/h2demo/service.yaml b/examples/golang.org/x/net/http2/h2demo/service.yaml deleted file mode 100644 index 2b7d541..0000000 --- a/examples/golang.org/x/net/http2/h2demo/service.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: h2demo -spec: - externalTrafficPolicy: Local - ports: - - port: 80 - targetPort: 80 - name: http - - port: 443 - targetPort: 443 - name: https - selector: - app: h2demo - type: LoadBalancer - loadBalancerIP: 130.211.116.44 diff --git a/examples/golang.org/x/net/http2/h2demo/tmpl.go b/examples/golang.org/x/net/http2/h2demo/tmpl.go deleted file mode 100644 index 504d6a7..0000000 --- a/examples/golang.org/x/net/http2/h2demo/tmpl.go +++ /dev/null @@ -1,1991 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build h2demo - -package main - -import "html/template" - -var pushTmpl = template.Must(template.New("serverpush").Parse(` - - - - - - - - - HTTP/2 Server Push Demo - - - - - - - - - -
-Note: This page exists for demonstration purposes. For the actual cmd/go docs, go to golang.org/cmd/go. -
- - - -
-... -
- - - - -
-
-
-
- Run - Format - - - -
-
- - -
-
- - -

Command go

- - - - - - - - - - - - - - -

-Go is a tool for managing Go source code. -

-

-Usage: -

-
go command [arguments]
-
-

-The commands are: -

-
build       compile packages and dependencies
-clean       remove object files
-doc         show documentation for package or symbol
-env         print Go environment information
-bug         start a bug report
-fix         run go tool fix on packages
-fmt         run gofmt on package sources
-generate    generate Go files by processing source
-get         download and install packages and dependencies
-install     compile and install packages and dependencies
-list        list packages
-run         compile and run Go program
-test        test packages
-tool        run specified go tool
-version     print Go version
-vet         run go tool vet on packages
-
-

-Use "go help [command]" for more information about a command. -

-

-Additional help topics: -

-
c           calling between Go and C
-buildmode   description of build modes
-filetype    file types
-gopath      GOPATH environment variable
-environment environment variables
-importpath  import path syntax
-packages    description of package lists
-testflag    description of testing flags
-testfunc    description of testing functions
-
-

-Use "go help [topic]" for more information about that topic. -

-

Compile packages and dependencies

-

-Usage: -

-
go build [-o output] [-i] [build flags] [packages]
-
-

-Build compiles the packages named by the import paths, -along with their dependencies, but it does not install the results. -

-

-If the arguments to build are a list of .go files, build treats -them as a list of source files specifying a single package. -

-

-When compiling a single main package, build writes -the resulting executable to an output file named after -the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe') -or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe'). -The '.exe' suffix is added when writing a Windows executable. -

-

-When compiling multiple packages or a single non-main package, -build compiles the packages but discards the resulting object, -serving only as a check that the packages can be built. -

-

-When compiling packages, build ignores files that end in '_test.go'. -

-

-The -o flag, only allowed when compiling a single package, -forces build to write the resulting executable or object -to the named output file, instead of the default behavior described -in the last two paragraphs. -

-

-The -i flag installs the packages that are dependencies of the target. -

-

-The build flags are shared by the build, clean, get, install, list, run, -and test commands: -

-
-a
-	force rebuilding of packages that are already up-to-date.
--n
-	print the commands but do not run them.
--p n
-	the number of programs, such as build commands or
-	test binaries, that can be run in parallel.
-	The default is the number of CPUs available.
--race
-	enable data race detection.
-	Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
--msan
-	enable interoperation with memory sanitizer.
-	Supported only on linux/amd64,
-	and only with Clang/LLVM as the host C compiler.
--v
-	print the names of packages as they are compiled.
--work
-	print the name of the temporary work directory and
-	do not delete it when exiting.
--x
-	print the commands.
-
--asmflags 'flag list'
-	arguments to pass on each go tool asm invocation.
--buildmode mode
-	build mode to use. See 'go help buildmode' for more.
--compiler name
-	name of compiler to use, as in runtime.Compiler (gccgo or gc).
--gccgoflags 'arg list'
-	arguments to pass on each gccgo compiler/linker invocation.
--gcflags 'arg list'
-	arguments to pass on each go tool compile invocation.
--installsuffix suffix
-	a suffix to use in the name of the package installation directory,
-	in order to keep output separate from default builds.
-	If using the -race flag, the install suffix is automatically set to race
-	or, if set explicitly, has _race appended to it.  Likewise for the -msan
-	flag.  Using a -buildmode option that requires non-default compile flags
-	has a similar effect.
--ldflags 'flag list'
-	arguments to pass on each go tool link invocation.
--linkshared
-	link against shared libraries previously created with
-	-buildmode=shared.
--pkgdir dir
-	install and load all packages from dir instead of the usual locations.
-	For example, when building with a non-standard configuration,
-	use -pkgdir to keep generated packages in a separate location.
--tags 'tag list'
-	a list of build tags to consider satisfied during the build.
-	For more information about build tags, see the description of
-	build constraints in the documentation for the go/build package.
--toolexec 'cmd args'
-	a program to use to invoke toolchain programs like vet and asm.
-	For example, instead of running asm, the go command will run
-	'cmd args /path/to/asm <arguments for asm>'.
-
-

-The list flags accept a space-separated list of strings. To embed spaces -in an element in the list, surround it with either single or double quotes. -

-

-For more about specifying packages, see 'go help packages'. -For more about where packages and binaries are installed, -run 'go help gopath'. -For more about calling between Go and C/C++, run 'go help c'. -

-

-Note: Build adheres to certain conventions such as those described -by 'go help gopath'. Not all projects can follow these conventions, -however. Installations that have their own conventions or that use -a separate software build system may choose to use lower-level -invocations such as 'go tool compile' and 'go tool link' to avoid -some of the overheads and design decisions of the build tool. -

-

-See also: go install, go get, go clean. -

-

Remove object files

-

-Usage: -

-
go clean [-i] [-r] [-n] [-x] [build flags] [packages]
-
-

-Clean removes object files from package source directories. -The go command builds most objects in a temporary directory, -so go clean is mainly concerned with object files left by other -tools or by manual invocations of go build. -

-

-Specifically, clean removes the following files from each of the -source directories corresponding to the import paths: -

-
_obj/            old object directory, left from Makefiles
-_test/           old test directory, left from Makefiles
-_testmain.go     old gotest file, left from Makefiles
-test.out         old test log, left from Makefiles
-build.out        old test log, left from Makefiles
-*.[568ao]        object files, left from Makefiles
-
-DIR(.exe)        from go build
-DIR.test(.exe)   from go test -c
-MAINFILE(.exe)   from go build MAINFILE.go
-*.so             from SWIG
-
-

-In the list, DIR represents the final path element of the -directory, and MAINFILE is the base name of any Go source -file in the directory that is not included when building -the package. -

-

-The -i flag causes clean to remove the corresponding installed -archive or binary (what 'go install' would create). -

-

-The -n flag causes clean to print the remove commands it would execute, -but not run them. -

-

-The -r flag causes clean to be applied recursively to all the -dependencies of the packages named by the import paths. -

-

-The -x flag causes clean to print remove commands as it executes them. -

-

-For more about build flags, see 'go help build'. -

-

-For more about specifying packages, see 'go help packages'. -

-

Show documentation for package or symbol

-

-Usage: -

-
go doc [-u] [-c] [package|[package.]symbol[.method]]
-
-

-Doc prints the documentation comments associated with the item identified by its -arguments (a package, const, func, type, var, or method) followed by a one-line -summary of each of the first-level items "under" that item (package-level -declarations for a package, methods for a type, etc.). -

-

-Doc accepts zero, one, or two arguments. -

-

-Given no arguments, that is, when run as -

-
go doc
-
-

-it prints the package documentation for the package in the current directory. -If the package is a command (package main), the exported symbols of the package -are elided from the presentation unless the -cmd flag is provided. -

-

-When run with one argument, the argument is treated as a Go-syntax-like -representation of the item to be documented. What the argument selects depends -on what is installed in GOROOT and GOPATH, as well as the form of the argument, -which is schematically one of these: -

-
go doc <pkg>
-go doc <sym>[.<method>]
-go doc [<pkg>.]<sym>[.<method>]
-go doc [<pkg>.][<sym>.]<method>
-
-

-The first item in this list matched by the argument is the one whose documentation -is printed. (See the examples below.) However, if the argument starts with a capital -letter it is assumed to identify a symbol or method in the current directory. -

-

-For packages, the order of scanning is determined lexically in breadth-first order. -That is, the package presented is the one that matches the search and is nearest -the root and lexically first at its level of the hierarchy. The GOROOT tree is -always scanned in its entirety before GOPATH. -

-

-If there is no package specified or matched, the package in the current -directory is selected, so "go doc Foo" shows the documentation for symbol Foo in -the current package. -

-

-The package path must be either a qualified path or a proper suffix of a -path. The go tool's usual package mechanism does not apply: package path -elements like . and ... are not implemented by go doc. -

-

-When run with two arguments, the first must be a full package path (not just a -suffix), and the second is a symbol or symbol and method; this is similar to the -syntax accepted by godoc: -

-
go doc <pkg> <sym>[.<method>]
-
-

-In all forms, when matching symbols, lower-case letters in the argument match -either case but upper-case letters match exactly. This means that there may be -multiple matches of a lower-case argument in a package if different symbols have -different cases. If this occurs, documentation for all matches is printed. -

-

-Examples: -

-
go doc
-	Show documentation for current package.
-go doc Foo
-	Show documentation for Foo in the current package.
-	(Foo starts with a capital letter so it cannot match
-	a package path.)
-go doc encoding/json
-	Show documentation for the encoding/json package.
-go doc json
-	Shorthand for encoding/json.
-go doc json.Number (or go doc json.number)
-	Show documentation and method summary for json.Number.
-go doc json.Number.Int64 (or go doc json.number.int64)
-	Show documentation for json.Number's Int64 method.
-go doc cmd/doc
-	Show package docs for the doc command.
-go doc -cmd cmd/doc
-	Show package docs and exported symbols within the doc command.
-go doc template.new
-	Show documentation for html/template's New function.
-	(html/template is lexically before text/template)
-go doc text/template.new # One argument
-	Show documentation for text/template's New function.
-go doc text/template new # Two arguments
-	Show documentation for text/template's New function.
-
-At least in the current tree, these invocations all print the
-documentation for json.Decoder's Decode method:
-
-go doc json.Decoder.Decode
-go doc json.decoder.decode
-go doc json.decode
-cd go/src/encoding/json; go doc decode
-
-

-Flags: -

-
-c
-	Respect case when matching symbols.
--cmd
-	Treat a command (package main) like a regular package.
-	Otherwise package main's exported symbols are hidden
-	when showing the package's top-level documentation.
--u
-	Show documentation for unexported as well as exported
-	symbols and methods.
-
-

Print Go environment information

-

-Usage: -

-
go env [var ...]
-
-

-Env prints Go environment information. -

-

-By default env prints information as a shell script -(on Windows, a batch file). If one or more variable -names is given as arguments, env prints the value of -each named variable on its own line. -

-

Start a bug report

-

-Usage: -

-
go bug
-
-

-Bug opens the default browser and starts a new bug report. -The report includes useful system information. -

-

Run go tool fix on packages

-

-Usage: -

-
go fix [packages]
-
-

-Fix runs the Go fix command on the packages named by the import paths. -

-

-For more about fix, see 'go doc cmd/fix'. -For more about specifying packages, see 'go help packages'. -

-

-To run fix with specific options, run 'go tool fix'. -

-

-See also: go fmt, go vet. -

-

Run gofmt on package sources

-

-Usage: -

-
go fmt [-n] [-x] [packages]
-
-

-Fmt runs the command 'gofmt -l -w' on the packages named -by the import paths. It prints the names of the files that are modified. -

-

-For more about gofmt, see 'go doc cmd/gofmt'. -For more about specifying packages, see 'go help packages'. -

-

-The -n flag prints commands that would be executed. -The -x flag prints commands as they are executed. -

-

-To run gofmt with specific options, run gofmt itself. -

-

-See also: go fix, go vet. -

-

Generate Go files by processing source

-

-Usage: -

-
go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]
-
-

-Generate runs commands described by directives within existing -files. Those commands can run any process but the intent is to -create or update Go source files. -

-

-Go generate is never run automatically by go build, go get, go test, -and so on. It must be run explicitly. -

-

-Go generate scans the file for directives, which are lines of -the form, -

-
//go:generate command argument...
-
-

-(note: no leading spaces and no space in "//go") where command -is the generator to be run, corresponding to an executable file -that can be run locally. It must either be in the shell path -(gofmt), a fully qualified path (/usr/you/bin/mytool), or a -command alias, described below. -

-

-Note that go generate does not parse the file, so lines that look -like directives in comments or multiline strings will be treated -as directives. -

-

-The arguments to the directive are space-separated tokens or -double-quoted strings passed to the generator as individual -arguments when it is run. -

-

-Quoted strings use Go syntax and are evaluated before execution; a -quoted string appears as a single argument to the generator. -

-

-Go generate sets several variables when it runs the generator: -

-
$GOARCH
-	The execution architecture (arm, amd64, etc.)
-$GOOS
-	The execution operating system (linux, windows, etc.)
-$GOFILE
-	The base name of the file.
-$GOLINE
-	The line number of the directive in the source file.
-$GOPACKAGE
-	The name of the package of the file containing the directive.
-$DOLLAR
-	A dollar sign.
-
-

-Other than variable substitution and quoted-string evaluation, no -special processing such as "globbing" is performed on the command -line. -

-

-As a last step before running the command, any invocations of any -environment variables with alphanumeric names, such as $GOFILE or -$HOME, are expanded throughout the command line. The syntax for -variable expansion is $NAME on all operating systems. Due to the -order of evaluation, variables are expanded even inside quoted -strings. If the variable NAME is not set, $NAME expands to the -empty string. -

-

-A directive of the form, -

-
//go:generate -command xxx args...
-
-

-specifies, for the remainder of this source file only, that the -string xxx represents the command identified by the arguments. This -can be used to create aliases or to handle multiword generators. -For example, -

-
//go:generate -command foo go tool foo
-
-

-specifies that the command "foo" represents the generator -"go tool foo". -

-

-Generate processes packages in the order given on the command line, -one at a time. If the command line lists .go files, they are treated -as a single package. Within a package, generate processes the -source files in a package in file name order, one at a time. Within -a source file, generate runs generators in the order they appear -in the file, one at a time. -

-

-If any generator returns an error exit status, "go generate" skips -all further processing for that package. -

-

-The generator is run in the package's source directory. -

-

-Go generate accepts one specific flag: -

-
-run=""
-	if non-empty, specifies a regular expression to select
-	directives whose full original source text (excluding
-	any trailing spaces and final newline) matches the
-	expression.
-
-

-It also accepts the standard build flags including -v, -n, and -x. -The -v flag prints the names of packages and files as they are -processed. -The -n flag prints commands that would be executed. -The -x flag prints commands as they are executed. -

-

-For more about build flags, see 'go help build'. -

-

-For more about specifying packages, see 'go help packages'. -

-

Download and install packages and dependencies

-

-Usage: -

-
go get [-d] [-f] [-fix] [-insecure] [-t] [-u] [build flags] [packages]
-
-

-Get downloads the packages named by the import paths, along with their -dependencies. It then installs the named packages, like 'go install'. -

-

-The -d flag instructs get to stop after downloading the packages; that is, -it instructs get not to install the packages. -

-

-The -f flag, valid only when -u is set, forces get -u not to verify that -each package has been checked out from the source control repository -implied by its import path. This can be useful if the source is a local fork -of the original. -

-

-The -fix flag instructs get to run the fix tool on the downloaded packages -before resolving dependencies or building the code. -

-

-The -insecure flag permits fetching from repositories and resolving -custom domains using insecure schemes such as HTTP. Use with caution. -

-

-The -t flag instructs get to also download the packages required to build -the tests for the specified packages. -

-

-The -u flag instructs get to use the network to update the named packages -and their dependencies. By default, get uses the network to check out -missing packages but does not use it to look for updates to existing packages. -

-

-The -v flag enables verbose progress and debug output. -

-

-Get also accepts build flags to control the installation. See 'go help build'. -

-

-When checking out a new package, get creates the target directory -GOPATH/src/<import-path>. If the GOPATH contains multiple entries, -get uses the first one. For more details see: 'go help gopath'. -

-

-When checking out or updating a package, get looks for a branch or tag -that matches the locally installed version of Go. The most important -rule is that if the local installation is running version "go1", get -searches for a branch or tag named "go1". If no such version exists it -retrieves the most recent version of the package. -

-

-When go get checks out or updates a Git repository, -it also updates any git submodules referenced by the repository. -

-

-Get never checks out or updates code stored in vendor directories. -

-

-For more about specifying packages, see 'go help packages'. -

-

-For more about how 'go get' finds source code to -download, see 'go help importpath'. -

-

-See also: go build, go install, go clean. -

-

Compile and install packages and dependencies

-

-Usage: -

-
go install [build flags] [packages]
-
-

-Install compiles and installs the packages named by the import paths, -along with their dependencies. -

-

-For more about the build flags, see 'go help build'. -For more about specifying packages, see 'go help packages'. -

-

-See also: go build, go get, go clean. -

-

List packages

-

-Usage: -

-
go list [-e] [-f format] [-json] [build flags] [packages]
-
-

-List lists the packages named by the import paths, one per line. -

-

-The default output shows the package import path: -

-
bytes
-encoding/json
-github.com/gorilla/mux
-golang.org/x/net/html
-
-

-The -f flag specifies an alternate format for the list, using the -syntax of package template. The default output is equivalent to -f -''. The struct being passed to the template is: -

-
type Package struct {
-    Dir           string // directory containing package sources
-    ImportPath    string // import path of package in dir
-    ImportComment string // path in import comment on package statement
-    Name          string // package name
-    Doc           string // package documentation string
-    Target        string // install path
-    Shlib         string // the shared library that contains this package (only set when -linkshared)
-    Goroot        bool   // is this package in the Go root?
-    Standard      bool   // is this package part of the standard Go library?
-    Stale         bool   // would 'go install' do anything for this package?
-    StaleReason   string // explanation for Stale==true
-    Root          string // Go root or Go path dir containing this package
-    ConflictDir   string // this directory shadows Dir in $GOPATH
-    BinaryOnly    bool   // binary-only package: cannot be recompiled from sources
-
-    // Source files
-    GoFiles        []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
-    CgoFiles       []string // .go sources files that import "C"
-    IgnoredGoFiles []string // .go sources ignored due to build constraints
-    CFiles         []string // .c source files
-    CXXFiles       []string // .cc, .cxx and .cpp source files
-    MFiles         []string // .m source files
-    HFiles         []string // .h, .hh, .hpp and .hxx source files
-    FFiles         []string // .f, .F, .for and .f90 Fortran source files
-    SFiles         []string // .s source files
-    SwigFiles      []string // .swig files
-    SwigCXXFiles   []string // .swigcxx files
-    SysoFiles      []string // .syso object files to add to archive
-    TestGoFiles    []string // _test.go files in package
-    XTestGoFiles   []string // _test.go files outside package
-
-    // Cgo directives
-    CgoCFLAGS    []string // cgo: flags for C compiler
-    CgoCPPFLAGS  []string // cgo: flags for C preprocessor
-    CgoCXXFLAGS  []string // cgo: flags for C++ compiler
-    CgoFFLAGS    []string // cgo: flags for Fortran compiler
-    CgoLDFLAGS   []string // cgo: flags for linker
-    CgoPkgConfig []string // cgo: pkg-config names
-
-    // Dependency information
-    Imports      []string // import paths used by this package
-    Deps         []string // all (recursively) imported dependencies
-    TestImports  []string // imports from TestGoFiles
-    XTestImports []string // imports from XTestGoFiles
-
-    // Error information
-    Incomplete bool            // this package or a dependency has an error
-    Error      *PackageError   // error loading package
-    DepsErrors []*PackageError // errors loading dependencies
-}
-
-

-Packages stored in vendor directories report an ImportPath that includes the -path to the vendor directory (for example, "d/vendor/p" instead of "p"), -so that the ImportPath uniquely identifies a given copy of a package. -The Imports, Deps, TestImports, and XTestImports lists also contain these -expanded imports paths. See golang.org/s/go15vendor for more about vendoring. -

-

-The error information, if any, is -

-
type PackageError struct {
-    ImportStack   []string // shortest path from package named on command line to this one
-    Pos           string   // position of error (if present, file:line:col)
-    Err           string   // the error itself
-}
-
-

-The template function "join" calls strings.Join. -

-

-The template function "context" returns the build context, defined as: -

-
type Context struct {
-	GOARCH        string   // target architecture
-	GOOS          string   // target operating system
-	GOROOT        string   // Go root
-	GOPATH        string   // Go path
-	CgoEnabled    bool     // whether cgo can be used
-	UseAllFiles   bool     // use files regardless of +build lines, file names
-	Compiler      string   // compiler to assume when computing target paths
-	BuildTags     []string // build constraints to match in +build lines
-	ReleaseTags   []string // releases the current release is compatible with
-	InstallSuffix string   // suffix to use in the name of the install dir
-}
-
-

-For more information about the meaning of these fields see the documentation -for the go/build package's Context type. -

-

-The -json flag causes the package data to be printed in JSON format -instead of using the template format. -

-

-The -e flag changes the handling of erroneous packages, those that -cannot be found or are malformed. By default, the list command -prints an error to standard error for each erroneous package and -omits the packages from consideration during the usual printing. -With the -e flag, the list command never prints errors to standard -error and instead processes the erroneous packages with the usual -printing. Erroneous packages will have a non-empty ImportPath and -a non-nil Error field; other information may or may not be missing -(zeroed). -

-

-For more about build flags, see 'go help build'. -

-

-For more about specifying packages, see 'go help packages'. -

-

Compile and run Go program

-

-Usage: -

-
go run [build flags] [-exec xprog] gofiles... [arguments...]
-
-

-Run compiles and runs the main package comprising the named Go source files. -A Go source file is defined to be a file ending in a literal ".go" suffix. -

-

-By default, 'go run' runs the compiled binary directly: 'a.out arguments...'. -If the -exec flag is given, 'go run' invokes the binary using xprog: -

-
'xprog a.out arguments...'.
-
-

-If the -exec flag is not given, GOOS or GOARCH is different from the system -default, and a program named go_$GOOS_$GOARCH_exec can be found -on the current search path, 'go run' invokes the binary using that program, -for example 'go_nacl_386_exec a.out arguments...'. This allows execution of -cross-compiled programs when a simulator or other execution method is -available. -

-

-For more about build flags, see 'go help build'. -

-

-See also: go build. -

-

Test packages

-

-Usage: -

-
go test [build/test flags] [packages] [build/test flags & test binary flags]
-
-

-'Go test' automates testing the packages named by the import paths. -It prints a summary of the test results in the format: -

-
ok   archive/tar   0.011s
-FAIL archive/zip   0.022s
-ok   compress/gzip 0.033s
-...
-
-

-followed by detailed output for each failed package. -

-

-'Go test' recompiles each package along with any files with names matching -the file pattern "*_test.go". -Files whose names begin with "_" (including "_test.go") or "." are ignored. -These additional files can contain test functions, benchmark functions, and -example functions. See 'go help testfunc' for more. -Each listed package causes the execution of a separate test binary. -

-

-Test files that declare a package with the suffix "_test" will be compiled as a -separate package, and then linked and run with the main test binary. -

-

-The go tool will ignore a directory named "testdata", making it available -to hold ancillary data needed by the tests. -

-

-By default, go test needs no arguments. It compiles and tests the package -with source in the current directory, including tests, and runs the tests. -

-

-The package is built in a temporary directory so it does not interfere with the -non-test installation. -

-

-In addition to the build flags, the flags handled by 'go test' itself are: -

-
-args
-    Pass the remainder of the command line (everything after -args)
-    to the test binary, uninterpreted and unchanged.
-    Because this flag consumes the remainder of the command line,
-    the package list (if present) must appear before this flag.
-
--c
-    Compile the test binary to pkg.test but do not run it
-    (where pkg is the last element of the package's import path).
-    The file name can be changed with the -o flag.
-
--exec xprog
-    Run the test binary using xprog. The behavior is the same as
-    in 'go run'. See 'go help run' for details.
-
--i
-    Install packages that are dependencies of the test.
-    Do not run the test.
-
--o file
-    Compile the test binary to the named file.
-    The test still runs (unless -c or -i is specified).
-
-

-The test binary also accepts flags that control execution of the test; these -flags are also accessible by 'go test'. See 'go help testflag' for details. -

-

-For more about build flags, see 'go help build'. -For more about specifying packages, see 'go help packages'. -

-

-See also: go build, go vet. -

-

Run specified go tool

-

-Usage: -

-
go tool [-n] command [args...]
-
-

-Tool runs the go tool command identified by the arguments. -With no arguments it prints the list of known tools. -

-

-The -n flag causes tool to print the command that would be -executed but not execute it. -

-

-For more about each tool command, see 'go tool command -h'. -

-

Print Go version

-

-Usage: -

-
go version
-
-

-Version prints the Go version, as reported by runtime.Version. -

-

Run go tool vet on packages

-

-Usage: -

-
go vet [-n] [-x] [build flags] [packages]
-
-

-Vet runs the Go vet command on the packages named by the import paths. -

-

-For more about vet, see 'go doc cmd/vet'. -For more about specifying packages, see 'go help packages'. -

-

-To run the vet tool with specific options, run 'go tool vet'. -

-

-The -n flag prints commands that would be executed. -The -x flag prints commands as they are executed. -

-

-For more about build flags, see 'go help build'. -

-

-See also: go fmt, go fix. -

-

Calling between Go and C

-

-There are two different ways to call between Go and C/C++ code. -

-

-The first is the cgo tool, which is part of the Go distribution. For -information on how to use it see the cgo documentation (go doc cmd/cgo). -

-

-The second is the SWIG program, which is a general tool for -interfacing between languages. For information on SWIG see -http://swig.org/. When running go build, any file with a .swig -extension will be passed to SWIG. Any file with a .swigcxx extension -will be passed to SWIG with the -c++ option. -

-

-When either cgo or SWIG is used, go build will pass any .c, .m, .s, -or .S files to the C compiler, and any .cc, .cpp, .cxx files to the C++ -compiler. The CC or CXX environment variables may be set to determine -the C or C++ compiler, respectively, to use. -

-

Description of build modes

-

-The 'go build' and 'go install' commands take a -buildmode argument which -indicates which kind of object file is to be built. Currently supported values -are: -

-
-buildmode=archive
-	Build the listed non-main packages into .a files. Packages named
-	main are ignored.
-
--buildmode=c-archive
-	Build the listed main package, plus all packages it imports,
-	into a C archive file. The only callable symbols will be those
-	functions exported using a cgo //export comment. Requires
-	exactly one main package to be listed.
-
--buildmode=c-shared
-	Build the listed main packages, plus all packages that they
-	import, into C shared libraries. The only callable symbols will
-	be those functions exported using a cgo //export comment.
-	Non-main packages are ignored.
-
--buildmode=default
-	Listed main packages are built into executables and listed
-	non-main packages are built into .a files (the default
-	behavior).
-
--buildmode=shared
-	Combine all the listed non-main packages into a single shared
-	library that will be used when building with the -linkshared
-	option. Packages named main are ignored.
-
--buildmode=exe
-	Build the listed main packages and everything they import into
-	executables. Packages not named main are ignored.
-
--buildmode=pie
-	Build the listed main packages and everything they import into
-	position independent executables (PIE). Packages not named
-	main are ignored.
-
--buildmode=plugin
-	Build the listed main packages, plus all packages that they
-	import, into a Go plugin. Packages not named main are ignored.
-
-

File types

-

-The go command examines the contents of a restricted set of files -in each directory. It identifies which files to examine based on -the extension of the file name. These extensions are: -

-
.go
-	Go source files.
-.c, .h
-	C source files.
-	If the package uses cgo or SWIG, these will be compiled with the
-	OS-native compiler (typically gcc); otherwise they will
-	trigger an error.
-.cc, .cpp, .cxx, .hh, .hpp, .hxx
-	C++ source files. Only useful with cgo or SWIG, and always
-	compiled with the OS-native compiler.
-.m
-	Objective-C source files. Only useful with cgo, and always
-	compiled with the OS-native compiler.
-.s, .S
-	Assembler source files.
-	If the package uses cgo or SWIG, these will be assembled with the
-	OS-native assembler (typically gcc (sic)); otherwise they
-	will be assembled with the Go assembler.
-.swig, .swigcxx
-	SWIG definition files.
-.syso
-	System object files.
-
-

-Files of each of these types except .syso may contain build -constraints, but the go command stops scanning for build constraints -at the first item in the file that is not a blank line or //-style -line comment. See the go/build package documentation for -more details. -

-

-Non-test Go source files can also include a //go:binary-only-package -comment, indicating that the package sources are included -for documentation only and must not be used to build the -package binary. This enables distribution of Go packages in -their compiled form alone. See the go/build package documentation -for more details. -

-

GOPATH environment variable

-

-The Go path is used to resolve import statements. -It is implemented by and documented in the go/build package. -

-

-The GOPATH environment variable lists places to look for Go code. -On Unix, the value is a colon-separated string. -On Windows, the value is a semicolon-separated string. -On Plan 9, the value is a list. -

-

-If the environment variable is unset, GOPATH defaults -to a subdirectory named "go" in the user's home directory -($HOME/go on Unix, %USERPROFILE%\go on Windows), -unless that directory holds a Go distribution. -Run "go env GOPATH" to see the current GOPATH. -

-

-See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH. -

-

-Each directory listed in GOPATH must have a prescribed structure: -

-

-The src directory holds source code. The path below src -determines the import path or executable name. -

-

-The pkg directory holds installed package objects. -As in the Go tree, each target operating system and -architecture pair has its own subdirectory of pkg -(pkg/GOOS_GOARCH). -

-

-If DIR is a directory listed in the GOPATH, a package with -source in DIR/src/foo/bar can be imported as "foo/bar" and -has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a". -

-

-The bin directory holds compiled commands. -Each command is named for its source directory, but only -the final element, not the entire path. That is, the -command with source in DIR/src/foo/quux is installed into -DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped -so that you can add DIR/bin to your PATH to get at the -installed commands. If the GOBIN environment variable is -set, commands are installed to the directory it names instead -of DIR/bin. GOBIN must be an absolute path. -

-

-Here's an example directory layout: -

-
GOPATH=/home/user/go
-
-/home/user/go/
-    src/
-        foo/
-            bar/               (go code in package bar)
-                x.go
-            quux/              (go code in package main)
-                y.go
-    bin/
-        quux                   (installed command)
-    pkg/
-        linux_amd64/
-            foo/
-                bar.a          (installed package object)
-
-

-Go searches each directory listed in GOPATH to find source code, -but new packages are always downloaded into the first directory -in the list. -

-

-See https://golang.org/doc/code.html for an example. -

-

Internal Directories

-

-Code in or below a directory named "internal" is importable only -by code in the directory tree rooted at the parent of "internal". -Here's an extended version of the directory layout above: -

-
/home/user/go/
-    src/
-        crash/
-            bang/              (go code in package bang)
-                b.go
-        foo/                   (go code in package foo)
-            f.go
-            bar/               (go code in package bar)
-                x.go
-            internal/
-                baz/           (go code in package baz)
-                    z.go
-            quux/              (go code in package main)
-                y.go
-
-

-The code in z.go is imported as "foo/internal/baz", but that -import statement can only appear in source files in the subtree -rooted at foo. The source files foo/f.go, foo/bar/x.go, and -foo/quux/y.go can all import "foo/internal/baz", but the source file -crash/bang/b.go cannot. -

-

-See https://golang.org/s/go14internal for details. -

-

Vendor Directories

-

-Go 1.6 includes support for using local copies of external dependencies -to satisfy imports of those dependencies, often referred to as vendoring. -

-

-Code below a directory named "vendor" is importable only -by code in the directory tree rooted at the parent of "vendor", -and only using an import path that omits the prefix up to and -including the vendor element. -

-

-Here's the example from the previous section, -but with the "internal" directory renamed to "vendor" -and a new foo/vendor/crash/bang directory added: -

-
/home/user/go/
-    src/
-        crash/
-            bang/              (go code in package bang)
-                b.go
-        foo/                   (go code in package foo)
-            f.go
-            bar/               (go code in package bar)
-                x.go
-            vendor/
-                crash/
-                    bang/      (go code in package bang)
-                        b.go
-                baz/           (go code in package baz)
-                    z.go
-            quux/              (go code in package main)
-                y.go
-
-

-The same visibility rules apply as for internal, but the code -in z.go is imported as "baz", not as "foo/vendor/baz". -

-

-Code in vendor directories deeper in the source tree shadows -code in higher directories. Within the subtree rooted at foo, an import -of "crash/bang" resolves to "foo/vendor/crash/bang", not the -top-level "crash/bang". -

-

-Code in vendor directories is not subject to import path -checking (see 'go help importpath'). -

-

-When 'go get' checks out or updates a git repository, it now also -updates submodules. -

-

-Vendor directories do not affect the placement of new repositories -being checked out for the first time by 'go get': those are always -placed in the main GOPATH, never in a vendor subtree. -

-

-See https://golang.org/s/go15vendor for details. -

-

Environment variables

-

-The go command, and the tools it invokes, examine a few different -environment variables. For many of these, you can see the default -value of on your system by running 'go env NAME', where NAME is the -name of the variable. -

-

-General-purpose environment variables: -

-
GCCGO
-	The gccgo command to run for 'go build -compiler=gccgo'.
-GOARCH
-	The architecture, or processor, for which to compile code.
-	Examples are amd64, 386, arm, ppc64.
-GOBIN
-	The directory where 'go install' will install a command.
-GOOS
-	The operating system for which to compile code.
-	Examples are linux, darwin, windows, netbsd.
-GOPATH
-	For more details see: 'go help gopath'.
-GORACE
-	Options for the race detector.
-	See https://golang.org/doc/articles/race_detector.html.
-GOROOT
-	The root of the go tree.
-
-

-Environment variables for use with cgo: -

-
CC
-	The command to use to compile C code.
-CGO_ENABLED
-	Whether the cgo command is supported.  Either 0 or 1.
-CGO_CFLAGS
-	Flags that cgo will pass to the compiler when compiling
-	C code.
-CGO_CPPFLAGS
-	Flags that cgo will pass to the compiler when compiling
-	C or C++ code.
-CGO_CXXFLAGS
-	Flags that cgo will pass to the compiler when compiling
-	C++ code.
-CGO_FFLAGS
-	Flags that cgo will pass to the compiler when compiling
-	Fortran code.
-CGO_LDFLAGS
-	Flags that cgo will pass to the compiler when linking.
-CXX
-	The command to use to compile C++ code.
-PKG_CONFIG
-	Path to pkg-config tool.
-
-

-Architecture-specific environment variables: -

-
GOARM
-	For GOARCH=arm, the ARM architecture for which to compile.
-	Valid values are 5, 6, 7.
-GO386
-	For GOARCH=386, the floating point instruction set.
-	Valid values are 387, sse2.
-
-

-Special-purpose environment variables: -

-
GOROOT_FINAL
-	The root of the installed Go tree, when it is
-	installed in a location other than where it is built.
-	File names in stack traces are rewritten from GOROOT to
-	GOROOT_FINAL.
-GO_EXTLINK_ENABLED
-	Whether the linker should use external linking mode
-	when using -linkmode=auto with code that uses cgo.
-	Set to 0 to disable external linking mode, 1 to enable it.
-GIT_ALLOW_PROTOCOL
-	Defined by Git. A colon-separated list of schemes that are allowed to be used
-	with git fetch/clone. If set, any scheme not explicitly mentioned will be
-	considered insecure by 'go get'.
-
-

Import path syntax

-

-An import path (see 'go help packages') denotes a package stored in the local -file system. In general, an import path denotes either a standard package (such -as "unicode/utf8") or a package found in one of the work spaces (For more -details see: 'go help gopath'). -

-

Relative import paths

-

-An import path beginning with ./ or ../ is called a relative path. -The toolchain supports relative import paths as a shortcut in two ways. -

-

-First, a relative path can be used as a shorthand on the command line. -If you are working in the directory containing the code imported as -"unicode" and want to run the tests for "unicode/utf8", you can type -"go test ./utf8" instead of needing to specify the full path. -Similarly, in the reverse situation, "go test .." will test "unicode" from -the "unicode/utf8" directory. Relative patterns are also allowed, like -"go test ./..." to test all subdirectories. See 'go help packages' for details -on the pattern syntax. -

-

-Second, if you are compiling a Go program not in a work space, -you can use a relative path in an import statement in that program -to refer to nearby code also not in a work space. -This makes it easy to experiment with small multipackage programs -outside of the usual work spaces, but such programs cannot be -installed with "go install" (there is no work space in which to install them), -so they are rebuilt from scratch each time they are built. -To avoid ambiguity, Go programs cannot use relative import paths -within a work space. -

-

Remote import paths

-

-Certain import paths also -describe how to obtain the source code for the package using -a revision control system. -

-

-A few common code hosting sites have special syntax: -

-
Bitbucket (Git, Mercurial)
-
-	import "bitbucket.org/user/project"
-	import "bitbucket.org/user/project/sub/directory"
-
-GitHub (Git)
-
-	import "github.com/user/project"
-	import "github.com/user/project/sub/directory"
-
-Launchpad (Bazaar)
-
-	import "launchpad.net/project"
-	import "launchpad.net/project/series"
-	import "launchpad.net/project/series/sub/directory"
-
-	import "launchpad.net/~user/project/branch"
-	import "launchpad.net/~user/project/branch/sub/directory"
-
-IBM DevOps Services (Git)
-
-	import "hub.jazz.net/git/user/project"
-	import "hub.jazz.net/git/user/project/sub/directory"
-
-

-For code hosted on other servers, import paths may either be qualified -with the version control type, or the go tool can dynamically fetch -the import path over https/http and discover where the code resides -from a <meta> tag in the HTML. -

-

-To declare the code location, an import path of the form -

-
repository.vcs/path
-
-

-specifies the given repository, with or without the .vcs suffix, -using the named version control system, and then the path inside -that repository. The supported version control systems are: -

-
Bazaar      .bzr
-Git         .git
-Mercurial   .hg
-Subversion  .svn
-
-

-For example, -

-
import "example.org/user/foo.hg"
-
-

-denotes the root directory of the Mercurial repository at -example.org/user/foo or foo.hg, and -

-
import "example.org/repo.git/foo/bar"
-
-

-denotes the foo/bar directory of the Git repository at -example.org/repo or repo.git. -

-

-When a version control system supports multiple protocols, -each is tried in turn when downloading. For example, a Git -download tries https://, then git+ssh://. -

-

-By default, downloads are restricted to known secure protocols -(e.g. https, ssh). To override this setting for Git downloads, the -GIT_ALLOW_PROTOCOL environment variable can be set (For more details see: -'go help environment'). -

-

-If the import path is not a known code hosting site and also lacks a -version control qualifier, the go tool attempts to fetch the import -over https/http and looks for a <meta> tag in the document's HTML -<head>. -

-

-The meta tag has the form: -

-
<meta name="go-import" content="import-prefix vcs repo-root">
-
-

-The import-prefix is the import path corresponding to the repository -root. It must be a prefix or an exact match of the package being -fetched with "go get". If it's not an exact match, another http -request is made at the prefix to verify the <meta> tags match. -

-

-The meta tag should appear as early in the file as possible. -In particular, it should appear before any raw JavaScript or CSS, -to avoid confusing the go command's restricted parser. -

-

-The vcs is one of "git", "hg", "svn", etc, -

-

-The repo-root is the root of the version control system -containing a scheme and not containing a .vcs qualifier. -

-

-For example, -

-
import "example.org/pkg/foo"
-
-

-will result in the following requests: -

-
https://example.org/pkg/foo?go-get=1 (preferred)
-http://example.org/pkg/foo?go-get=1  (fallback, only with -insecure)
-
-

-If that page contains the meta tag -

-
<meta name="go-import" content="example.org git https://code.org/r/p/exproj">
-
-

-the go tool will verify that https://example.org/?go-get=1 contains the -same meta tag and then git clone https://code.org/r/p/exproj into -GOPATH/src/example.org. -

-

-New downloaded packages are written to the first directory listed in the GOPATH -environment variable (For more details see: 'go help gopath'). -

-

-The go command attempts to download the version of the -package appropriate for the Go release being used. -Run 'go help get' for more. -

-

Import path checking

-

-When the custom import path feature described above redirects to a -known code hosting site, each of the resulting packages has two possible -import paths, using the custom domain or the known hosting site. -

-

-A package statement is said to have an "import comment" if it is immediately -followed (before the next newline) by a comment of one of these two forms: -

-
package math // import "path"
-package math /* import "path" */
-
-

-The go command will refuse to install a package with an import comment -unless it is being referred to by that import path. In this way, import comments -let package authors make sure the custom import path is used and not a -direct path to the underlying code hosting site. -

-

-Import path checking is disabled for code found within vendor trees. -This makes it possible to copy code into alternate locations in vendor trees -without needing to update import comments. -

-

-See https://golang.org/s/go14customimport for details. -

-

Description of package lists

-

-Many commands apply to a set of packages: -

-
go action [packages]
-
-

-Usually, [packages] is a list of import paths. -

-

-An import path that is a rooted path or that begins with -a . or .. element is interpreted as a file system path and -denotes the package in that directory. -

-

-Otherwise, the import path P denotes the package found in -the directory DIR/src/P for some DIR listed in the GOPATH -environment variable (For more details see: 'go help gopath'). -

-

-If no import paths are given, the action applies to the -package in the current directory. -

-

-There are four reserved names for paths that should not be used -for packages to be built with the go tool: -

-

-- "main" denotes the top-level package in a stand-alone executable. -

-

-- "all" expands to all package directories found in all the GOPATH -trees. For example, 'go list all' lists all the packages on the local -system. -

-

-- "std" is like all but expands to just the packages in the standard -Go library. -

-

-- "cmd" expands to the Go repository's commands and their -internal libraries. -

-

-Import paths beginning with "cmd/" only match source code in -the Go repository. -

-

-An import path is a pattern if it includes one or more "..." wildcards, -each of which can match any string, including the empty string and -strings containing slashes. Such a pattern expands to all package -directories found in the GOPATH trees with names matching the -patterns. As a special case, x/... matches x as well as x's subdirectories. -For example, net/... expands to net and packages in its subdirectories. -

-

-An import path can also name a package to be downloaded from -a remote repository. Run 'go help importpath' for details. -

-

-Every package in a program must have a unique import path. -By convention, this is arranged by starting each path with a -unique prefix that belongs to you. For example, paths used -internally at Google all begin with 'google', and paths -denoting remote repositories begin with the path to the code, -such as 'github.com/user/repo'. -

-

-Packages in a program need not have unique package names, -but there are two reserved package names with special meaning. -The name main indicates a command, not a library. -Commands are built into binaries and cannot be imported. -The name documentation indicates documentation for -a non-Go program in the directory. Files in package documentation -are ignored by the go command. -

-

-As a special case, if the package list is a list of .go files from a -single directory, the command is applied to a single synthesized -package made up of exactly those files, ignoring any build constraints -in those files and ignoring any other files in the directory. -

-

-Directory and file names that begin with "." or "_" are ignored -by the go tool, as are directories named "testdata". -

-

Description of testing flags

-

-The 'go test' command takes both flags that apply to 'go test' itself -and flags that apply to the resulting test binary. -

-

-Several of the flags control profiling and write an execution profile -suitable for "go tool pprof"; run "go tool pprof -h" for more -information. The --alloc_space, --alloc_objects, and --show_bytes -options of pprof control how the information is presented. -

-

-The following flags are recognized by the 'go test' command and -control the execution of any test: -

-
-bench regexp
-    Run (sub)benchmarks matching a regular expression.
-    The given regular expression is split into smaller ones by
-    top-level '/', where each must match the corresponding part of a
-    benchmark's identifier.
-    By default, no benchmarks run. To run all benchmarks,
-    use '-bench .' or '-bench=.'.
-
--benchtime t
-    Run enough iterations of each benchmark to take t, specified
-    as a time.Duration (for example, -benchtime 1h30s).
-    The default is 1 second (1s).
-
--count n
-    Run each test and benchmark n times (default 1).
-    If -cpu is set, run n times for each GOMAXPROCS value.
-    Examples are always run once.
-
--cover
-    Enable coverage analysis.
-
--covermode set,count,atomic
-    Set the mode for coverage analysis for the package[s]
-    being tested. The default is "set" unless -race is enabled,
-    in which case it is "atomic".
-    The values:
-	set: bool: does this statement run?
-	count: int: how many times does this statement run?
-	atomic: int: count, but correct in multithreaded tests;
-		significantly more expensive.
-    Sets -cover.
-
--coverpkg pkg1,pkg2,pkg3
-    Apply coverage analysis in each test to the given list of packages.
-    The default is for each test to analyze only the package being tested.
-    Packages are specified as import paths.
-    Sets -cover.
-
--cpu 1,2,4
-    Specify a list of GOMAXPROCS values for which the tests or
-    benchmarks should be executed.  The default is the current value
-    of GOMAXPROCS.
-
--parallel n
-    Allow parallel execution of test functions that call t.Parallel.
-    The value of this flag is the maximum number of tests to run
-    simultaneously; by default, it is set to the value of GOMAXPROCS.
-    Note that -parallel only applies within a single test binary.
-    The 'go test' command may run tests for different packages
-    in parallel as well, according to the setting of the -p flag
-    (see 'go help build').
-
--run regexp
-    Run only those tests and examples matching the regular expression.
-    For tests the regular expression is split into smaller ones by
-    top-level '/', where each must match the corresponding part of a
-    test's identifier.
-
--short
-    Tell long-running tests to shorten their run time.
-    It is off by default but set during all.bash so that installing
-    the Go tree can run a sanity check but not spend time running
-    exhaustive tests.
-
--timeout t
-    If a test runs longer than t, panic.
-    The default is 10 minutes (10m).
-
--v
-    Verbose output: log all tests as they are run. Also print all
-    text from Log and Logf calls even if the test succeeds.
-
-

-The following flags are also recognized by 'go test' and can be used to -profile the tests during execution: -

-
-benchmem
-    Print memory allocation statistics for benchmarks.
-
--blockprofile block.out
-    Write a goroutine blocking profile to the specified file
-    when all tests are complete.
-    Writes test binary as -c would.
-
--blockprofilerate n
-    Control the detail provided in goroutine blocking profiles by
-    calling runtime.SetBlockProfileRate with n.
-    See 'go doc runtime.SetBlockProfileRate'.
-    The profiler aims to sample, on average, one blocking event every
-    n nanoseconds the program spends blocked.  By default,
-    if -test.blockprofile is set without this flag, all blocking events
-    are recorded, equivalent to -test.blockprofilerate=1.
-
--coverprofile cover.out
-    Write a coverage profile to the file after all tests have passed.
-    Sets -cover.
-
--cpuprofile cpu.out
-    Write a CPU profile to the specified file before exiting.
-    Writes test binary as -c would.
-
--memprofile mem.out
-    Write a memory profile to the file after all tests have passed.
-    Writes test binary as -c would.
-
--memprofilerate n
-    Enable more precise (and expensive) memory profiles by setting
-    runtime.MemProfileRate.  See 'go doc runtime.MemProfileRate'.
-    To profile all memory allocations, use -test.memprofilerate=1
-    and pass --alloc_space flag to the pprof tool.
-
--mutexprofile mutex.out
-    Write a mutex contention profile to the specified file
-    when all tests are complete.
-    Writes test binary as -c would.
-
--mutexprofilefraction n
-    Sample 1 in n stack traces of goroutines holding a
-    contended mutex.
-
--outputdir directory
-    Place output files from profiling in the specified directory,
-    by default the directory in which "go test" is running.
-
--trace trace.out
-    Write an execution trace to the specified file before exiting.
-
-

-Each of these flags is also recognized with an optional 'test.' prefix, -as in -test.v. When invoking the generated test binary (the result of -'go test -c') directly, however, the prefix is mandatory. -

-

-The 'go test' command rewrites or removes recognized flags, -as appropriate, both before and after the optional package list, -before invoking the test binary. -

-

-For instance, the command -

-
go test -v -myflag testdata -cpuprofile=prof.out -x
-
-

-will compile the test binary and then run it as -

-
pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out
-
-

-(The -x flag is removed because it applies only to the go command's -execution, not to the test itself.) -

-

-The test flags that generate profiles (other than for coverage) also -leave the test binary in pkg.test for use when analyzing the profiles. -

-

-When 'go test' runs a test binary, it does so from within the -corresponding package's source code directory. Depending on the test, -it may be necessary to do the same when invoking a generated test -binary directly. -

-

-The command-line package list, if present, must appear before any -flag not known to the go test command. Continuing the example above, -the package list would have to appear before -myflag, but could appear -on either side of -v. -

-

-To keep an argument for a test binary from being interpreted as a -known flag or a package name, use -args (see 'go help test') which -passes the remainder of the command line through to the test binary -uninterpreted and unaltered. -

-

-For instance, the command -

-
go test -v -args -x -v
-
-

-will compile the test binary and then run it as -

-
pkg.test -test.v -x -v
-
-

-Similarly, -

-
go test -args math
-
-

-will compile the test binary and then run it as -

-
pkg.test math
-
-

-In the first example, the -x and the second -v are passed through to the -test binary unchanged and with no effect on the go command itself. -In the second example, the argument math is passed through to the test -binary, instead of being interpreted as the package list. -

-

Description of testing functions

-

-The 'go test' command expects to find test, benchmark, and example functions -in the "*_test.go" files corresponding to the package under test. -

-

-A test function is one named TestXXX (where XXX is any alphanumeric string -not starting with a lower case letter) and should have the signature, -

-
func TestXXX(t *testing.T) { ... }
-
-

-A benchmark function is one named BenchmarkXXX and should have the signature, -

-
func BenchmarkXXX(b *testing.B) { ... }
-
-

-An example function is similar to a test function but, instead of using -*testing.T to report success or failure, prints output to os.Stdout. -If the last comment in the function starts with "Output:" then the output -is compared exactly against the comment (see examples below). If the last -comment begins with "Unordered output:" then the output is compared to the -comment, however the order of the lines is ignored. An example with no such -comment is compiled but not executed. An example with no text after -"Output:" is compiled, executed, and expected to produce no output. -

-

-Godoc displays the body of ExampleXXX to demonstrate the use -of the function, constant, or variable XXX. An example of a method M with -receiver type T or *T is named ExampleT_M. There may be multiple examples -for a given function, constant, or variable, distinguished by a trailing _xxx, -where xxx is a suffix not beginning with an upper case letter. -

-

-Here is an example of an example: -

-
func ExamplePrintln() {
-	Println("The output of\nthis example.")
-	// Output: The output of
-	// this example.
-}
-
-

-Here is another example where the ordering of the output is ignored: -

-
func ExamplePerm() {
-	for _, value := range Perm(4) {
-		fmt.Println(value)
-	}
-
-	// Unordered output: 4
-	// 2
-	// 1
-	// 3
-	// 0
-}
-
-

-The entire test file is presented as the example when it contains a single -example function, at least one other function, type, variable, or constant -declaration, and no test or benchmark functions. -

-

-See the documentation of the testing package for more information. -

- - - -
-
- - - - - - - - -`)) diff --git a/examples/golang.org/x/net/http2/h2i/README.md b/examples/golang.org/x/net/http2/h2i/README.md deleted file mode 100644 index fb5c5ef..0000000 --- a/examples/golang.org/x/net/http2/h2i/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# h2i - -**h2i** is an interactive HTTP/2 ("h2") console debugger. Miss the good ol' -days of telnetting to your HTTP/1.n servers? We're bringing you -back. - -Features: -- send raw HTTP/2 frames - - PING - - SETTINGS - - HEADERS - - etc -- type in HTTP/1.n and have it auto-HPACK/frame-ify it for HTTP/2 -- pretty print all received HTTP/2 frames from the peer (including HPACK decoding) -- tab completion of commands, options - -Not yet features, but soon: -- unnecessary CONTINUATION frames on short boundaries, to test peer implementations -- request bodies (DATA frames) -- send invalid frames for testing server implementations (supported by underlying Framer) - -Later: -- act like a server - -## Installation - -``` -$ go get golang.org/x/net/http2/h2i -$ h2i -``` - -## Demo - -``` -$ h2i -Usage: h2i - - -insecure - Whether to skip TLS cert validation - -nextproto string - Comma-separated list of NPN/ALPN protocol names to negotiate. (default "h2,h2-14") - -$ h2i google.com -Connecting to google.com:443 ... -Connected to 74.125.224.41:443 -Negotiated protocol "h2-14" -[FrameHeader SETTINGS len=18] - [MAX_CONCURRENT_STREAMS = 100] - [INITIAL_WINDOW_SIZE = 1048576] - [MAX_FRAME_SIZE = 16384] -[FrameHeader WINDOW_UPDATE len=4] - Window-Increment = 983041 - -h2i> PING h2iSayHI -[FrameHeader PING flags=ACK len=8] - Data = "h2iSayHI" -h2i> headers -(as HTTP/1.1)> GET / HTTP/1.1 -(as HTTP/1.1)> Host: ip.appspot.com -(as HTTP/1.1)> User-Agent: h2i/brad-n-blake -(as HTTP/1.1)> -Opening Stream-ID 1: - :authority = ip.appspot.com - :method = GET - :path = / - :scheme = https - user-agent = h2i/brad-n-blake -[FrameHeader HEADERS flags=END_HEADERS stream=1 len=77] - :status = "200" - alternate-protocol = "443:quic,p=1" - content-length = "15" - content-type = "text/html" - date = "Fri, 01 May 2015 23:06:56 GMT" - server = "Google Frontend" -[FrameHeader DATA flags=END_STREAM stream=1 len=15] - "173.164.155.78\n" -[FrameHeader PING len=8] - Data = "\x00\x00\x00\x00\x00\x00\x00\x00" -h2i> ping -[FrameHeader PING flags=ACK len=8] - Data = "h2i_ping" -h2i> ping -[FrameHeader PING flags=ACK len=8] - Data = "h2i_ping" -h2i> ping -[FrameHeader GOAWAY len=22] - Last-Stream-ID = 1; Error-Code = PROTOCOL_ERROR (1) - -ReadFrame: EOF -``` - -## Status - -Quick few hour hack. So much yet to do. Feel free to file issues for -bugs or wishlist items, but [@bmizerany](https://github.com/bmizerany/) -and I aren't yet accepting pull requests until things settle down. - diff --git a/examples/golang.org/x/net/http2/h2i/h2i.go b/examples/golang.org/x/net/http2/h2i/h2i.go deleted file mode 100644 index 12d325e..0000000 --- a/examples/golang.org/x/net/http2/h2i/h2i.go +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !js,!nacl,!plan9,!solaris - -/* -The h2i command is an interactive HTTP/2 console. - -Usage: - $ h2i [flags] - -Interactive commands in the console: (all parts case-insensitive) - - ping [data] - settings ack - settings FOO=n BAR=z - headers (open a new stream by typing HTTP/1.1) -*/ -package main - -import ( - "bufio" - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "log" - "net" - "net/http" - "os" - "regexp" - "strconv" - "strings" - - "golang.org/x/crypto/ssh/terminal" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -// Flags -var ( - flagNextProto = flag.String("nextproto", "h2,h2-14", "Comma-separated list of NPN/ALPN protocol names to negotiate.") - flagInsecure = flag.Bool("insecure", false, "Whether to skip TLS cert validation") - flagSettings = flag.String("settings", "empty", "comma-separated list of KEY=value settings for the initial SETTINGS frame. The magic value 'empty' sends an empty initial settings frame, and the magic value 'omit' causes no initial settings frame to be sent.") - flagDial = flag.String("dial", "", "optional ip:port to dial, to connect to a host:port but use a different SNI name (including a SNI name without DNS)") -) - -type command struct { - run func(*h2i, []string) error // required - - // complete optionally specifies tokens (case-insensitive) which are - // valid for this subcommand. - complete func() []string -} - -var commands = map[string]command{ - "ping": {run: (*h2i).cmdPing}, - "settings": { - run: (*h2i).cmdSettings, - complete: func() []string { - return []string{ - "ACK", - http2.SettingHeaderTableSize.String(), - http2.SettingEnablePush.String(), - http2.SettingMaxConcurrentStreams.String(), - http2.SettingInitialWindowSize.String(), - http2.SettingMaxFrameSize.String(), - http2.SettingMaxHeaderListSize.String(), - } - }, - }, - "quit": {run: (*h2i).cmdQuit}, - "headers": {run: (*h2i).cmdHeaders}, -} - -func usage() { - fmt.Fprintf(os.Stderr, "Usage: h2i \n\n") - flag.PrintDefaults() -} - -// withPort adds ":443" if another port isn't already present. -func withPort(host string) string { - if _, _, err := net.SplitHostPort(host); err != nil { - return net.JoinHostPort(host, "443") - } - return host -} - -// withoutPort strips the port from addr if present. -func withoutPort(addr string) string { - if h, _, err := net.SplitHostPort(addr); err == nil { - return h - } - return addr -} - -// h2i is the app's state. -type h2i struct { - host string - tc *tls.Conn - framer *http2.Framer - term *terminal.Terminal - - // owned by the command loop: - streamID uint32 - hbuf bytes.Buffer - henc *hpack.Encoder - - // owned by the readFrames loop: - peerSetting map[http2.SettingID]uint32 - hdec *hpack.Decoder -} - -func main() { - flag.Usage = usage - flag.Parse() - if flag.NArg() != 1 { - usage() - os.Exit(2) - } - log.SetFlags(0) - - host := flag.Arg(0) - app := &h2i{ - host: host, - peerSetting: make(map[http2.SettingID]uint32), - } - app.henc = hpack.NewEncoder(&app.hbuf) - - if err := app.Main(); err != nil { - if app.term != nil { - app.logf("%v\n", err) - } else { - fmt.Fprintf(os.Stderr, "%v\n", err) - } - os.Exit(1) - } - fmt.Fprintf(os.Stdout, "\n") -} - -func (app *h2i) Main() error { - cfg := &tls.Config{ - ServerName: withoutPort(app.host), - NextProtos: strings.Split(*flagNextProto, ","), - InsecureSkipVerify: *flagInsecure, - } - - hostAndPort := *flagDial - if hostAndPort == "" { - hostAndPort = withPort(app.host) - } - log.Printf("Connecting to %s ...", hostAndPort) - tc, err := tls.Dial("tcp", hostAndPort, cfg) - if err != nil { - return fmt.Errorf("Error dialing %s: %v", hostAndPort, err) - } - log.Printf("Connected to %v", tc.RemoteAddr()) - defer tc.Close() - - if err := tc.Handshake(); err != nil { - return fmt.Errorf("TLS handshake: %v", err) - } - if !*flagInsecure { - if err := tc.VerifyHostname(app.host); err != nil { - return fmt.Errorf("VerifyHostname: %v", err) - } - } - state := tc.ConnectionState() - log.Printf("Negotiated protocol %q", state.NegotiatedProtocol) - if !state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol == "" { - return fmt.Errorf("Could not negotiate protocol mutually") - } - - if _, err := io.WriteString(tc, http2.ClientPreface); err != nil { - return err - } - - app.framer = http2.NewFramer(tc, tc) - - oldState, err := terminal.MakeRaw(int(os.Stdin.Fd())) - if err != nil { - return err - } - defer terminal.Restore(0, oldState) - - var screen = struct { - io.Reader - io.Writer - }{os.Stdin, os.Stdout} - - app.term = terminal.NewTerminal(screen, "h2i> ") - lastWord := regexp.MustCompile(`.+\W(\w+)$`) - app.term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) { - if key != '\t' { - return - } - if pos != len(line) { - // TODO: we're being lazy for now, only supporting tab completion at the end. - return - } - // Auto-complete for the command itself. - if !strings.Contains(line, " ") { - var name string - name, _, ok = lookupCommand(line) - if !ok { - return - } - return name, len(name), true - } - _, c, ok := lookupCommand(line[:strings.IndexByte(line, ' ')]) - if !ok || c.complete == nil { - return - } - if strings.HasSuffix(line, " ") { - app.logf("%s", strings.Join(c.complete(), " ")) - return line, pos, true - } - m := lastWord.FindStringSubmatch(line) - if m == nil { - return line, len(line), true - } - soFar := m[1] - var match []string - for _, cand := range c.complete() { - if len(soFar) > len(cand) || !strings.EqualFold(cand[:len(soFar)], soFar) { - continue - } - match = append(match, cand) - } - if len(match) == 0 { - return - } - if len(match) > 1 { - // TODO: auto-complete any common prefix - app.logf("%s", strings.Join(match, " ")) - return line, pos, true - } - newLine = line[:len(line)-len(soFar)] + match[0] - return newLine, len(newLine), true - - } - - errc := make(chan error, 2) - go func() { errc <- app.readFrames() }() - go func() { errc <- app.readConsole() }() - return <-errc -} - -func (app *h2i) logf(format string, args ...interface{}) { - fmt.Fprintf(app.term, format+"\r\n", args...) -} - -func (app *h2i) readConsole() error { - if s := *flagSettings; s != "omit" { - var args []string - if s != "empty" { - args = strings.Split(s, ",") - } - _, c, ok := lookupCommand("settings") - if !ok { - panic("settings command not found") - } - c.run(app, args) - } - - for { - line, err := app.term.ReadLine() - if err == io.EOF { - return nil - } - if err != nil { - return fmt.Errorf("terminal.ReadLine: %v", err) - } - f := strings.Fields(line) - if len(f) == 0 { - continue - } - cmd, args := f[0], f[1:] - if _, c, ok := lookupCommand(cmd); ok { - err = c.run(app, args) - } else { - app.logf("Unknown command %q", line) - } - if err == errExitApp { - return nil - } - if err != nil { - return err - } - } -} - -func lookupCommand(prefix string) (name string, c command, ok bool) { - prefix = strings.ToLower(prefix) - if c, ok = commands[prefix]; ok { - return prefix, c, ok - } - - for full, candidate := range commands { - if strings.HasPrefix(full, prefix) { - if c.run != nil { - return "", command{}, false // ambiguous - } - c = candidate - name = full - } - } - return name, c, c.run != nil -} - -var errExitApp = errors.New("internal sentinel error value to quit the console reading loop") - -func (a *h2i) cmdQuit(args []string) error { - if len(args) > 0 { - a.logf("the QUIT command takes no argument") - return nil - } - return errExitApp -} - -func (a *h2i) cmdSettings(args []string) error { - if len(args) == 1 && strings.EqualFold(args[0], "ACK") { - return a.framer.WriteSettingsAck() - } - var settings []http2.Setting - for _, arg := range args { - if strings.EqualFold(arg, "ACK") { - a.logf("Error: ACK must be only argument with the SETTINGS command") - return nil - } - eq := strings.Index(arg, "=") - if eq == -1 { - a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) - return nil - } - sid, ok := settingByName(arg[:eq]) - if !ok { - a.logf("Error: unknown setting name %q", arg[:eq]) - return nil - } - val, err := strconv.ParseUint(arg[eq+1:], 10, 32) - if err != nil { - a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) - return nil - } - settings = append(settings, http2.Setting{ - ID: sid, - Val: uint32(val), - }) - } - a.logf("Sending: %v", settings) - return a.framer.WriteSettings(settings...) -} - -func settingByName(name string) (http2.SettingID, bool) { - for _, sid := range [...]http2.SettingID{ - http2.SettingHeaderTableSize, - http2.SettingEnablePush, - http2.SettingMaxConcurrentStreams, - http2.SettingInitialWindowSize, - http2.SettingMaxFrameSize, - http2.SettingMaxHeaderListSize, - } { - if strings.EqualFold(sid.String(), name) { - return sid, true - } - } - return 0, false -} - -func (app *h2i) cmdPing(args []string) error { - if len(args) > 1 { - app.logf("invalid PING usage: only accepts 0 or 1 args") - return nil // nil means don't end the program - } - var data [8]byte - if len(args) == 1 { - copy(data[:], args[0]) - } else { - copy(data[:], "h2i_ping") - } - return app.framer.WritePing(false, data) -} - -func (app *h2i) cmdHeaders(args []string) error { - if len(args) > 0 { - app.logf("Error: HEADERS doesn't yet take arguments.") - // TODO: flags for restricting window size, to force CONTINUATION - // frames. - return nil - } - var h1req bytes.Buffer - app.term.SetPrompt("(as HTTP/1.1)> ") - defer app.term.SetPrompt("h2i> ") - for { - line, err := app.term.ReadLine() - if err != nil { - return err - } - h1req.WriteString(line) - h1req.WriteString("\r\n") - if line == "" { - break - } - } - req, err := http.ReadRequest(bufio.NewReader(&h1req)) - if err != nil { - app.logf("Invalid HTTP/1.1 request: %v", err) - return nil - } - if app.streamID == 0 { - app.streamID = 1 - } else { - app.streamID += 2 - } - app.logf("Opening Stream-ID %d:", app.streamID) - hbf := app.encodeHeaders(req) - if len(hbf) > 16<<10 { - app.logf("TODO: h2i doesn't yet write CONTINUATION frames. Copy it from transport.go") - return nil - } - return app.framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: app.streamID, - BlockFragment: hbf, - EndStream: req.Method == "GET" || req.Method == "HEAD", // good enough for now - EndHeaders: true, // for now - }) -} - -func (app *h2i) readFrames() error { - for { - f, err := app.framer.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame: %v", err) - } - app.logf("%v", f) - switch f := f.(type) { - case *http2.PingFrame: - app.logf(" Data = %q", f.Data) - case *http2.SettingsFrame: - f.ForeachSetting(func(s http2.Setting) error { - app.logf(" %v", s) - app.peerSetting[s.ID] = s.Val - return nil - }) - case *http2.WindowUpdateFrame: - app.logf(" Window-Increment = %v", f.Increment) - case *http2.GoAwayFrame: - app.logf(" Last-Stream-ID = %d; Error-Code = %v (%d)", f.LastStreamID, f.ErrCode, f.ErrCode) - case *http2.DataFrame: - app.logf(" %q", f.Data()) - case *http2.HeadersFrame: - if f.HasPriority() { - app.logf(" PRIORITY = %v", f.Priority) - } - if app.hdec == nil { - // TODO: if the user uses h2i to send a SETTINGS frame advertising - // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE - // and stuff here instead of using the 4k default. But for now: - tableSize := uint32(4 << 10) - app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField) - } - app.hdec.Write(f.HeaderBlockFragment()) - case *http2.PushPromiseFrame: - if app.hdec == nil { - // TODO: if the user uses h2i to send a SETTINGS frame advertising - // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE - // and stuff here instead of using the 4k default. But for now: - tableSize := uint32(4 << 10) - app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField) - } - app.hdec.Write(f.HeaderBlockFragment()) - } - } -} - -// called from readLoop -func (app *h2i) onNewHeaderField(f hpack.HeaderField) { - if f.Sensitive { - app.logf(" %s = %q (SENSITIVE)", f.Name, f.Value) - } - app.logf(" %s = %q", f.Name, f.Value) -} - -func (app *h2i) encodeHeaders(req *http.Request) []byte { - app.hbuf.Reset() - - // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go - host := req.Host - if host == "" { - host = req.URL.Host - } - - path := req.RequestURI - if path == "" { - path = "/" - } - - app.writeHeader(":authority", host) // probably not right for all sites - app.writeHeader(":method", req.Method) - app.writeHeader(":path", path) - app.writeHeader(":scheme", "https") - - for k, vv := range req.Header { - lowKey := strings.ToLower(k) - if lowKey == "host" { - continue - } - for _, v := range vv { - app.writeHeader(lowKey, v) - } - } - return app.hbuf.Bytes() -} - -func (app *h2i) writeHeader(name, value string) { - app.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) - app.logf(" %s = %s", name, value) -} diff --git a/examples/golang.org/x/net/http2/headermap.go b/examples/golang.org/x/net/http2/headermap.go deleted file mode 100644 index c2805f6..0000000 --- a/examples/golang.org/x/net/http2/headermap.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "net/http" - "strings" -) - -var ( - commonLowerHeader = map[string]string{} // Go-Canonical-Case -> lower-case - commonCanonHeader = map[string]string{} // lower-case -> Go-Canonical-Case -) - -func init() { - for _, v := range []string{ - "accept", - "accept-charset", - "accept-encoding", - "accept-language", - "accept-ranges", - "age", - "access-control-allow-origin", - "allow", - "authorization", - "cache-control", - "content-disposition", - "content-encoding", - "content-language", - "content-length", - "content-location", - "content-range", - "content-type", - "cookie", - "date", - "etag", - "expect", - "expires", - "from", - "host", - "if-match", - "if-modified-since", - "if-none-match", - "if-unmodified-since", - "last-modified", - "link", - "location", - "max-forwards", - "proxy-authenticate", - "proxy-authorization", - "range", - "referer", - "refresh", - "retry-after", - "server", - "set-cookie", - "strict-transport-security", - "trailer", - "transfer-encoding", - "user-agent", - "vary", - "via", - "www-authenticate", - } { - chk := http.CanonicalHeaderKey(v) - commonLowerHeader[chk] = v - commonCanonHeader[v] = chk - } -} - -func lowerHeader(v string) string { - if s, ok := commonLowerHeader[v]; ok { - return s - } - return strings.ToLower(v) -} diff --git a/examples/golang.org/x/net/http2/hpack/encode.go b/examples/golang.org/x/net/http2/hpack/encode.go deleted file mode 100644 index 1565cf2..0000000 --- a/examples/golang.org/x/net/http2/hpack/encode.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "io" -) - -const ( - uint32Max = ^uint32(0) - initialHeaderTableSize = 4096 -) - -type Encoder struct { - dynTab dynamicTable - // minSize is the minimum table size set by - // SetMaxDynamicTableSize after the previous Header Table Size - // Update. - minSize uint32 - // maxSizeLimit is the maximum table size this encoder - // supports. This will protect the encoder from too large - // size. - maxSizeLimit uint32 - // tableSizeUpdate indicates whether "Header Table Size - // Update" is required. - tableSizeUpdate bool - w io.Writer - buf []byte -} - -// NewEncoder returns a new Encoder which performs HPACK encoding. An -// encoded data is written to w. -func NewEncoder(w io.Writer) *Encoder { - e := &Encoder{ - minSize: uint32Max, - maxSizeLimit: initialHeaderTableSize, - tableSizeUpdate: false, - w: w, - } - e.dynTab.table.init() - e.dynTab.setMaxSize(initialHeaderTableSize) - return e -} - -// WriteField encodes f into a single Write to e's underlying Writer. -// This function may also produce bytes for "Header Table Size Update" -// if necessary. If produced, it is done before encoding f. -func (e *Encoder) WriteField(f HeaderField) error { - e.buf = e.buf[:0] - - if e.tableSizeUpdate { - e.tableSizeUpdate = false - if e.minSize < e.dynTab.maxSize { - e.buf = appendTableSize(e.buf, e.minSize) - } - e.minSize = uint32Max - e.buf = appendTableSize(e.buf, e.dynTab.maxSize) - } - - idx, nameValueMatch := e.searchTable(f) - if nameValueMatch { - e.buf = appendIndexed(e.buf, idx) - } else { - indexing := e.shouldIndex(f) - if indexing { - e.dynTab.add(f) - } - - if idx == 0 { - e.buf = appendNewName(e.buf, f, indexing) - } else { - e.buf = appendIndexedName(e.buf, f, idx, indexing) - } - } - n, err := e.w.Write(e.buf) - if err == nil && n != len(e.buf) { - err = io.ErrShortWrite - } - return err -} - -// searchTable searches f in both stable and dynamic header tables. -// The static header table is searched first. Only when there is no -// exact match for both name and value, the dynamic header table is -// then searched. If there is no match, i is 0. If both name and value -// match, i is the matched index and nameValueMatch becomes true. If -// only name matches, i points to that index and nameValueMatch -// becomes false. -func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) { - i, nameValueMatch = staticTable.search(f) - if nameValueMatch { - return i, true - } - - j, nameValueMatch := e.dynTab.table.search(f) - if nameValueMatch || (i == 0 && j != 0) { - return j + uint64(staticTable.len()), nameValueMatch - } - - return i, false -} - -// SetMaxDynamicTableSize changes the dynamic header table size to v. -// The actual size is bounded by the value passed to -// SetMaxDynamicTableSizeLimit. -func (e *Encoder) SetMaxDynamicTableSize(v uint32) { - if v > e.maxSizeLimit { - v = e.maxSizeLimit - } - if v < e.minSize { - e.minSize = v - } - e.tableSizeUpdate = true - e.dynTab.setMaxSize(v) -} - -// SetMaxDynamicTableSizeLimit changes the maximum value that can be -// specified in SetMaxDynamicTableSize to v. By default, it is set to -// 4096, which is the same size of the default dynamic header table -// size described in HPACK specification. If the current maximum -// dynamic header table size is strictly greater than v, "Header Table -// Size Update" will be done in the next WriteField call and the -// maximum dynamic header table size is truncated to v. -func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) { - e.maxSizeLimit = v - if e.dynTab.maxSize > v { - e.tableSizeUpdate = true - e.dynTab.setMaxSize(v) - } -} - -// shouldIndex reports whether f should be indexed. -func (e *Encoder) shouldIndex(f HeaderField) bool { - return !f.Sensitive && f.Size() <= e.dynTab.maxSize -} - -// appendIndexed appends index i, as encoded in "Indexed Header Field" -// representation, to dst and returns the extended buffer. -func appendIndexed(dst []byte, i uint64) []byte { - first := len(dst) - dst = appendVarInt(dst, 7, i) - dst[first] |= 0x80 - return dst -} - -// appendNewName appends f, as encoded in one of "Literal Header field -// - New Name" representation variants, to dst and returns the -// extended buffer. -// -// If f.Sensitive is true, "Never Indexed" representation is used. If -// f.Sensitive is false and indexing is true, "Inremental Indexing" -// representation is used. -func appendNewName(dst []byte, f HeaderField, indexing bool) []byte { - dst = append(dst, encodeTypeByte(indexing, f.Sensitive)) - dst = appendHpackString(dst, f.Name) - return appendHpackString(dst, f.Value) -} - -// appendIndexedName appends f and index i referring indexed name -// entry, as encoded in one of "Literal Header field - Indexed Name" -// representation variants, to dst and returns the extended buffer. -// -// If f.Sensitive is true, "Never Indexed" representation is used. If -// f.Sensitive is false and indexing is true, "Incremental Indexing" -// representation is used. -func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte { - first := len(dst) - var n byte - if indexing { - n = 6 - } else { - n = 4 - } - dst = appendVarInt(dst, n, i) - dst[first] |= encodeTypeByte(indexing, f.Sensitive) - return appendHpackString(dst, f.Value) -} - -// appendTableSize appends v, as encoded in "Header Table Size Update" -// representation, to dst and returns the extended buffer. -func appendTableSize(dst []byte, v uint32) []byte { - first := len(dst) - dst = appendVarInt(dst, 5, uint64(v)) - dst[first] |= 0x20 - return dst -} - -// appendVarInt appends i, as encoded in variable integer form using n -// bit prefix, to dst and returns the extended buffer. -// -// See -// http://http2.github.io/http2-spec/compression.html#integer.representation -func appendVarInt(dst []byte, n byte, i uint64) []byte { - k := uint64((1 << n) - 1) - if i < k { - return append(dst, byte(i)) - } - dst = append(dst, byte(k)) - i -= k - for ; i >= 128; i >>= 7 { - dst = append(dst, byte(0x80|(i&0x7f))) - } - return append(dst, byte(i)) -} - -// appendHpackString appends s, as encoded in "String Literal" -// representation, to dst and returns the extended buffer. -// -// s will be encoded in Huffman codes only when it produces strictly -// shorter byte string. -func appendHpackString(dst []byte, s string) []byte { - huffmanLength := HuffmanEncodeLength(s) - if huffmanLength < uint64(len(s)) { - first := len(dst) - dst = appendVarInt(dst, 7, huffmanLength) - dst = AppendHuffmanString(dst, s) - dst[first] |= 0x80 - } else { - dst = appendVarInt(dst, 7, uint64(len(s))) - dst = append(dst, s...) - } - return dst -} - -// encodeTypeByte returns type byte. If sensitive is true, type byte -// for "Never Indexed" representation is returned. If sensitive is -// false and indexing is true, type byte for "Incremental Indexing" -// representation is returned. Otherwise, type byte for "Without -// Indexing" is returned. -func encodeTypeByte(indexing, sensitive bool) byte { - if sensitive { - return 0x10 - } - if indexing { - return 0x40 - } - return 0 -} diff --git a/examples/golang.org/x/net/http2/hpack/encode_test.go b/examples/golang.org/x/net/http2/hpack/encode_test.go deleted file mode 100644 index 05f12db..0000000 --- a/examples/golang.org/x/net/http2/hpack/encode_test.go +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "bytes" - "encoding/hex" - "fmt" - "math/rand" - "reflect" - "strings" - "testing" -) - -func TestEncoderTableSizeUpdate(t *testing.T) { - tests := []struct { - size1, size2 uint32 - wantHex string - }{ - // Should emit 2 table size updates (2048 and 4096) - {2048, 4096, "3fe10f 3fe11f 82"}, - - // Should emit 1 table size update (2048) - {16384, 2048, "3fe10f 82"}, - } - for _, tt := range tests { - var buf bytes.Buffer - e := NewEncoder(&buf) - e.SetMaxDynamicTableSize(tt.size1) - e.SetMaxDynamicTableSize(tt.size2) - if err := e.WriteField(pair(":method", "GET")); err != nil { - t.Fatal(err) - } - want := removeSpace(tt.wantHex) - if got := hex.EncodeToString(buf.Bytes()); got != want { - t.Errorf("e.SetDynamicTableSize %v, %v = %q; want %q", tt.size1, tt.size2, got, want) - } - } -} - -func TestEncoderWriteField(t *testing.T) { - var buf bytes.Buffer - e := NewEncoder(&buf) - var got []HeaderField - d := NewDecoder(4<<10, func(f HeaderField) { - got = append(got, f) - }) - - tests := []struct { - hdrs []HeaderField - }{ - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }}, - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }}, - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }}, - } - for i, tt := range tests { - buf.Reset() - got = got[:0] - for _, hf := range tt.hdrs { - if err := e.WriteField(hf); err != nil { - t.Fatal(err) - } - } - _, err := d.Write(buf.Bytes()) - if err != nil { - t.Errorf("%d. Decoder Write = %v", i, err) - } - if !reflect.DeepEqual(got, tt.hdrs) { - t.Errorf("%d. Decoded %+v; want %+v", i, got, tt.hdrs) - } - } -} - -func TestEncoderSearchTable(t *testing.T) { - e := NewEncoder(nil) - - e.dynTab.add(pair("foo", "bar")) - e.dynTab.add(pair("blake", "miz")) - e.dynTab.add(pair(":method", "GET")) - - tests := []struct { - hf HeaderField - wantI uint64 - wantMatch bool - }{ - // Name and Value match - {pair("foo", "bar"), uint64(staticTable.len()) + 3, true}, - {pair("blake", "miz"), uint64(staticTable.len()) + 2, true}, - {pair(":method", "GET"), 2, true}, - - // Only name match because Sensitive == true. This is allowed to match - // any ":method" entry. The current implementation uses the last entry - // added in newStaticTable. - {HeaderField{":method", "GET", true}, 3, false}, - - // Only Name matches - {pair("foo", "..."), uint64(staticTable.len()) + 3, false}, - {pair("blake", "..."), uint64(staticTable.len()) + 2, false}, - // As before, this is allowed to match any ":method" entry. - {pair(":method", "..."), 3, false}, - - // None match - {pair("foo-", "bar"), 0, false}, - } - for _, tt := range tests { - if gotI, gotMatch := e.searchTable(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch { - t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch) - } - } -} - -func TestAppendVarInt(t *testing.T) { - tests := []struct { - n byte - i uint64 - want []byte - }{ - // Fits in a byte: - {1, 0, []byte{0}}, - {2, 2, []byte{2}}, - {3, 6, []byte{6}}, - {4, 14, []byte{14}}, - {5, 30, []byte{30}}, - {6, 62, []byte{62}}, - {7, 126, []byte{126}}, - {8, 254, []byte{254}}, - - // Multiple bytes: - {5, 1337, []byte{31, 154, 10}}, - } - for _, tt := range tests { - got := appendVarInt(nil, tt.n, tt.i) - if !bytes.Equal(got, tt.want) { - t.Errorf("appendVarInt(nil, %v, %v) = %v; want %v", tt.n, tt.i, got, tt.want) - } - } -} - -func TestAppendHpackString(t *testing.T) { - tests := []struct { - s, wantHex string - }{ - // Huffman encoded - {"www.example.com", "8c f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, - - // Not Huffman encoded - {"a", "01 61"}, - - // zero length - {"", "00"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendHpackString(nil, tt.s) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendHpackString(nil, %q) = %q; want %q", tt.s, got, want) - } - } -} - -func TestAppendIndexed(t *testing.T) { - tests := []struct { - i uint64 - wantHex string - }{ - // 1 byte - {1, "81"}, - {126, "fe"}, - - // 2 bytes - {127, "ff00"}, - {128, "ff01"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendIndexed(nil, tt.i) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendIndex(nil, %v) = %q; want %q", tt.i, got, want) - } - } -} - -func TestAppendNewName(t *testing.T) { - tests := []struct { - f HeaderField - indexing bool - wantHex string - }{ - // Incremental indexing - {HeaderField{"custom-key", "custom-value", false}, true, "40 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - - // Without indexing - {HeaderField{"custom-key", "custom-value", false}, false, "00 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - - // Never indexed - {HeaderField{"custom-key", "custom-value", true}, true, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - {HeaderField{"custom-key", "custom-value", true}, false, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendNewName(nil, tt.f, tt.indexing) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendNewName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) - } - } -} - -func TestAppendIndexedName(t *testing.T) { - tests := []struct { - f HeaderField - i uint64 - indexing bool - wantHex string - }{ - // Incremental indexing - {HeaderField{":status", "302", false}, 8, true, "48 82 6402"}, - - // Without indexing - {HeaderField{":status", "302", false}, 8, false, "08 82 6402"}, - - // Never indexed - {HeaderField{":status", "302", true}, 8, true, "18 82 6402"}, - {HeaderField{":status", "302", true}, 8, false, "18 82 6402"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendIndexedName(nil, tt.f, tt.i, tt.indexing) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendIndexedName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) - } - } -} - -func TestAppendTableSize(t *testing.T) { - tests := []struct { - i uint32 - wantHex string - }{ - // Fits into 1 byte - {30, "3e"}, - - // Extra byte - {31, "3f00"}, - {32, "3f01"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendTableSize(nil, tt.i) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendTableSize(nil, %v) = %q; want %q", tt.i, got, want) - } - } -} - -func TestEncoderSetMaxDynamicTableSize(t *testing.T) { - var buf bytes.Buffer - e := NewEncoder(&buf) - tests := []struct { - v uint32 - wantUpdate bool - wantMinSize uint32 - wantMaxSize uint32 - }{ - // Set new table size to 2048 - {2048, true, 2048, 2048}, - - // Set new table size to 16384, but still limited to - // 4096 - {16384, true, 2048, 4096}, - } - for _, tt := range tests { - e.SetMaxDynamicTableSize(tt.v) - if got := e.tableSizeUpdate; tt.wantUpdate != got { - t.Errorf("e.tableSizeUpdate = %v; want %v", got, tt.wantUpdate) - } - if got := e.minSize; tt.wantMinSize != got { - t.Errorf("e.minSize = %v; want %v", got, tt.wantMinSize) - } - if got := e.dynTab.maxSize; tt.wantMaxSize != got { - t.Errorf("e.maxSize = %v; want %v", got, tt.wantMaxSize) - } - } -} - -func TestEncoderSetMaxDynamicTableSizeLimit(t *testing.T) { - e := NewEncoder(nil) - // 4095 < initialHeaderTableSize means maxSize is truncated to - // 4095. - e.SetMaxDynamicTableSizeLimit(4095) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - if got, want := e.maxSizeLimit, uint32(4095); got != want { - t.Errorf("e.maxSizeLimit = %v; want %v", got, want) - } - if got, want := e.tableSizeUpdate, true; got != want { - t.Errorf("e.tableSizeUpdate = %v; want %v", got, want) - } - // maxSize will be truncated to maxSizeLimit - e.SetMaxDynamicTableSize(16384) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - // 8192 > current maxSizeLimit, so maxSize does not change. - e.SetMaxDynamicTableSizeLimit(8192) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - if got, want := e.maxSizeLimit, uint32(8192); got != want { - t.Errorf("e.maxSizeLimit = %v; want %v", got, want) - } -} - -func removeSpace(s string) string { - return strings.Replace(s, " ", "", -1) -} - -func BenchmarkEncoderSearchTable(b *testing.B) { - e := NewEncoder(nil) - - // A sample of possible header fields. - // This is not based on any actual data from HTTP/2 traces. - var possible []HeaderField - for _, f := range staticTable.ents { - if f.Value == "" { - possible = append(possible, f) - continue - } - // Generate 5 random values, except for cookie and set-cookie, - // which we know can have many values in practice. - num := 5 - if f.Name == "cookie" || f.Name == "set-cookie" { - num = 25 - } - for i := 0; i < num; i++ { - f.Value = fmt.Sprintf("%s-%d", f.Name, i) - possible = append(possible, f) - } - } - for k := 0; k < 10; k++ { - f := HeaderField{ - Name: fmt.Sprintf("x-header-%d", k), - Sensitive: rand.Int()%2 == 0, - } - for i := 0; i < 5; i++ { - f.Value = fmt.Sprintf("%s-%d", f.Name, i) - possible = append(possible, f) - } - } - - // Add a random sample to the dynamic table. This very loosely simulates - // a history of 100 requests with 20 header fields per request. - for r := 0; r < 100*20; r++ { - f := possible[rand.Int31n(int32(len(possible)))] - // Skip if this is in the staticTable verbatim. - if _, has := staticTable.search(f); !has { - e.dynTab.add(f) - } - } - - b.ResetTimer() - for n := 0; n < b.N; n++ { - for _, f := range possible { - e.searchTable(f) - } - } -} diff --git a/examples/golang.org/x/net/http2/hpack/hpack.go b/examples/golang.org/x/net/http2/hpack/hpack.go deleted file mode 100644 index 166788c..0000000 --- a/examples/golang.org/x/net/http2/hpack/hpack.go +++ /dev/null @@ -1,496 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package hpack implements HPACK, a compression format for -// efficiently representing HTTP header fields in the context of HTTP/2. -// -// See http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-09 -package hpack - -import ( - "bytes" - "errors" - "fmt" -) - -// A DecodingError is something the spec defines as a decoding error. -type DecodingError struct { - Err error -} - -func (de DecodingError) Error() string { - return fmt.Sprintf("decoding error: %v", de.Err) -} - -// An InvalidIndexError is returned when an encoder references a table -// entry before the static table or after the end of the dynamic table. -type InvalidIndexError int - -func (e InvalidIndexError) Error() string { - return fmt.Sprintf("invalid indexed representation index %d", int(e)) -} - -// A HeaderField is a name-value pair. Both the name and value are -// treated as opaque sequences of octets. -type HeaderField struct { - Name, Value string - - // Sensitive means that this header field should never be - // indexed. - Sensitive bool -} - -// IsPseudo reports whether the header field is an http2 pseudo header. -// That is, it reports whether it starts with a colon. -// It is not otherwise guaranteed to be a valid pseudo header field, -// though. -func (hf HeaderField) IsPseudo() bool { - return len(hf.Name) != 0 && hf.Name[0] == ':' -} - -func (hf HeaderField) String() string { - var suffix string - if hf.Sensitive { - suffix = " (sensitive)" - } - return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix) -} - -// Size returns the size of an entry per RFC 7541 section 4.1. -func (hf HeaderField) Size() uint32 { - // http://http2.github.io/http2-spec/compression.html#rfc.section.4.1 - // "The size of the dynamic table is the sum of the size of - // its entries. The size of an entry is the sum of its name's - // length in octets (as defined in Section 5.2), its value's - // length in octets (see Section 5.2), plus 32. The size of - // an entry is calculated using the length of the name and - // value without any Huffman encoding applied." - - // This can overflow if somebody makes a large HeaderField - // Name and/or Value by hand, but we don't care, because that - // won't happen on the wire because the encoding doesn't allow - // it. - return uint32(len(hf.Name) + len(hf.Value) + 32) -} - -// A Decoder is the decoding context for incremental processing of -// header blocks. -type Decoder struct { - dynTab dynamicTable - emit func(f HeaderField) - - emitEnabled bool // whether calls to emit are enabled - maxStrLen int // 0 means unlimited - - // buf is the unparsed buffer. It's only written to - // saveBuf if it was truncated in the middle of a header - // block. Because it's usually not owned, we can only - // process it under Write. - buf []byte // not owned; only valid during Write - - // saveBuf is previous data passed to Write which we weren't able - // to fully parse before. Unlike buf, we own this data. - saveBuf bytes.Buffer -} - -// NewDecoder returns a new decoder with the provided maximum dynamic -// table size. The emitFunc will be called for each valid field -// parsed, in the same goroutine as calls to Write, before Write returns. -func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder { - d := &Decoder{ - emit: emitFunc, - emitEnabled: true, - } - d.dynTab.table.init() - d.dynTab.allowedMaxSize = maxDynamicTableSize - d.dynTab.setMaxSize(maxDynamicTableSize) - return d -} - -// ErrStringLength is returned by Decoder.Write when the max string length -// (as configured by Decoder.SetMaxStringLength) would be violated. -var ErrStringLength = errors.New("hpack: string too long") - -// SetMaxStringLength sets the maximum size of a HeaderField name or -// value string. If a string exceeds this length (even after any -// decompression), Write will return ErrStringLength. -// A value of 0 means unlimited and is the default from NewDecoder. -func (d *Decoder) SetMaxStringLength(n int) { - d.maxStrLen = n -} - -// SetEmitFunc changes the callback used when new header fields -// are decoded. -// It must be non-nil. It does not affect EmitEnabled. -func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) { - d.emit = emitFunc -} - -// SetEmitEnabled controls whether the emitFunc provided to NewDecoder -// should be called. The default is true. -// -// This facility exists to let servers enforce MAX_HEADER_LIST_SIZE -// while still decoding and keeping in-sync with decoder state, but -// without doing unnecessary decompression or generating unnecessary -// garbage for header fields past the limit. -func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v } - -// EmitEnabled reports whether calls to the emitFunc provided to NewDecoder -// are currently enabled. The default is true. -func (d *Decoder) EmitEnabled() bool { return d.emitEnabled } - -// TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their -// underlying buffers for garbage reasons. - -func (d *Decoder) SetMaxDynamicTableSize(v uint32) { - d.dynTab.setMaxSize(v) -} - -// SetAllowedMaxDynamicTableSize sets the upper bound that the encoded -// stream (via dynamic table size updates) may set the maximum size -// to. -func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) { - d.dynTab.allowedMaxSize = v -} - -type dynamicTable struct { - // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2 - table headerFieldTable - size uint32 // in bytes - maxSize uint32 // current maxSize - allowedMaxSize uint32 // maxSize may go up to this, inclusive -} - -func (dt *dynamicTable) setMaxSize(v uint32) { - dt.maxSize = v - dt.evict() -} - -func (dt *dynamicTable) add(f HeaderField) { - dt.table.addEntry(f) - dt.size += f.Size() - dt.evict() -} - -// If we're too big, evict old stuff. -func (dt *dynamicTable) evict() { - var n int - for dt.size > dt.maxSize && n < dt.table.len() { - dt.size -= dt.table.ents[n].Size() - n++ - } - dt.table.evictOldest(n) -} - -func (d *Decoder) maxTableIndex() int { - // This should never overflow. RFC 7540 Section 6.5.2 limits the size of - // the dynamic table to 2^32 bytes, where each entry will occupy more than - // one byte. Further, the staticTable has a fixed, small length. - return d.dynTab.table.len() + staticTable.len() -} - -func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) { - // See Section 2.3.3. - if i == 0 { - return - } - if i <= uint64(staticTable.len()) { - return staticTable.ents[i-1], true - } - if i > uint64(d.maxTableIndex()) { - return - } - // In the dynamic table, newer entries have lower indices. - // However, dt.ents[0] is the oldest entry. Hence, dt.ents is - // the reversed dynamic table. - dt := d.dynTab.table - return dt.ents[dt.len()-(int(i)-staticTable.len())], true -} - -// Decode decodes an entire block. -// -// TODO: remove this method and make it incremental later? This is -// easier for debugging now. -func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) { - var hf []HeaderField - saveFunc := d.emit - defer func() { d.emit = saveFunc }() - d.emit = func(f HeaderField) { hf = append(hf, f) } - if _, err := d.Write(p); err != nil { - return nil, err - } - if err := d.Close(); err != nil { - return nil, err - } - return hf, nil -} - -func (d *Decoder) Close() error { - if d.saveBuf.Len() > 0 { - d.saveBuf.Reset() - return DecodingError{errors.New("truncated headers")} - } - return nil -} - -func (d *Decoder) Write(p []byte) (n int, err error) { - if len(p) == 0 { - // Prevent state machine CPU attacks (making us redo - // work up to the point of finding out we don't have - // enough data) - return - } - // Only copy the data if we have to. Optimistically assume - // that p will contain a complete header block. - if d.saveBuf.Len() == 0 { - d.buf = p - } else { - d.saveBuf.Write(p) - d.buf = d.saveBuf.Bytes() - d.saveBuf.Reset() - } - - for len(d.buf) > 0 { - err = d.parseHeaderFieldRepr() - if err == errNeedMore { - // Extra paranoia, making sure saveBuf won't - // get too large. All the varint and string - // reading code earlier should already catch - // overlong things and return ErrStringLength, - // but keep this as a last resort. - const varIntOverhead = 8 // conservative - if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) { - return 0, ErrStringLength - } - d.saveBuf.Write(d.buf) - return len(p), nil - } - if err != nil { - break - } - } - return len(p), err -} - -// errNeedMore is an internal sentinel error value that means the -// buffer is truncated and we need to read more data before we can -// continue parsing. -var errNeedMore = errors.New("need more data") - -type indexType int - -const ( - indexedTrue indexType = iota - indexedFalse - indexedNever -) - -func (v indexType) indexed() bool { return v == indexedTrue } -func (v indexType) sensitive() bool { return v == indexedNever } - -// returns errNeedMore if there isn't enough data available. -// any other error is fatal. -// consumes d.buf iff it returns nil. -// precondition: must be called with len(d.buf) > 0 -func (d *Decoder) parseHeaderFieldRepr() error { - b := d.buf[0] - switch { - case b&128 != 0: - // Indexed representation. - // High bit set? - // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1 - return d.parseFieldIndexed() - case b&192 == 64: - // 6.2.1 Literal Header Field with Incremental Indexing - // 0b10xxxxxx: top two bits are 10 - // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1 - return d.parseFieldLiteral(6, indexedTrue) - case b&240 == 0: - // 6.2.2 Literal Header Field without Indexing - // 0b0000xxxx: top four bits are 0000 - // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2 - return d.parseFieldLiteral(4, indexedFalse) - case b&240 == 16: - // 6.2.3 Literal Header Field never Indexed - // 0b0001xxxx: top four bits are 0001 - // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3 - return d.parseFieldLiteral(4, indexedNever) - case b&224 == 32: - // 6.3 Dynamic Table Size Update - // Top three bits are '001'. - // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3 - return d.parseDynamicTableSizeUpdate() - } - - return DecodingError{errors.New("invalid encoding")} -} - -// (same invariants and behavior as parseHeaderFieldRepr) -func (d *Decoder) parseFieldIndexed() error { - buf := d.buf - idx, buf, err := readVarInt(7, buf) - if err != nil { - return err - } - hf, ok := d.at(idx) - if !ok { - return DecodingError{InvalidIndexError(idx)} - } - d.buf = buf - return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value}) -} - -// (same invariants and behavior as parseHeaderFieldRepr) -func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error { - buf := d.buf - nameIdx, buf, err := readVarInt(n, buf) - if err != nil { - return err - } - - var hf HeaderField - wantStr := d.emitEnabled || it.indexed() - if nameIdx > 0 { - ihf, ok := d.at(nameIdx) - if !ok { - return DecodingError{InvalidIndexError(nameIdx)} - } - hf.Name = ihf.Name - } else { - hf.Name, buf, err = d.readString(buf, wantStr) - if err != nil { - return err - } - } - hf.Value, buf, err = d.readString(buf, wantStr) - if err != nil { - return err - } - d.buf = buf - if it.indexed() { - d.dynTab.add(hf) - } - hf.Sensitive = it.sensitive() - return d.callEmit(hf) -} - -func (d *Decoder) callEmit(hf HeaderField) error { - if d.maxStrLen != 0 { - if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen { - return ErrStringLength - } - } - if d.emitEnabled { - d.emit(hf) - } - return nil -} - -// (same invariants and behavior as parseHeaderFieldRepr) -func (d *Decoder) parseDynamicTableSizeUpdate() error { - // RFC 7541, sec 4.2: This dynamic table size update MUST occur at the - // beginning of the first header block following the change to the dynamic table size. - if d.dynTab.size > 0 { - return DecodingError{errors.New("dynamic table size update MUST occur at the beginning of a header block")} - } - - buf := d.buf - size, buf, err := readVarInt(5, buf) - if err != nil { - return err - } - if size > uint64(d.dynTab.allowedMaxSize) { - return DecodingError{errors.New("dynamic table size update too large")} - } - d.dynTab.setMaxSize(uint32(size)) - d.buf = buf - return nil -} - -var errVarintOverflow = DecodingError{errors.New("varint integer overflow")} - -// readVarInt reads an unsigned variable length integer off the -// beginning of p. n is the parameter as described in -// http://http2.github.io/http2-spec/compression.html#rfc.section.5.1. -// -// n must always be between 1 and 8. -// -// The returned remain buffer is either a smaller suffix of p, or err != nil. -// The error is errNeedMore if p doesn't contain a complete integer. -func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) { - if n < 1 || n > 8 { - panic("bad n") - } - if len(p) == 0 { - return 0, p, errNeedMore - } - i = uint64(p[0]) - if n < 8 { - i &= (1 << uint64(n)) - 1 - } - if i < (1< 0 { - b := p[0] - p = p[1:] - i += uint64(b&127) << m - if b&128 == 0 { - return i, p, nil - } - m += 7 - if m >= 63 { // TODO: proper overflow check. making this up. - return 0, origP, errVarintOverflow - } - } - return 0, origP, errNeedMore -} - -// readString decodes an hpack string from p. -// -// wantStr is whether s will be used. If false, decompression and -// []byte->string garbage are skipped if s will be ignored -// anyway. This does mean that huffman decoding errors for non-indexed -// strings past the MAX_HEADER_LIST_SIZE are ignored, but the server -// is returning an error anyway, and because they're not indexed, the error -// won't affect the decoding state. -func (d *Decoder) readString(p []byte, wantStr bool) (s string, remain []byte, err error) { - if len(p) == 0 { - return "", p, errNeedMore - } - isHuff := p[0]&128 != 0 - strLen, p, err := readVarInt(7, p) - if err != nil { - return "", p, err - } - if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) { - return "", nil, ErrStringLength - } - if uint64(len(p)) < strLen { - return "", p, errNeedMore - } - if !isHuff { - if wantStr { - s = string(p[:strLen]) - } - return s, p[strLen:], nil - } - - if wantStr { - buf := bufPool.Get().(*bytes.Buffer) - buf.Reset() // don't trust others - defer bufPool.Put(buf) - if err := huffmanDecode(buf, d.maxStrLen, p[:strLen]); err != nil { - buf.Reset() - return "", nil, err - } - s = buf.String() - buf.Reset() // be nice to GC - } - return s, p[strLen:], nil -} diff --git a/examples/golang.org/x/net/http2/hpack/hpack_test.go b/examples/golang.org/x/net/http2/hpack/hpack_test.go deleted file mode 100644 index 974c35f..0000000 --- a/examples/golang.org/x/net/http2/hpack/hpack_test.go +++ /dev/null @@ -1,741 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "bytes" - "encoding/hex" - "fmt" - "math/rand" - "reflect" - "strings" - "testing" - "time" -) - -func (d *Decoder) mustAt(idx int) HeaderField { - if hf, ok := d.at(uint64(idx)); !ok { - panic(fmt.Sprintf("bogus index %d", idx)) - } else { - return hf - } -} - -func TestDynamicTableAt(t *testing.T) { - d := NewDecoder(4096, nil) - at := d.mustAt - if got, want := at(2), (pair(":method", "GET")); got != want { - t.Errorf("at(2) = %v; want %v", got, want) - } - d.dynTab.add(pair("foo", "bar")) - d.dynTab.add(pair("blake", "miz")) - if got, want := at(staticTable.len()+1), (pair("blake", "miz")); got != want { - t.Errorf("at(dyn 1) = %v; want %v", got, want) - } - if got, want := at(staticTable.len()+2), (pair("foo", "bar")); got != want { - t.Errorf("at(dyn 2) = %v; want %v", got, want) - } - if got, want := at(3), (pair(":method", "POST")); got != want { - t.Errorf("at(3) = %v; want %v", got, want) - } -} - -func TestDynamicTableSizeEvict(t *testing.T) { - d := NewDecoder(4096, nil) - if want := uint32(0); d.dynTab.size != want { - t.Fatalf("size = %d; want %d", d.dynTab.size, want) - } - add := d.dynTab.add - add(pair("blake", "eats pizza")) - if want := uint32(15 + 32); d.dynTab.size != want { - t.Fatalf("after pizza, size = %d; want %d", d.dynTab.size, want) - } - add(pair("foo", "bar")) - if want := uint32(15 + 32 + 6 + 32); d.dynTab.size != want { - t.Fatalf("after foo bar, size = %d; want %d", d.dynTab.size, want) - } - d.dynTab.setMaxSize(15 + 32 + 1 /* slop */) - if want := uint32(6 + 32); d.dynTab.size != want { - t.Fatalf("after setMaxSize, size = %d; want %d", d.dynTab.size, want) - } - if got, want := d.mustAt(staticTable.len()+1), (pair("foo", "bar")); got != want { - t.Errorf("at(dyn 1) = %v; want %v", got, want) - } - add(pair("long", strings.Repeat("x", 500))) - if want := uint32(0); d.dynTab.size != want { - t.Fatalf("after big one, size = %d; want %d", d.dynTab.size, want) - } -} - -func TestDecoderDecode(t *testing.T) { - tests := []struct { - name string - in []byte - want []HeaderField - wantDynTab []HeaderField // newest entry first - }{ - // C.2.1 Literal Header Field with Indexing - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.1 - {"C.2.1", dehex("400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"), - []HeaderField{pair("custom-key", "custom-header")}, - []HeaderField{pair("custom-key", "custom-header")}, - }, - - // C.2.2 Literal Header Field without Indexing - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.2 - {"C.2.2", dehex("040c 2f73 616d 706c 652f 7061 7468"), - []HeaderField{pair(":path", "/sample/path")}, - []HeaderField{}}, - - // C.2.3 Literal Header Field never Indexed - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.3 - {"C.2.3", dehex("1008 7061 7373 776f 7264 0673 6563 7265 74"), - []HeaderField{{"password", "secret", true}}, - []HeaderField{}}, - - // C.2.4 Indexed Header Field - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.4 - {"C.2.4", []byte("\x82"), - []HeaderField{pair(":method", "GET")}, - []HeaderField{}}, - } - for _, tt := range tests { - d := NewDecoder(4096, nil) - hf, err := d.DecodeFull(tt.in) - if err != nil { - t.Errorf("%s: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(hf, tt.want) { - t.Errorf("%s: Got %v; want %v", tt.name, hf, tt.want) - } - gotDynTab := d.dynTab.reverseCopy() - if !reflect.DeepEqual(gotDynTab, tt.wantDynTab) { - t.Errorf("%s: dynamic table after = %v; want %v", tt.name, gotDynTab, tt.wantDynTab) - } - } -} - -func (dt *dynamicTable) reverseCopy() (hf []HeaderField) { - hf = make([]HeaderField, len(dt.table.ents)) - for i := range hf { - hf[i] = dt.table.ents[len(dt.table.ents)-1-i] - } - return -} - -type encAndWant struct { - enc []byte - want []HeaderField - wantDynTab []HeaderField - wantDynSize uint32 -} - -// C.3 Request Examples without Huffman Coding -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.3 -func TestDecodeC3_NoHuffman(t *testing.T) { - testDecodeSeries(t, 4096, []encAndWant{ - {dehex("8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }, - []HeaderField{ - pair(":authority", "www.example.com"), - }, - 57, - }, - {dehex("8286 84be 5808 6e6f 2d63 6163 6865"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }, - []HeaderField{ - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 110, - }, - {dehex("8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }, - []HeaderField{ - pair("custom-key", "custom-value"), - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 164, - }, - }) -} - -// C.4 Request Examples with Huffman Coding -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.4 -func TestDecodeC4_Huffman(t *testing.T) { - testDecodeSeries(t, 4096, []encAndWant{ - {dehex("8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }, - []HeaderField{ - pair(":authority", "www.example.com"), - }, - 57, - }, - {dehex("8286 84be 5886 a8eb 1064 9cbf"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }, - []HeaderField{ - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 110, - }, - {dehex("8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }, - []HeaderField{ - pair("custom-key", "custom-value"), - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 164, - }, - }) -} - -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.5 -// "This section shows several consecutive header lists, corresponding -// to HTTP responses, on the same connection. The HTTP/2 setting -// parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 -// octets, causing some evictions to occur." -func TestDecodeC5_ResponsesNoHuff(t *testing.T) { - testDecodeSeries(t, 256, []encAndWant{ - {dehex(` -4803 3330 3258 0770 7269 7661 7465 611d -4d6f 6e2c 2032 3120 4f63 7420 3230 3133 -2032 303a 3133 3a32 3120 474d 546e 1768 -7474 7073 3a2f 2f77 7777 2e65 7861 6d70 -6c65 2e63 6f6d -`), - []HeaderField{ - pair(":status", "302"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - pair(":status", "302"), - }, - 222, - }, - {dehex("4803 3330 37c1 c0bf"), - []HeaderField{ - pair(":status", "307"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair(":status", "307"), - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - }, - 222, - }, - {dehex(` -88c1 611d 4d6f 6e2c 2032 3120 4f63 7420 -3230 3133 2032 303a 3133 3a32 3220 474d -54c0 5a04 677a 6970 7738 666f 6f3d 4153 -444a 4b48 514b 425a 584f 5157 454f 5049 -5541 5851 5745 4f49 553b 206d 6178 2d61 -6765 3d33 3630 303b 2076 6572 7369 6f6e -3d31 -`), - []HeaderField{ - pair(":status", "200"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - pair("location", "https://www.example.com"), - pair("content-encoding", "gzip"), - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - }, - []HeaderField{ - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - pair("content-encoding", "gzip"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - }, - 215, - }, - }) -} - -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.6 -// "This section shows the same examples as the previous section, but -// using Huffman encoding for the literal values. The HTTP/2 setting -// parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 -// octets, causing some evictions to occur. The eviction mechanism -// uses the length of the decoded literal values, so the same -// evictions occurs as in the previous section." -func TestDecodeC6_ResponsesHuffman(t *testing.T) { - testDecodeSeries(t, 256, []encAndWant{ - {dehex(` -4882 6402 5885 aec3 771a 4b61 96d0 7abe -9410 54d4 44a8 2005 9504 0b81 66e0 82a6 -2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8 -e9ae 82ae 43d3 -`), - []HeaderField{ - pair(":status", "302"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - pair(":status", "302"), - }, - 222, - }, - {dehex("4883 640e ffc1 c0bf"), - []HeaderField{ - pair(":status", "307"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair(":status", "307"), - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - }, - 222, - }, - {dehex(` -88c1 6196 d07a be94 1054 d444 a820 0595 -040b 8166 e084 a62d 1bff c05a 839b d9ab -77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b -3960 d5af 2708 7f36 72c1 ab27 0fb5 291f -9587 3160 65c0 03ed 4ee5 b106 3d50 07 -`), - []HeaderField{ - pair(":status", "200"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - pair("location", "https://www.example.com"), - pair("content-encoding", "gzip"), - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - }, - []HeaderField{ - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - pair("content-encoding", "gzip"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - }, - 215, - }, - }) -} - -func testDecodeSeries(t *testing.T, size uint32, steps []encAndWant) { - d := NewDecoder(size, nil) - for i, step := range steps { - hf, err := d.DecodeFull(step.enc) - if err != nil { - t.Fatalf("Error at step index %d: %v", i, err) - } - if !reflect.DeepEqual(hf, step.want) { - t.Fatalf("At step index %d: Got headers %v; want %v", i, hf, step.want) - } - gotDynTab := d.dynTab.reverseCopy() - if !reflect.DeepEqual(gotDynTab, step.wantDynTab) { - t.Errorf("After step index %d, dynamic table = %v; want %v", i, gotDynTab, step.wantDynTab) - } - if d.dynTab.size != step.wantDynSize { - t.Errorf("After step index %d, dynamic table size = %v; want %v", i, d.dynTab.size, step.wantDynSize) - } - } -} - -func TestHuffmanDecodeExcessPadding(t *testing.T) { - tests := [][]byte{ - {0xff}, // Padding Exceeds 7 bits - {0x1f, 0xff}, // {"a", 1 byte excess padding} - {0x1f, 0xff, 0xff}, // {"a", 2 byte excess padding} - {0x1f, 0xff, 0xff, 0xff}, // {"a", 3 byte excess padding} - {0xff, 0x9f, 0xff, 0xff, 0xff}, // {"a", 29 bit excess padding} - {'R', 0xbc, '0', 0xff, 0xff, 0xff, 0xff}, // Padding ends on partial symbol. - } - for i, in := range tests { - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("test-%d: decode(%q) = %v; want ErrInvalidHuffman", i, in, err) - } - } -} - -func TestHuffmanDecodeEOS(t *testing.T) { - in := []byte{0xff, 0xff, 0xff, 0xff, 0xfc} // {EOS, "?"} - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("error = %v; want ErrInvalidHuffman", err) - } -} - -func TestHuffmanDecodeMaxLengthOnTrailingByte(t *testing.T) { - in := []byte{0x00, 0x01} // {"0", "0", "0"} - var buf bytes.Buffer - if err := huffmanDecode(&buf, 2, in); err != ErrStringLength { - t.Errorf("error = %v; want ErrStringLength", err) - } -} - -func TestHuffmanDecodeCorruptPadding(t *testing.T) { - in := []byte{0x00} - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("error = %v; want ErrInvalidHuffman", err) - } -} - -func TestHuffmanDecode(t *testing.T) { - tests := []struct { - inHex, want string - }{ - {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"}, - {"a8eb 1064 9cbf", "no-cache"}, - {"25a8 49e9 5ba9 7d7f", "custom-key"}, - {"25a8 49e9 5bb8 e8b4 bf", "custom-value"}, - {"6402", "302"}, - {"aec3 771a 4b", "private"}, - {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, - {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"}, - {"9bd9 ab", "gzip"}, - {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07", - "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, - } - for i, tt := range tests { - var buf bytes.Buffer - in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1)) - if err != nil { - t.Errorf("%d. hex input error: %v", i, err) - continue - } - if _, err := HuffmanDecode(&buf, in); err != nil { - t.Errorf("%d. decode error: %v", i, err) - continue - } - if got := buf.String(); tt.want != got { - t.Errorf("%d. decode = %q; want %q", i, got, tt.want) - } - } -} - -func TestAppendHuffmanString(t *testing.T) { - tests := []struct { - in, want string - }{ - {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, - {"no-cache", "a8eb 1064 9cbf"}, - {"custom-key", "25a8 49e9 5ba9 7d7f"}, - {"custom-value", "25a8 49e9 5bb8 e8b4 bf"}, - {"302", "6402"}, - {"private", "aec3 771a 4b"}, - {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"}, - {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"}, - {"gzip", "9bd9 ab"}, - {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", - "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"}, - } - for i, tt := range tests { - buf := []byte{} - want := strings.Replace(tt.want, " ", "", -1) - buf = AppendHuffmanString(buf, tt.in) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("%d. encode = %q; want %q", i, got, want) - } - } -} - -func TestHuffmanMaxStrLen(t *testing.T) { - const msg = "Some string" - huff := AppendHuffmanString(nil, msg) - - testGood := func(max int) { - var out bytes.Buffer - if err := huffmanDecode(&out, max, huff); err != nil { - t.Errorf("For maxLen=%d, unexpected error: %v", max, err) - } - if out.String() != msg { - t.Errorf("For maxLen=%d, out = %q; want %q", max, out.String(), msg) - } - } - testGood(0) - testGood(len(msg)) - testGood(len(msg) + 1) - - var out bytes.Buffer - if err := huffmanDecode(&out, len(msg)-1, huff); err != ErrStringLength { - t.Errorf("err = %v; want ErrStringLength", err) - } -} - -func TestHuffmanRoundtripStress(t *testing.T) { - const Len = 50 // of uncompressed string - input := make([]byte, Len) - var output bytes.Buffer - var huff []byte - - n := 5000 - if testing.Short() { - n = 100 - } - seed := time.Now().UnixNano() - t.Logf("Seed = %v", seed) - src := rand.New(rand.NewSource(seed)) - var encSize int64 - for i := 0; i < n; i++ { - for l := range input { - input[l] = byte(src.Intn(256)) - } - huff = AppendHuffmanString(huff[:0], string(input)) - encSize += int64(len(huff)) - output.Reset() - if err := huffmanDecode(&output, 0, huff); err != nil { - t.Errorf("Failed to decode %q -> %q -> error %v", input, huff, err) - continue - } - if !bytes.Equal(output.Bytes(), input) { - t.Errorf("Roundtrip failure on %q -> %q -> %q", input, huff, output.Bytes()) - } - } - t.Logf("Compressed size of original: %0.02f%% (%v -> %v)", 100*(float64(encSize)/(Len*float64(n))), Len*n, encSize) -} - -func TestHuffmanDecodeFuzz(t *testing.T) { - const Len = 50 // of compressed - var buf, zbuf bytes.Buffer - - n := 5000 - if testing.Short() { - n = 100 - } - seed := time.Now().UnixNano() - t.Logf("Seed = %v", seed) - src := rand.New(rand.NewSource(seed)) - numFail := 0 - for i := 0; i < n; i++ { - zbuf.Reset() - if i == 0 { - // Start with at least one invalid one. - zbuf.WriteString("00\x91\xff\xff\xff\xff\xc8") - } else { - for l := 0; l < Len; l++ { - zbuf.WriteByte(byte(src.Intn(256))) - } - } - - buf.Reset() - if err := huffmanDecode(&buf, 0, zbuf.Bytes()); err != nil { - if err == ErrInvalidHuffman { - numFail++ - continue - } - t.Errorf("Failed to decode %q: %v", zbuf.Bytes(), err) - continue - } - } - t.Logf("%0.02f%% are invalid (%d / %d)", 100*float64(numFail)/float64(n), numFail, n) - if numFail < 1 { - t.Error("expected at least one invalid huffman encoding (test starts with one)") - } -} - -func TestReadVarInt(t *testing.T) { - type res struct { - i uint64 - consumed int - err error - } - tests := []struct { - n byte - p []byte - want res - }{ - // Fits in a byte: - {1, []byte{0}, res{0, 1, nil}}, - {2, []byte{2}, res{2, 1, nil}}, - {3, []byte{6}, res{6, 1, nil}}, - {4, []byte{14}, res{14, 1, nil}}, - {5, []byte{30}, res{30, 1, nil}}, - {6, []byte{62}, res{62, 1, nil}}, - {7, []byte{126}, res{126, 1, nil}}, - {8, []byte{254}, res{254, 1, nil}}, - - // Doesn't fit in a byte: - {1, []byte{1}, res{0, 0, errNeedMore}}, - {2, []byte{3}, res{0, 0, errNeedMore}}, - {3, []byte{7}, res{0, 0, errNeedMore}}, - {4, []byte{15}, res{0, 0, errNeedMore}}, - {5, []byte{31}, res{0, 0, errNeedMore}}, - {6, []byte{63}, res{0, 0, errNeedMore}}, - {7, []byte{127}, res{0, 0, errNeedMore}}, - {8, []byte{255}, res{0, 0, errNeedMore}}, - - // Ignoring top bits: - {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111 - {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100 - {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101 - - // Extra byte: - {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte - - // Short a byte: - {5, []byte{191, 154}, res{0, 0, errNeedMore}}, - - // integer overflow: - {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}}, - } - for _, tt := range tests { - i, remain, err := readVarInt(tt.n, tt.p) - consumed := len(tt.p) - len(remain) - got := res{i, consumed, err} - if got != tt.want { - t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want) - } - } -} - -// Fuzz crash, originally reported at https://github.com/bradfitz/http2/issues/56 -func TestHuffmanFuzzCrash(t *testing.T) { - got, err := HuffmanDecodeToString([]byte("00\x91\xff\xff\xff\xff\xc8")) - if got != "" { - t.Errorf("Got %q; want empty string", got) - } - if err != ErrInvalidHuffman { - t.Errorf("Err = %v; want ErrInvalidHuffman", err) - } -} - -func pair(name, value string) HeaderField { - return HeaderField{Name: name, Value: value} -} - -func dehex(s string) []byte { - s = strings.Replace(s, " ", "", -1) - s = strings.Replace(s, "\n", "", -1) - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} - -func TestEmitEnabled(t *testing.T) { - var buf bytes.Buffer - enc := NewEncoder(&buf) - enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) - enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) - - numCallback := 0 - var dec *Decoder - dec = NewDecoder(8<<20, func(HeaderField) { - numCallback++ - dec.SetEmitEnabled(false) - }) - if !dec.EmitEnabled() { - t.Errorf("initial emit enabled = false; want true") - } - if _, err := dec.Write(buf.Bytes()); err != nil { - t.Error(err) - } - if numCallback != 1 { - t.Errorf("num callbacks = %d; want 1", numCallback) - } - if dec.EmitEnabled() { - t.Errorf("emit enabled = true; want false") - } -} - -func TestSaveBufLimit(t *testing.T) { - const maxStr = 1 << 10 - var got []HeaderField - dec := NewDecoder(initialHeaderTableSize, func(hf HeaderField) { - got = append(got, hf) - }) - dec.SetMaxStringLength(maxStr) - var frag []byte - frag = append(frag[:0], encodeTypeByte(false, false)) - frag = appendVarInt(frag, 7, 3) - frag = append(frag, "foo"...) - frag = appendVarInt(frag, 7, 3) - frag = append(frag, "bar"...) - - if _, err := dec.Write(frag); err != nil { - t.Fatal(err) - } - - want := []HeaderField{{Name: "foo", Value: "bar"}} - if !reflect.DeepEqual(got, want) { - t.Errorf("After small writes, got %v; want %v", got, want) - } - - frag = append(frag[:0], encodeTypeByte(false, false)) - frag = appendVarInt(frag, 7, maxStr*3) - frag = append(frag, make([]byte, maxStr*3)...) - - _, err := dec.Write(frag) - if err != ErrStringLength { - t.Fatalf("Write error = %v; want ErrStringLength", err) - } -} - -func TestDynamicSizeUpdate(t *testing.T) { - var buf bytes.Buffer - enc := NewEncoder(&buf) - enc.SetMaxDynamicTableSize(255) - enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) - - d := NewDecoder(4096, nil) - _, err := d.DecodeFull(buf.Bytes()) - if err != nil { - t.Fatalf("unexpected error: got = %v", err) - } - - // must fail since the dynamic table update must be at the beginning - _, err = d.DecodeFull(buf.Bytes()) - if err == nil { - t.Fatalf("dynamic table size update not at the beginning of a header block") - } -} diff --git a/examples/golang.org/x/net/http2/hpack/huffman.go b/examples/golang.org/x/net/http2/hpack/huffman.go deleted file mode 100644 index 8850e39..0000000 --- a/examples/golang.org/x/net/http2/hpack/huffman.go +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "bytes" - "errors" - "io" - "sync" -) - -var bufPool = sync.Pool{ - New: func() interface{} { return new(bytes.Buffer) }, -} - -// HuffmanDecode decodes the string in v and writes the expanded -// result to w, returning the number of bytes written to w and the -// Write call's return value. At most one Write call is made. -func HuffmanDecode(w io.Writer, v []byte) (int, error) { - buf := bufPool.Get().(*bytes.Buffer) - buf.Reset() - defer bufPool.Put(buf) - if err := huffmanDecode(buf, 0, v); err != nil { - return 0, err - } - return w.Write(buf.Bytes()) -} - -// HuffmanDecodeToString decodes the string in v. -func HuffmanDecodeToString(v []byte) (string, error) { - buf := bufPool.Get().(*bytes.Buffer) - buf.Reset() - defer bufPool.Put(buf) - if err := huffmanDecode(buf, 0, v); err != nil { - return "", err - } - return buf.String(), nil -} - -// ErrInvalidHuffman is returned for errors found decoding -// Huffman-encoded strings. -var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data") - -// huffmanDecode decodes v to buf. -// If maxLen is greater than 0, attempts to write more to buf than -// maxLen bytes will return ErrStringLength. -func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { - n := rootHuffmanNode - // cur is the bit buffer that has not been fed into n. - // cbits is the number of low order bits in cur that are valid. - // sbits is the number of bits of the symbol prefix being decoded. - cur, cbits, sbits := uint(0), uint8(0), uint8(0) - for _, b := range v { - cur = cur<<8 | uint(b) - cbits += 8 - sbits += 8 - for cbits >= 8 { - idx := byte(cur >> (cbits - 8)) - n = n.children[idx] - if n == nil { - return ErrInvalidHuffman - } - if n.children == nil { - if maxLen != 0 && buf.Len() == maxLen { - return ErrStringLength - } - buf.WriteByte(n.sym) - cbits -= n.codeLen - n = rootHuffmanNode - sbits = cbits - } else { - cbits -= 8 - } - } - } - for cbits > 0 { - n = n.children[byte(cur<<(8-cbits))] - if n == nil { - return ErrInvalidHuffman - } - if n.children != nil || n.codeLen > cbits { - break - } - if maxLen != 0 && buf.Len() == maxLen { - return ErrStringLength - } - buf.WriteByte(n.sym) - cbits -= n.codeLen - n = rootHuffmanNode - sbits = cbits - } - if sbits > 7 { - // Either there was an incomplete symbol, or overlong padding. - // Both are decoding errors per RFC 7541 section 5.2. - return ErrInvalidHuffman - } - if mask := uint(1< 8 { - codeLen -= 8 - i := uint8(code >> codeLen) - if cur.children[i] == nil { - cur.children[i] = newInternalNode() - } - cur = cur.children[i] - } - shift := 8 - codeLen - start, end := int(uint8(code<> (nbits - rembits)) - dst[len(dst)-1] |= t - } - - return dst -} - -// HuffmanEncodeLength returns the number of bytes required to encode -// s in Huffman codes. The result is round up to byte boundary. -func HuffmanEncodeLength(s string) uint64 { - n := uint64(0) - for i := 0; i < len(s); i++ { - n += uint64(huffmanCodeLen[s[i]]) - } - return (n + 7) / 8 -} - -// appendByteToHuffmanCode appends Huffman code for c to dst and -// returns the extended buffer and the remaining bits in the last -// element. The appending is not byte aligned and the remaining bits -// in the last element of dst is given in rembits. -func appendByteToHuffmanCode(dst []byte, rembits uint8, c byte) ([]byte, uint8) { - code := huffmanCodes[c] - nbits := huffmanCodeLen[c] - - for { - if rembits > nbits { - t := uint8(code << (rembits - nbits)) - dst[len(dst)-1] |= t - rembits -= nbits - break - } - - t := uint8(code >> (nbits - rembits)) - dst[len(dst)-1] |= t - - nbits -= rembits - rembits = 8 - - if nbits == 0 { - break - } - - dst = append(dst, 0) - } - - return dst, rembits -} diff --git a/examples/golang.org/x/net/http2/hpack/tables.go b/examples/golang.org/x/net/http2/hpack/tables.go deleted file mode 100644 index a66cfbe..0000000 --- a/examples/golang.org/x/net/http2/hpack/tables.go +++ /dev/null @@ -1,479 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "fmt" -) - -// headerFieldTable implements a list of HeaderFields. -// This is used to implement the static and dynamic tables. -type headerFieldTable struct { - // For static tables, entries are never evicted. - // - // For dynamic tables, entries are evicted from ents[0] and added to the end. - // Each entry has a unique id that starts at one and increments for each - // entry that is added. This unique id is stable across evictions, meaning - // it can be used as a pointer to a specific entry. As in hpack, unique ids - // are 1-based. The unique id for ents[k] is k + evictCount + 1. - // - // Zero is not a valid unique id. - // - // evictCount should not overflow in any remotely practical situation. In - // practice, we will have one dynamic table per HTTP/2 connection. If we - // assume a very powerful server that handles 1M QPS per connection and each - // request adds (then evicts) 100 entries from the table, it would still take - // 2M years for evictCount to overflow. - ents []HeaderField - evictCount uint64 - - // byName maps a HeaderField name to the unique id of the newest entry with - // the same name. See above for a definition of "unique id". - byName map[string]uint64 - - // byNameValue maps a HeaderField name/value pair to the unique id of the newest - // entry with the same name and value. See above for a definition of "unique id". - byNameValue map[pairNameValue]uint64 -} - -type pairNameValue struct { - name, value string -} - -func (t *headerFieldTable) init() { - t.byName = make(map[string]uint64) - t.byNameValue = make(map[pairNameValue]uint64) -} - -// len reports the number of entries in the table. -func (t *headerFieldTable) len() int { - return len(t.ents) -} - -// addEntry adds a new entry. -func (t *headerFieldTable) addEntry(f HeaderField) { - id := uint64(t.len()) + t.evictCount + 1 - t.byName[f.Name] = id - t.byNameValue[pairNameValue{f.Name, f.Value}] = id - t.ents = append(t.ents, f) -} - -// evictOldest evicts the n oldest entries in the table. -func (t *headerFieldTable) evictOldest(n int) { - if n > t.len() { - panic(fmt.Sprintf("evictOldest(%v) on table with %v entries", n, t.len())) - } - for k := 0; k < n; k++ { - f := t.ents[k] - id := t.evictCount + uint64(k) + 1 - if t.byName[f.Name] == id { - delete(t.byName, f.Name) - } - if p := (pairNameValue{f.Name, f.Value}); t.byNameValue[p] == id { - delete(t.byNameValue, p) - } - } - copy(t.ents, t.ents[n:]) - for k := t.len() - n; k < t.len(); k++ { - t.ents[k] = HeaderField{} // so strings can be garbage collected - } - t.ents = t.ents[:t.len()-n] - if t.evictCount+uint64(n) < t.evictCount { - panic("evictCount overflow") - } - t.evictCount += uint64(n) -} - -// search finds f in the table. If there is no match, i is 0. -// If both name and value match, i is the matched index and nameValueMatch -// becomes true. If only name matches, i points to that index and -// nameValueMatch becomes false. -// -// The returned index is a 1-based HPACK index. For dynamic tables, HPACK says -// that index 1 should be the newest entry, but t.ents[0] is the oldest entry, -// meaning t.ents is reversed for dynamic tables. Hence, when t is a dynamic -// table, the return value i actually refers to the entry t.ents[t.len()-i]. -// -// All tables are assumed to be a dynamic tables except for the global -// staticTable pointer. -// -// See Section 2.3.3. -func (t *headerFieldTable) search(f HeaderField) (i uint64, nameValueMatch bool) { - if !f.Sensitive { - if id := t.byNameValue[pairNameValue{f.Name, f.Value}]; id != 0 { - return t.idToIndex(id), true - } - } - if id := t.byName[f.Name]; id != 0 { - return t.idToIndex(id), false - } - return 0, false -} - -// idToIndex converts a unique id to an HPACK index. -// See Section 2.3.3. -func (t *headerFieldTable) idToIndex(id uint64) uint64 { - if id <= t.evictCount { - panic(fmt.Sprintf("id (%v) <= evictCount (%v)", id, t.evictCount)) - } - k := id - t.evictCount - 1 // convert id to an index t.ents[k] - if t != staticTable { - return uint64(t.len()) - k // dynamic table - } - return k + 1 -} - -// http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-07#appendix-B -var staticTable = newStaticTable() -var staticTableEntries = [...]HeaderField{ - {Name: ":authority"}, - {Name: ":method", Value: "GET"}, - {Name: ":method", Value: "POST"}, - {Name: ":path", Value: "/"}, - {Name: ":path", Value: "/index.html"}, - {Name: ":scheme", Value: "http"}, - {Name: ":scheme", Value: "https"}, - {Name: ":status", Value: "200"}, - {Name: ":status", Value: "204"}, - {Name: ":status", Value: "206"}, - {Name: ":status", Value: "304"}, - {Name: ":status", Value: "400"}, - {Name: ":status", Value: "404"}, - {Name: ":status", Value: "500"}, - {Name: "accept-charset"}, - {Name: "accept-encoding", Value: "gzip, deflate"}, - {Name: "accept-language"}, - {Name: "accept-ranges"}, - {Name: "accept"}, - {Name: "access-control-allow-origin"}, - {Name: "age"}, - {Name: "allow"}, - {Name: "authorization"}, - {Name: "cache-control"}, - {Name: "content-disposition"}, - {Name: "content-encoding"}, - {Name: "content-language"}, - {Name: "content-length"}, - {Name: "content-location"}, - {Name: "content-range"}, - {Name: "content-type"}, - {Name: "cookie"}, - {Name: "date"}, - {Name: "etag"}, - {Name: "expect"}, - {Name: "expires"}, - {Name: "from"}, - {Name: "host"}, - {Name: "if-match"}, - {Name: "if-modified-since"}, - {Name: "if-none-match"}, - {Name: "if-range"}, - {Name: "if-unmodified-since"}, - {Name: "last-modified"}, - {Name: "link"}, - {Name: "location"}, - {Name: "max-forwards"}, - {Name: "proxy-authenticate"}, - {Name: "proxy-authorization"}, - {Name: "range"}, - {Name: "referer"}, - {Name: "refresh"}, - {Name: "retry-after"}, - {Name: "server"}, - {Name: "set-cookie"}, - {Name: "strict-transport-security"}, - {Name: "transfer-encoding"}, - {Name: "user-agent"}, - {Name: "vary"}, - {Name: "via"}, - {Name: "www-authenticate"}, -} - -func newStaticTable() *headerFieldTable { - t := &headerFieldTable{} - t.init() - for _, e := range staticTableEntries[:] { - t.addEntry(e) - } - return t -} - -var huffmanCodes = [256]uint32{ - 0x1ff8, - 0x7fffd8, - 0xfffffe2, - 0xfffffe3, - 0xfffffe4, - 0xfffffe5, - 0xfffffe6, - 0xfffffe7, - 0xfffffe8, - 0xffffea, - 0x3ffffffc, - 0xfffffe9, - 0xfffffea, - 0x3ffffffd, - 0xfffffeb, - 0xfffffec, - 0xfffffed, - 0xfffffee, - 0xfffffef, - 0xffffff0, - 0xffffff1, - 0xffffff2, - 0x3ffffffe, - 0xffffff3, - 0xffffff4, - 0xffffff5, - 0xffffff6, - 0xffffff7, - 0xffffff8, - 0xffffff9, - 0xffffffa, - 0xffffffb, - 0x14, - 0x3f8, - 0x3f9, - 0xffa, - 0x1ff9, - 0x15, - 0xf8, - 0x7fa, - 0x3fa, - 0x3fb, - 0xf9, - 0x7fb, - 0xfa, - 0x16, - 0x17, - 0x18, - 0x0, - 0x1, - 0x2, - 0x19, - 0x1a, - 0x1b, - 0x1c, - 0x1d, - 0x1e, - 0x1f, - 0x5c, - 0xfb, - 0x7ffc, - 0x20, - 0xffb, - 0x3fc, - 0x1ffa, - 0x21, - 0x5d, - 0x5e, - 0x5f, - 0x60, - 0x61, - 0x62, - 0x63, - 0x64, - 0x65, - 0x66, - 0x67, - 0x68, - 0x69, - 0x6a, - 0x6b, - 0x6c, - 0x6d, - 0x6e, - 0x6f, - 0x70, - 0x71, - 0x72, - 0xfc, - 0x73, - 0xfd, - 0x1ffb, - 0x7fff0, - 0x1ffc, - 0x3ffc, - 0x22, - 0x7ffd, - 0x3, - 0x23, - 0x4, - 0x24, - 0x5, - 0x25, - 0x26, - 0x27, - 0x6, - 0x74, - 0x75, - 0x28, - 0x29, - 0x2a, - 0x7, - 0x2b, - 0x76, - 0x2c, - 0x8, - 0x9, - 0x2d, - 0x77, - 0x78, - 0x79, - 0x7a, - 0x7b, - 0x7ffe, - 0x7fc, - 0x3ffd, - 0x1ffd, - 0xffffffc, - 0xfffe6, - 0x3fffd2, - 0xfffe7, - 0xfffe8, - 0x3fffd3, - 0x3fffd4, - 0x3fffd5, - 0x7fffd9, - 0x3fffd6, - 0x7fffda, - 0x7fffdb, - 0x7fffdc, - 0x7fffdd, - 0x7fffde, - 0xffffeb, - 0x7fffdf, - 0xffffec, - 0xffffed, - 0x3fffd7, - 0x7fffe0, - 0xffffee, - 0x7fffe1, - 0x7fffe2, - 0x7fffe3, - 0x7fffe4, - 0x1fffdc, - 0x3fffd8, - 0x7fffe5, - 0x3fffd9, - 0x7fffe6, - 0x7fffe7, - 0xffffef, - 0x3fffda, - 0x1fffdd, - 0xfffe9, - 0x3fffdb, - 0x3fffdc, - 0x7fffe8, - 0x7fffe9, - 0x1fffde, - 0x7fffea, - 0x3fffdd, - 0x3fffde, - 0xfffff0, - 0x1fffdf, - 0x3fffdf, - 0x7fffeb, - 0x7fffec, - 0x1fffe0, - 0x1fffe1, - 0x3fffe0, - 0x1fffe2, - 0x7fffed, - 0x3fffe1, - 0x7fffee, - 0x7fffef, - 0xfffea, - 0x3fffe2, - 0x3fffe3, - 0x3fffe4, - 0x7ffff0, - 0x3fffe5, - 0x3fffe6, - 0x7ffff1, - 0x3ffffe0, - 0x3ffffe1, - 0xfffeb, - 0x7fff1, - 0x3fffe7, - 0x7ffff2, - 0x3fffe8, - 0x1ffffec, - 0x3ffffe2, - 0x3ffffe3, - 0x3ffffe4, - 0x7ffffde, - 0x7ffffdf, - 0x3ffffe5, - 0xfffff1, - 0x1ffffed, - 0x7fff2, - 0x1fffe3, - 0x3ffffe6, - 0x7ffffe0, - 0x7ffffe1, - 0x3ffffe7, - 0x7ffffe2, - 0xfffff2, - 0x1fffe4, - 0x1fffe5, - 0x3ffffe8, - 0x3ffffe9, - 0xffffffd, - 0x7ffffe3, - 0x7ffffe4, - 0x7ffffe5, - 0xfffec, - 0xfffff3, - 0xfffed, - 0x1fffe6, - 0x3fffe9, - 0x1fffe7, - 0x1fffe8, - 0x7ffff3, - 0x3fffea, - 0x3fffeb, - 0x1ffffee, - 0x1ffffef, - 0xfffff4, - 0xfffff5, - 0x3ffffea, - 0x7ffff4, - 0x3ffffeb, - 0x7ffffe6, - 0x3ffffec, - 0x3ffffed, - 0x7ffffe7, - 0x7ffffe8, - 0x7ffffe9, - 0x7ffffea, - 0x7ffffeb, - 0xffffffe, - 0x7ffffec, - 0x7ffffed, - 0x7ffffee, - 0x7ffffef, - 0x7fffff0, - 0x3ffffee, -} - -var huffmanCodeLen = [256]uint8{ - 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, - 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, - 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, - 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, - 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, - 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, - 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, - 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, - 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, - 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, - 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, - 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, - 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, - 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, -} diff --git a/examples/golang.org/x/net/http2/hpack/tables_test.go b/examples/golang.org/x/net/http2/hpack/tables_test.go deleted file mode 100644 index d963f36..0000000 --- a/examples/golang.org/x/net/http2/hpack/tables_test.go +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hpack - -import ( - "bufio" - "regexp" - "strconv" - "strings" - "testing" -) - -func TestHeaderFieldTable(t *testing.T) { - table := &headerFieldTable{} - table.init() - table.addEntry(pair("key1", "value1-1")) - table.addEntry(pair("key2", "value2-1")) - table.addEntry(pair("key1", "value1-2")) - table.addEntry(pair("key3", "value3-1")) - table.addEntry(pair("key4", "value4-1")) - table.addEntry(pair("key2", "value2-2")) - - // Tests will be run twice: once before evicting anything, and - // again after evicting the three oldest entries. - tests := []struct { - f HeaderField - beforeWantStaticI uint64 - beforeWantMatch bool - afterWantStaticI uint64 - afterWantMatch bool - }{ - {HeaderField{"key1", "value1-1", false}, 1, true, 0, false}, - {HeaderField{"key1", "value1-2", false}, 3, true, 0, false}, - {HeaderField{"key1", "value1-3", false}, 3, false, 0, false}, - {HeaderField{"key2", "value2-1", false}, 2, true, 3, false}, - {HeaderField{"key2", "value2-2", false}, 6, true, 3, true}, - {HeaderField{"key2", "value2-3", false}, 6, false, 3, false}, - {HeaderField{"key4", "value4-1", false}, 5, true, 2, true}, - // Name match only, because sensitive. - {HeaderField{"key4", "value4-1", true}, 5, false, 2, false}, - // Key not found. - {HeaderField{"key5", "value5-x", false}, 0, false, 0, false}, - } - - staticToDynamic := func(i uint64) uint64 { - if i == 0 { - return 0 - } - return uint64(table.len()) - i + 1 // dynamic is the reversed table - } - - searchStatic := func(f HeaderField) (uint64, bool) { - old := staticTable - staticTable = table - defer func() { staticTable = old }() - return staticTable.search(f) - } - - searchDynamic := func(f HeaderField) (uint64, bool) { - return table.search(f) - } - - for _, test := range tests { - gotI, gotMatch := searchStatic(test.f) - if wantI, wantMatch := test.beforeWantStaticI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("before evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - gotI, gotMatch = searchDynamic(test.f) - wantDynamicI := staticToDynamic(test.beforeWantStaticI) - if wantI, wantMatch := wantDynamicI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("before evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - } - - table.evictOldest(3) - - for _, test := range tests { - gotI, gotMatch := searchStatic(test.f) - if wantI, wantMatch := test.afterWantStaticI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("after evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - gotI, gotMatch = searchDynamic(test.f) - wantDynamicI := staticToDynamic(test.afterWantStaticI) - if wantI, wantMatch := wantDynamicI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("after evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - } -} - -func TestHeaderFieldTable_LookupMapEviction(t *testing.T) { - table := &headerFieldTable{} - table.init() - table.addEntry(pair("key1", "value1-1")) - table.addEntry(pair("key2", "value2-1")) - table.addEntry(pair("key1", "value1-2")) - table.addEntry(pair("key3", "value3-1")) - table.addEntry(pair("key4", "value4-1")) - table.addEntry(pair("key2", "value2-2")) - - // evict all pairs - table.evictOldest(table.len()) - - if l := table.len(); l > 0 { - t.Errorf("table.len() = %d, want 0", l) - } - - if l := len(table.byName); l > 0 { - t.Errorf("len(table.byName) = %d, want 0", l) - } - - if l := len(table.byNameValue); l > 0 { - t.Errorf("len(table.byNameValue) = %d, want 0", l) - } -} - -func TestStaticTable(t *testing.T) { - fromSpec := ` - +-------+-----------------------------+---------------+ - | 1 | :authority | | - | 2 | :method | GET | - | 3 | :method | POST | - | 4 | :path | / | - | 5 | :path | /index.html | - | 6 | :scheme | http | - | 7 | :scheme | https | - | 8 | :status | 200 | - | 9 | :status | 204 | - | 10 | :status | 206 | - | 11 | :status | 304 | - | 12 | :status | 400 | - | 13 | :status | 404 | - | 14 | :status | 500 | - | 15 | accept-charset | | - | 16 | accept-encoding | gzip, deflate | - | 17 | accept-language | | - | 18 | accept-ranges | | - | 19 | accept | | - | 20 | access-control-allow-origin | | - | 21 | age | | - | 22 | allow | | - | 23 | authorization | | - | 24 | cache-control | | - | 25 | content-disposition | | - | 26 | content-encoding | | - | 27 | content-language | | - | 28 | content-length | | - | 29 | content-location | | - | 30 | content-range | | - | 31 | content-type | | - | 32 | cookie | | - | 33 | date | | - | 34 | etag | | - | 35 | expect | | - | 36 | expires | | - | 37 | from | | - | 38 | host | | - | 39 | if-match | | - | 40 | if-modified-since | | - | 41 | if-none-match | | - | 42 | if-range | | - | 43 | if-unmodified-since | | - | 44 | last-modified | | - | 45 | link | | - | 46 | location | | - | 47 | max-forwards | | - | 48 | proxy-authenticate | | - | 49 | proxy-authorization | | - | 50 | range | | - | 51 | referer | | - | 52 | refresh | | - | 53 | retry-after | | - | 54 | server | | - | 55 | set-cookie | | - | 56 | strict-transport-security | | - | 57 | transfer-encoding | | - | 58 | user-agent | | - | 59 | vary | | - | 60 | via | | - | 61 | www-authenticate | | - +-------+-----------------------------+---------------+ -` - bs := bufio.NewScanner(strings.NewReader(fromSpec)) - re := regexp.MustCompile(`\| (\d+)\s+\| (\S+)\s*\| (\S(.*\S)?)?\s+\|`) - for bs.Scan() { - l := bs.Text() - if !strings.Contains(l, "|") { - continue - } - m := re.FindStringSubmatch(l) - if m == nil { - continue - } - i, err := strconv.Atoi(m[1]) - if err != nil { - t.Errorf("Bogus integer on line %q", l) - continue - } - if i < 1 || i > staticTable.len() { - t.Errorf("Bogus index %d on line %q", i, l) - continue - } - if got, want := staticTable.ents[i-1].Name, m[2]; got != want { - t.Errorf("header index %d name = %q; want %q", i, got, want) - } - if got, want := staticTable.ents[i-1].Value, m[3]; got != want { - t.Errorf("header index %d value = %q; want %q", i, got, want) - } - } - if err := bs.Err(); err != nil { - t.Error(err) - } -} diff --git a/examples/golang.org/x/net/http2/http2.go b/examples/golang.org/x/net/http2/http2.go deleted file mode 100644 index c824282..0000000 --- a/examples/golang.org/x/net/http2/http2.go +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package http2 implements the HTTP/2 protocol. -// -// This package is low-level and intended to be used directly by very -// few people. Most users will use it indirectly through the automatic -// use by the net/http package (from Go 1.6 and later). -// For use in earlier Go versions see ConfigureServer. (Transport support -// requires Go 1.6 or later) -// -// See https://http2.github.io/ for more information on HTTP/2. -// -// See https://http2.golang.org/ for a test server running this code. -// -package http2 // import "golang.org/x/net/http2" - -import ( - "bufio" - "crypto/tls" - "errors" - "fmt" - "io" - "net/http" - "os" - "sort" - "strconv" - "strings" - "sync" - - "golang.org/x/net/http/httpguts" -) - -var ( - VerboseLogs bool - logFrameWrites bool - logFrameReads bool - inTests bool -) - -func init() { - e := os.Getenv("GODEBUG") - if strings.Contains(e, "http2debug=1") { - VerboseLogs = true - } - if strings.Contains(e, "http2debug=2") { - VerboseLogs = true - logFrameWrites = true - logFrameReads = true - } -} - -const ( - // ClientPreface is the string that must be sent by new - // connections from clients. - ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" - - // SETTINGS_MAX_FRAME_SIZE default - // http://http2.github.io/http2-spec/#rfc.section.6.5.2 - initialMaxFrameSize = 16384 - - // NextProtoTLS is the NPN/ALPN protocol negotiated during - // HTTP/2's TLS setup. - NextProtoTLS = "h2" - - // http://http2.github.io/http2-spec/#SettingValues - initialHeaderTableSize = 4096 - - initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size - - defaultMaxReadFrameSize = 1 << 20 -) - -var ( - clientPreface = []byte(ClientPreface) -) - -type streamState int - -// HTTP/2 stream states. -// -// See http://tools.ietf.org/html/rfc7540#section-5.1. -// -// For simplicity, the server code merges "reserved (local)" into -// "half-closed (remote)". This is one less state transition to track. -// The only downside is that we send PUSH_PROMISEs slightly less -// liberally than allowable. More discussion here: -// https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html -// -// "reserved (remote)" is omitted since the client code does not -// support server push. -const ( - stateIdle streamState = iota - stateOpen - stateHalfClosedLocal - stateHalfClosedRemote - stateClosed -) - -var stateName = [...]string{ - stateIdle: "Idle", - stateOpen: "Open", - stateHalfClosedLocal: "HalfClosedLocal", - stateHalfClosedRemote: "HalfClosedRemote", - stateClosed: "Closed", -} - -func (st streamState) String() string { - return stateName[st] -} - -// Setting is a setting parameter: which setting it is, and its value. -type Setting struct { - // ID is which setting is being set. - // See http://http2.github.io/http2-spec/#SettingValues - ID SettingID - - // Val is the value. - Val uint32 -} - -func (s Setting) String() string { - return fmt.Sprintf("[%v = %d]", s.ID, s.Val) -} - -// Valid reports whether the setting is valid. -func (s Setting) Valid() error { - // Limits and error codes from 6.5.2 Defined SETTINGS Parameters - switch s.ID { - case SettingEnablePush: - if s.Val != 1 && s.Val != 0 { - return ConnectionError(ErrCodeProtocol) - } - case SettingInitialWindowSize: - if s.Val > 1<<31-1 { - return ConnectionError(ErrCodeFlowControl) - } - case SettingMaxFrameSize: - if s.Val < 16384 || s.Val > 1<<24-1 { - return ConnectionError(ErrCodeProtocol) - } - } - return nil -} - -// A SettingID is an HTTP/2 setting as defined in -// http://http2.github.io/http2-spec/#iana-settings -type SettingID uint16 - -const ( - SettingHeaderTableSize SettingID = 0x1 - SettingEnablePush SettingID = 0x2 - SettingMaxConcurrentStreams SettingID = 0x3 - SettingInitialWindowSize SettingID = 0x4 - SettingMaxFrameSize SettingID = 0x5 - SettingMaxHeaderListSize SettingID = 0x6 -) - -var settingName = map[SettingID]string{ - SettingHeaderTableSize: "HEADER_TABLE_SIZE", - SettingEnablePush: "ENABLE_PUSH", - SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS", - SettingInitialWindowSize: "INITIAL_WINDOW_SIZE", - SettingMaxFrameSize: "MAX_FRAME_SIZE", - SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE", -} - -func (s SettingID) String() string { - if v, ok := settingName[s]; ok { - return v - } - return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s)) -} - -var ( - errInvalidHeaderFieldName = errors.New("http2: invalid header field name") - errInvalidHeaderFieldValue = errors.New("http2: invalid header field value") -) - -// validWireHeaderFieldName reports whether v is a valid header field -// name (key). See httpguts.ValidHeaderName for the base rules. -// -// Further, http2 says: -// "Just as in HTTP/1.x, header field names are strings of ASCII -// characters that are compared in a case-insensitive -// fashion. However, header field names MUST be converted to -// lowercase prior to their encoding in HTTP/2. " -func validWireHeaderFieldName(v string) bool { - if len(v) == 0 { - return false - } - for _, r := range v { - if !httpguts.IsTokenRune(r) { - return false - } - if 'A' <= r && r <= 'Z' { - return false - } - } - return true -} - -var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n) - -func init() { - for i := 100; i <= 999; i++ { - if v := http.StatusText(i); v != "" { - httpCodeStringCommon[i] = strconv.Itoa(i) - } - } -} - -func httpCodeString(code int) string { - if s, ok := httpCodeStringCommon[code]; ok { - return s - } - return strconv.Itoa(code) -} - -// from pkg io -type stringWriter interface { - WriteString(s string) (n int, err error) -} - -// A gate lets two goroutines coordinate their activities. -type gate chan struct{} - -func (g gate) Done() { g <- struct{}{} } -func (g gate) Wait() { <-g } - -// A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed). -type closeWaiter chan struct{} - -// Init makes a closeWaiter usable. -// It exists because so a closeWaiter value can be placed inside a -// larger struct and have the Mutex and Cond's memory in the same -// allocation. -func (cw *closeWaiter) Init() { - *cw = make(chan struct{}) -} - -// Close marks the closeWaiter as closed and unblocks any waiters. -func (cw closeWaiter) Close() { - close(cw) -} - -// Wait waits for the closeWaiter to become closed. -func (cw closeWaiter) Wait() { - <-cw -} - -// bufferedWriter is a buffered writer that writes to w. -// Its buffered writer is lazily allocated as needed, to minimize -// idle memory usage with many connections. -type bufferedWriter struct { - w io.Writer // immutable - bw *bufio.Writer // non-nil when data is buffered -} - -func newBufferedWriter(w io.Writer) *bufferedWriter { - return &bufferedWriter{w: w} -} - -// bufWriterPoolBufferSize is the size of bufio.Writer's -// buffers created using bufWriterPool. -// -// TODO: pick a less arbitrary value? this is a bit under -// (3 x typical 1500 byte MTU) at least. Other than that, -// not much thought went into it. -const bufWriterPoolBufferSize = 4 << 10 - -var bufWriterPool = sync.Pool{ - New: func() interface{} { - return bufio.NewWriterSize(nil, bufWriterPoolBufferSize) - }, -} - -func (w *bufferedWriter) Available() int { - if w.bw == nil { - return bufWriterPoolBufferSize - } - return w.bw.Available() -} - -func (w *bufferedWriter) Write(p []byte) (n int, err error) { - if w.bw == nil { - bw := bufWriterPool.Get().(*bufio.Writer) - bw.Reset(w.w) - w.bw = bw - } - return w.bw.Write(p) -} - -func (w *bufferedWriter) Flush() error { - bw := w.bw - if bw == nil { - return nil - } - err := bw.Flush() - bw.Reset(nil) - bufWriterPool.Put(bw) - w.bw = nil - return err -} - -func mustUint31(v int32) uint32 { - if v < 0 || v > 2147483647 { - panic("out of range") - } - return uint32(v) -} - -// bodyAllowedForStatus reports whether a given response status code -// permits a body. See RFC 7230, section 3.3. -func bodyAllowedForStatus(status int) bool { - switch { - case status >= 100 && status <= 199: - return false - case status == 204: - return false - case status == 304: - return false - } - return true -} - -type httpError struct { - msg string - timeout bool -} - -func (e *httpError) Error() string { return e.msg } -func (e *httpError) Timeout() bool { return e.timeout } -func (e *httpError) Temporary() bool { return true } - -var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true} - -type connectionStater interface { - ConnectionState() tls.ConnectionState -} - -var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }} - -type sorter struct { - v []string // owned by sorter -} - -func (s *sorter) Len() int { return len(s.v) } -func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] } -func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] } - -// Keys returns the sorted keys of h. -// -// The returned slice is only valid until s used again or returned to -// its pool. -func (s *sorter) Keys(h http.Header) []string { - keys := s.v[:0] - for k := range h { - keys = append(keys, k) - } - s.v = keys - sort.Sort(s) - return keys -} - -func (s *sorter) SortStrings(ss []string) { - // Our sorter works on s.v, which sorter owns, so - // stash it away while we sort the user's buffer. - save := s.v - s.v = ss - sort.Sort(s) - s.v = save -} - -// validPseudoPath reports whether v is a valid :path pseudo-header -// value. It must be either: -// -// *) a non-empty string starting with '/' -// *) the string '*', for OPTIONS requests. -// -// For now this is only used a quick check for deciding when to clean -// up Opaque URLs before sending requests from the Transport. -// See golang.org/issue/16847 -// -// We used to enforce that the path also didn't start with "//", but -// Google's GFE accepts such paths and Chrome sends them, so ignore -// that part of the spec. See golang.org/issue/19103. -func validPseudoPath(v string) bool { - return (len(v) > 0 && v[0] == '/') || v == "*" -} diff --git a/examples/golang.org/x/net/http2/http2_test.go b/examples/golang.org/x/net/http2/http2_test.go deleted file mode 100644 index 667db48..0000000 --- a/examples/golang.org/x/net/http2/http2_test.go +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "errors" - "flag" - "fmt" - "net/http" - "os/exec" - "strconv" - "strings" - "testing" - "time" - - "golang.org/x/net/http2/hpack" -) - -var knownFailing = flag.Bool("known_failing", false, "Run known-failing tests.") - -func condSkipFailingTest(t *testing.T) { - if !*knownFailing { - t.Skip("Skipping known-failing test without --known_failing") - } -} - -func init() { - inTests = true - DebugGoroutines = true - flag.BoolVar(&VerboseLogs, "verboseh2", VerboseLogs, "Verbose HTTP/2 debug logging") -} - -func TestSettingString(t *testing.T) { - tests := []struct { - s Setting - want string - }{ - {Setting{SettingMaxFrameSize, 123}, "[MAX_FRAME_SIZE = 123]"}, - {Setting{1<<16 - 1, 123}, "[UNKNOWN_SETTING_65535 = 123]"}, - } - for i, tt := range tests { - got := fmt.Sprint(tt.s) - if got != tt.want { - t.Errorf("%d. for %#v, string = %q; want %q", i, tt.s, got, tt.want) - } - } -} - -type twriter struct { - t testing.TB - st *serverTester // optional -} - -func (w twriter) Write(p []byte) (n int, err error) { - if w.st != nil { - ps := string(p) - for _, phrase := range w.st.logFilter { - if strings.Contains(ps, phrase) { - return len(p), nil // no logging - } - } - } - w.t.Logf("%s", p) - return len(p), nil -} - -// like encodeHeader, but don't add implicit pseudo headers. -func encodeHeaderNoImplicit(t *testing.T, headers ...string) []byte { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if err := enc.WriteField(hpack.HeaderField{Name: k, Value: v}); err != nil { - t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } - } - return buf.Bytes() -} - -// Verify that curl has http2. -func requireCurl(t *testing.T) { - out, err := dockerLogs(curl(t, "--version")) - if err != nil { - t.Skipf("failed to determine curl features; skipping test") - } - if !strings.Contains(string(out), "HTTP2") { - t.Skip("curl doesn't support HTTP2; skipping test") - } -} - -func curl(t *testing.T, args ...string) (container string) { - out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "gohttp2/curl"}, args...)...).Output() - if err != nil { - t.Skipf("Failed to run curl in docker: %v, %s", err, out) - } - return strings.TrimSpace(string(out)) -} - -// Verify that h2load exists. -func requireH2load(t *testing.T) { - out, err := dockerLogs(h2load(t, "--version")) - if err != nil { - t.Skipf("failed to probe h2load; skipping test: %s", out) - } - if !strings.Contains(string(out), "h2load nghttp2/") { - t.Skipf("h2load not present; skipping test. (Output=%q)", out) - } -} - -func h2load(t *testing.T, args ...string) (container string) { - out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl"}, args...)...).Output() - if err != nil { - t.Skipf("Failed to run h2load in docker: %v, %s", err, out) - } - return strings.TrimSpace(string(out)) -} - -type puppetCommand struct { - fn func(w http.ResponseWriter, r *http.Request) - done chan<- bool -} - -type handlerPuppet struct { - ch chan puppetCommand -} - -func newHandlerPuppet() *handlerPuppet { - return &handlerPuppet{ - ch: make(chan puppetCommand), - } -} - -func (p *handlerPuppet) act(w http.ResponseWriter, r *http.Request) { - for cmd := range p.ch { - cmd.fn(w, r) - cmd.done <- true - } -} - -func (p *handlerPuppet) done() { close(p.ch) } -func (p *handlerPuppet) do(fn func(http.ResponseWriter, *http.Request)) { - done := make(chan bool) - p.ch <- puppetCommand{fn, done} - <-done -} -func dockerLogs(container string) ([]byte, error) { - out, err := exec.Command("docker", "wait", container).CombinedOutput() - if err != nil { - return out, err - } - exitStatus, err := strconv.Atoi(strings.TrimSpace(string(out))) - if err != nil { - return out, errors.New("unexpected exit status from docker wait") - } - out, err = exec.Command("docker", "logs", container).CombinedOutput() - exec.Command("docker", "rm", container).Run() - if err == nil && exitStatus != 0 { - err = fmt.Errorf("exit status %d: %s", exitStatus, out) - } - return out, err -} - -func kill(container string) { - exec.Command("docker", "kill", container).Run() - exec.Command("docker", "rm", container).Run() -} - -func cleanDate(res *http.Response) { - if d := res.Header["Date"]; len(d) == 1 { - d[0] = "XXX" - } -} - -func TestSorterPoolAllocs(t *testing.T) { - ss := []string{"a", "b", "c"} - h := http.Header{ - "a": nil, - "b": nil, - "c": nil, - } - sorter := new(sorter) - - if allocs := testing.AllocsPerRun(100, func() { - sorter.SortStrings(ss) - }); allocs >= 1 { - t.Logf("SortStrings allocs = %v; want <1", allocs) - } - - if allocs := testing.AllocsPerRun(5, func() { - if len(sorter.Keys(h)) != 3 { - t.Fatal("wrong result") - } - }); allocs > 0 { - t.Logf("Keys allocs = %v; want <1", allocs) - } -} - -// waitCondition reports whether fn eventually returned true, -// checking immediately and then every checkEvery amount, -// until waitFor has elapsed, at which point it returns false. -func waitCondition(waitFor, checkEvery time.Duration, fn func() bool) bool { - deadline := time.Now().Add(waitFor) - for time.Now().Before(deadline) { - if fn() { - return true - } - time.Sleep(checkEvery) - } - return false -} - -// waitErrCondition is like waitCondition but with errors instead of bools. -func waitErrCondition(waitFor, checkEvery time.Duration, fn func() error) error { - deadline := time.Now().Add(waitFor) - var err error - for time.Now().Before(deadline) { - if err = fn(); err == nil { - return nil - } - time.Sleep(checkEvery) - } - return err -} diff --git a/examples/golang.org/x/net/http2/not_go111.go b/examples/golang.org/x/net/http2/not_go111.go deleted file mode 100644 index 0df34e6..0000000 --- a/examples/golang.org/x/net/http2/not_go111.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.11 - -package http2 - -import "net/textproto" - -func traceHasWroteHeaderField(trace *clientTrace) bool { return false } - -func traceWroteHeaderField(trace *clientTrace, k, v string) {} - -func traceGot1xxResponseFunc(trace *clientTrace) func(int, textproto.MIMEHeader) error { - return nil -} diff --git a/examples/golang.org/x/net/http2/not_go16.go b/examples/golang.org/x/net/http2/not_go16.go deleted file mode 100644 index 508cebc..0000000 --- a/examples/golang.org/x/net/http2/not_go16.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.6 - -package http2 - -import ( - "net/http" - "time" -) - -func configureTransport(t1 *http.Transport) (*Transport, error) { - return nil, errTransportVersion -} - -func transportExpectContinueTimeout(t1 *http.Transport) time.Duration { - return 0 - -} diff --git a/examples/golang.org/x/net/http2/not_go17.go b/examples/golang.org/x/net/http2/not_go17.go deleted file mode 100644 index 7ffb250..0000000 --- a/examples/golang.org/x/net/http2/not_go17.go +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package http2 - -import ( - "crypto/tls" - "errors" - "net" - "net/http" - "time" -) - -type contextContext interface { - Done() <-chan struct{} - Err() error -} - -var errCanceled = errors.New("canceled") - -type fakeContext struct{} - -func (fakeContext) Done() <-chan struct{} { return nil } -func (fakeContext) Err() error { panic("should not be called") } - -func reqContext(r *http.Request) fakeContext { - return fakeContext{} -} - -func setResponseUncompressed(res *http.Response) { - // Nothing. -} - -type clientTrace struct{} - -func requestTrace(*http.Request) *clientTrace { return nil } -func traceGetConn(*http.Request, string) {} -func traceGotConn(*http.Request, *ClientConn) {} -func traceFirstResponseByte(*clientTrace) {} -func traceWroteHeaders(*clientTrace) {} -func traceWroteRequest(*clientTrace, error) {} -func traceGot100Continue(trace *clientTrace) {} -func traceWait100Continue(trace *clientTrace) {} - -func nop() {} - -func serverConnBaseContext(c net.Conn, opts *ServeConnOpts) (ctx contextContext, cancel func()) { - return nil, nop -} - -func contextWithCancel(ctx contextContext) (_ contextContext, cancel func()) { - return ctx, nop -} - -func requestWithContext(req *http.Request, ctx contextContext) *http.Request { - return req -} - -// temporary copy of Go 1.6's private tls.Config.clone: -func cloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - } -} - -func (cc *ClientConn) Ping(ctx contextContext) error { - return cc.ping(ctx) -} - -func (cc *ClientConn) Shutdown(ctx contextContext) error { - return cc.shutdown(ctx) -} - -func (t *Transport) idleConnTimeout() time.Duration { return 0 } diff --git a/examples/golang.org/x/net/http2/not_go18.go b/examples/golang.org/x/net/http2/not_go18.go deleted file mode 100644 index 6f8d3f8..0000000 --- a/examples/golang.org/x/net/http2/not_go18.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8 - -package http2 - -import ( - "io" - "net/http" -) - -func configureServer18(h1 *http.Server, h2 *Server) error { - // No IdleTimeout to sync prior to Go 1.8. - return nil -} - -func shouldLogPanic(panicValue interface{}) bool { - return panicValue != nil -} - -func reqGetBody(req *http.Request) func() (io.ReadCloser, error) { - return nil -} - -func reqBodyIsNoBody(io.ReadCloser) bool { return false } - -func go18httpNoBody() io.ReadCloser { return nil } // for tests only diff --git a/examples/golang.org/x/net/http2/not_go19.go b/examples/golang.org/x/net/http2/not_go19.go deleted file mode 100644 index 5ae0772..0000000 --- a/examples/golang.org/x/net/http2/not_go19.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.9 - -package http2 - -import ( - "net/http" -) - -func configureServer19(s *http.Server, conf *Server) error { - // not supported prior to go1.9 - return nil -} diff --git a/examples/golang.org/x/net/http2/pipe.go b/examples/golang.org/x/net/http2/pipe.go deleted file mode 100644 index a614009..0000000 --- a/examples/golang.org/x/net/http2/pipe.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "errors" - "io" - "sync" -) - -// pipe is a goroutine-safe io.Reader/io.Writer pair. It's like -// io.Pipe except there are no PipeReader/PipeWriter halves, and the -// underlying buffer is an interface. (io.Pipe is always unbuffered) -type pipe struct { - mu sync.Mutex - c sync.Cond // c.L lazily initialized to &p.mu - b pipeBuffer // nil when done reading - err error // read error once empty. non-nil means closed. - breakErr error // immediate read error (caller doesn't see rest of b) - donec chan struct{} // closed on error - readFn func() // optional code to run in Read before error -} - -type pipeBuffer interface { - Len() int - io.Writer - io.Reader -} - -func (p *pipe) Len() int { - p.mu.Lock() - defer p.mu.Unlock() - if p.b == nil { - return 0 - } - return p.b.Len() -} - -// Read waits until data is available and copies bytes -// from the buffer into p. -func (p *pipe) Read(d []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - if p.c.L == nil { - p.c.L = &p.mu - } - for { - if p.breakErr != nil { - return 0, p.breakErr - } - if p.b != nil && p.b.Len() > 0 { - return p.b.Read(d) - } - if p.err != nil { - if p.readFn != nil { - p.readFn() // e.g. copy trailers - p.readFn = nil // not sticky like p.err - } - p.b = nil - return 0, p.err - } - p.c.Wait() - } -} - -var errClosedPipeWrite = errors.New("write on closed buffer") - -// Write copies bytes from p into the buffer and wakes a reader. -// It is an error to write more data than the buffer can hold. -func (p *pipe) Write(d []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - if p.c.L == nil { - p.c.L = &p.mu - } - defer p.c.Signal() - if p.err != nil { - return 0, errClosedPipeWrite - } - if p.breakErr != nil { - return len(d), nil // discard when there is no reader - } - return p.b.Write(d) -} - -// CloseWithError causes the next Read (waking up a current blocked -// Read if needed) to return the provided err after all data has been -// read. -// -// The error must be non-nil. -func (p *pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) } - -// BreakWithError causes the next Read (waking up a current blocked -// Read if needed) to return the provided err immediately, without -// waiting for unread data. -func (p *pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) } - -// closeWithErrorAndCode is like CloseWithError but also sets some code to run -// in the caller's goroutine before returning the error. -func (p *pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) } - -func (p *pipe) closeWithError(dst *error, err error, fn func()) { - if err == nil { - panic("err must be non-nil") - } - p.mu.Lock() - defer p.mu.Unlock() - if p.c.L == nil { - p.c.L = &p.mu - } - defer p.c.Signal() - if *dst != nil { - // Already been done. - return - } - p.readFn = fn - if dst == &p.breakErr { - p.b = nil - } - *dst = err - p.closeDoneLocked() -} - -// requires p.mu be held. -func (p *pipe) closeDoneLocked() { - if p.donec == nil { - return - } - // Close if unclosed. This isn't racy since we always - // hold p.mu while closing. - select { - case <-p.donec: - default: - close(p.donec) - } -} - -// Err returns the error (if any) first set by BreakWithError or CloseWithError. -func (p *pipe) Err() error { - p.mu.Lock() - defer p.mu.Unlock() - if p.breakErr != nil { - return p.breakErr - } - return p.err -} - -// Done returns a channel which is closed if and when this pipe is closed -// with CloseWithError. -func (p *pipe) Done() <-chan struct{} { - p.mu.Lock() - defer p.mu.Unlock() - if p.donec == nil { - p.donec = make(chan struct{}) - if p.err != nil || p.breakErr != nil { - // Already hit an error. - p.closeDoneLocked() - } - } - return p.donec -} diff --git a/examples/golang.org/x/net/http2/pipe_test.go b/examples/golang.org/x/net/http2/pipe_test.go deleted file mode 100644 index 1bf351f..0000000 --- a/examples/golang.org/x/net/http2/pipe_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "testing" -) - -func TestPipeClose(t *testing.T) { - var p pipe - p.b = new(bytes.Buffer) - a := errors.New("a") - b := errors.New("b") - p.CloseWithError(a) - p.CloseWithError(b) - _, err := p.Read(make([]byte, 1)) - if err != a { - t.Errorf("err = %v want %v", err, a) - } -} - -func TestPipeDoneChan(t *testing.T) { - var p pipe - done := p.Done() - select { - case <-done: - t.Fatal("done too soon") - default: - } - p.CloseWithError(io.EOF) - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_ErrFirst(t *testing.T) { - var p pipe - p.CloseWithError(io.EOF) - done := p.Done() - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_Break(t *testing.T) { - var p pipe - done := p.Done() - select { - case <-done: - t.Fatal("done too soon") - default: - } - p.BreakWithError(io.EOF) - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_Break_ErrFirst(t *testing.T) { - var p pipe - p.BreakWithError(io.EOF) - done := p.Done() - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeCloseWithError(t *testing.T) { - p := &pipe{b: new(bytes.Buffer)} - const body = "foo" - io.WriteString(p, body) - a := errors.New("test error") - p.CloseWithError(a) - all, err := ioutil.ReadAll(p) - if string(all) != body { - t.Errorf("read bytes = %q; want %q", all, body) - } - if err != a { - t.Logf("read error = %v, %v", err, a) - } - // Read and Write should fail. - if n, err := p.Write([]byte("abc")); err != errClosedPipeWrite || n != 0 { - t.Errorf("Write(abc) after close\ngot %v, %v\nwant 0, %v", n, err, errClosedPipeWrite) - } - if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { - t.Errorf("Read() after close\ngot %v, nil\nwant 0, %v", n, errClosedPipeWrite) - } -} - -func TestPipeBreakWithError(t *testing.T) { - p := &pipe{b: new(bytes.Buffer)} - io.WriteString(p, "foo") - a := errors.New("test err") - p.BreakWithError(a) - all, err := ioutil.ReadAll(p) - if string(all) != "" { - t.Errorf("read bytes = %q; want empty string", all) - } - if err != a { - t.Logf("read error = %v, %v", err, a) - } - if p.b != nil { - t.Errorf("buffer should be nil after BreakWithError") - } - // Write should succeed silently. - if n, err := p.Write([]byte("abc")); err != nil || n != 3 { - t.Errorf("Write(abc) after break\ngot %v, %v\nwant 0, nil", n, err) - } - if p.b != nil { - t.Errorf("buffer should be nil after Write") - } - // Read should fail. - if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { - t.Errorf("Read() after close\ngot %v, nil\nwant 0, not nil", n) - } -} diff --git a/examples/golang.org/x/net/http2/server.go b/examples/golang.org/x/net/http2/server.go deleted file mode 100644 index 6e2c5b9..0000000 --- a/examples/golang.org/x/net/http2/server.go +++ /dev/null @@ -1,2891 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TODO: turn off the serve goroutine when idle, so -// an idle conn only has the readFrames goroutine active. (which could -// also be optimized probably to pin less memory in crypto/tls). This -// would involve tracking when the serve goroutine is active (atomic -// int32 read/CAS probably?) and starting it up when frames arrive, -// and shutting it down when all handlers exit. the occasional PING -// packets could use time.AfterFunc to call sc.wakeStartServeLoop() -// (which is a no-op if already running) and then queue the PING write -// as normal. The serve loop would then exit in most cases (if no -// Handlers running) and not be woken up again until the PING packet -// returns. - -// TODO (maybe): add a mechanism for Handlers to going into -// half-closed-local mode (rw.(io.Closer) test?) but not exit their -// handler, and continue to be able to read from the -// Request.Body. This would be a somewhat semantic change from HTTP/1 -// (or at least what we expose in net/http), so I'd probably want to -// add it there too. For now, this package says that returning from -// the Handler ServeHTTP function means you're both done reading and -// done writing, without a way to stop just one or the other. - -package http2 - -import ( - "bufio" - "bytes" - "crypto/tls" - "errors" - "fmt" - "io" - "log" - "math" - "net" - "net/http" - "net/textproto" - "net/url" - "os" - "reflect" - "runtime" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/http/httpguts" - "golang.org/x/net/http2/hpack" -) - -const ( - prefaceTimeout = 10 * time.Second - firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway - handlerChunkWriteSize = 4 << 10 - defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to? -) - -var ( - errClientDisconnected = errors.New("client disconnected") - errClosedBody = errors.New("body closed by handler") - errHandlerComplete = errors.New("http2: request body closed due to handler exiting") - errStreamClosed = errors.New("http2: stream closed") -) - -var responseWriterStatePool = sync.Pool{ - New: func() interface{} { - rws := &responseWriterState{} - rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize) - return rws - }, -} - -// Test hooks. -var ( - testHookOnConn func() - testHookGetServerConn func(*serverConn) - testHookOnPanicMu *sync.Mutex // nil except in tests - testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool) -) - -// Server is an HTTP/2 server. -type Server struct { - // MaxHandlers limits the number of http.Handler ServeHTTP goroutines - // which may run at a time over all connections. - // Negative or zero no limit. - // TODO: implement - MaxHandlers int - - // MaxConcurrentStreams optionally specifies the number of - // concurrent streams that each client may have open at a - // time. This is unrelated to the number of http.Handler goroutines - // which may be active globally, which is MaxHandlers. - // If zero, MaxConcurrentStreams defaults to at least 100, per - // the HTTP/2 spec's recommendations. - MaxConcurrentStreams uint32 - - // MaxReadFrameSize optionally specifies the largest frame - // this server is willing to read. A valid value is between - // 16k and 16M, inclusive. If zero or otherwise invalid, a - // default value is used. - MaxReadFrameSize uint32 - - // PermitProhibitedCipherSuites, if true, permits the use of - // cipher suites prohibited by the HTTP/2 spec. - PermitProhibitedCipherSuites bool - - // IdleTimeout specifies how long until idle clients should be - // closed with a GOAWAY frame. PING frames are not considered - // activity for the purposes of IdleTimeout. - IdleTimeout time.Duration - - // MaxUploadBufferPerConnection is the size of the initial flow - // control window for each connections. The HTTP/2 spec does not - // allow this to be smaller than 65535 or larger than 2^32-1. - // If the value is outside this range, a default value will be - // used instead. - MaxUploadBufferPerConnection int32 - - // MaxUploadBufferPerStream is the size of the initial flow control - // window for each stream. The HTTP/2 spec does not allow this to - // be larger than 2^32-1. If the value is zero or larger than the - // maximum, a default value will be used instead. - MaxUploadBufferPerStream int32 - - // NewWriteScheduler constructs a write scheduler for a connection. - // If nil, a default scheduler is chosen. - NewWriteScheduler func() WriteScheduler - - // Internal state. This is a pointer (rather than embedded directly) - // so that we don't embed a Mutex in this struct, which will make the - // struct non-copyable, which might break some callers. - state *serverInternalState -} - -func (s *Server) initialConnRecvWindowSize() int32 { - if s.MaxUploadBufferPerConnection > initialWindowSize { - return s.MaxUploadBufferPerConnection - } - return 1 << 20 -} - -func (s *Server) initialStreamRecvWindowSize() int32 { - if s.MaxUploadBufferPerStream > 0 { - return s.MaxUploadBufferPerStream - } - return 1 << 20 -} - -func (s *Server) maxReadFrameSize() uint32 { - if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize { - return v - } - return defaultMaxReadFrameSize -} - -func (s *Server) maxConcurrentStreams() uint32 { - if v := s.MaxConcurrentStreams; v > 0 { - return v - } - return defaultMaxStreams -} - -type serverInternalState struct { - mu sync.Mutex - activeConns map[*serverConn]struct{} -} - -func (s *serverInternalState) registerConn(sc *serverConn) { - if s == nil { - return // if the Server was used without calling ConfigureServer - } - s.mu.Lock() - s.activeConns[sc] = struct{}{} - s.mu.Unlock() -} - -func (s *serverInternalState) unregisterConn(sc *serverConn) { - if s == nil { - return // if the Server was used without calling ConfigureServer - } - s.mu.Lock() - delete(s.activeConns, sc) - s.mu.Unlock() -} - -func (s *serverInternalState) startGracefulShutdown() { - if s == nil { - return // if the Server was used without calling ConfigureServer - } - s.mu.Lock() - for sc := range s.activeConns { - sc.startGracefulShutdown() - } - s.mu.Unlock() -} - -// ConfigureServer adds HTTP/2 support to a net/http Server. -// -// The configuration conf may be nil. -// -// ConfigureServer must be called before s begins serving. -func ConfigureServer(s *http.Server, conf *Server) error { - if s == nil { - panic("nil *http.Server") - } - if conf == nil { - conf = new(Server) - } - conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})} - if err := configureServer18(s, conf); err != nil { - return err - } - if err := configureServer19(s, conf); err != nil { - return err - } - - if s.TLSConfig == nil { - s.TLSConfig = new(tls.Config) - } else if s.TLSConfig.CipherSuites != nil { - // If they already provided a CipherSuite list, return - // an error if it has a bad order or is missing - // ECDHE_RSA_WITH_AES_128_GCM_SHA256 or ECDHE_ECDSA_WITH_AES_128_GCM_SHA256. - haveRequired := false - sawBad := false - for i, cs := range s.TLSConfig.CipherSuites { - switch cs { - case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - // Alternative MTI cipher to not discourage ECDSA-only servers. - // See http://golang.org/cl/30721 for further information. - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: - haveRequired = true - } - if isBadCipher(cs) { - sawBad = true - } else if sawBad { - return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs) - } - } - if !haveRequired { - return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.") - } - } - - // Note: not setting MinVersion to tls.VersionTLS12, - // as we don't want to interfere with HTTP/1.1 traffic - // on the user's server. We enforce TLS 1.2 later once - // we accept a connection. Ideally this should be done - // during next-proto selection, but using TLS <1.2 with - // HTTP/2 is still the client's bug. - - s.TLSConfig.PreferServerCipherSuites = true - - haveNPN := false - for _, p := range s.TLSConfig.NextProtos { - if p == NextProtoTLS { - haveNPN = true - break - } - } - if !haveNPN { - s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS) - } - - if s.TLSNextProto == nil { - s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} - } - protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) { - if testHookOnConn != nil { - testHookOnConn() - } - conf.ServeConn(c, &ServeConnOpts{ - Handler: h, - BaseConfig: hs, - }) - } - s.TLSNextProto[NextProtoTLS] = protoHandler - return nil -} - -// ServeConnOpts are options for the Server.ServeConn method. -type ServeConnOpts struct { - // BaseConfig optionally sets the base configuration - // for values. If nil, defaults are used. - BaseConfig *http.Server - - // Handler specifies which handler to use for processing - // requests. If nil, BaseConfig.Handler is used. If BaseConfig - // or BaseConfig.Handler is nil, http.DefaultServeMux is used. - Handler http.Handler -} - -func (o *ServeConnOpts) baseConfig() *http.Server { - if o != nil && o.BaseConfig != nil { - return o.BaseConfig - } - return new(http.Server) -} - -func (o *ServeConnOpts) handler() http.Handler { - if o != nil { - if o.Handler != nil { - return o.Handler - } - if o.BaseConfig != nil && o.BaseConfig.Handler != nil { - return o.BaseConfig.Handler - } - } - return http.DefaultServeMux -} - -// ServeConn serves HTTP/2 requests on the provided connection and -// blocks until the connection is no longer readable. -// -// ServeConn starts speaking HTTP/2 assuming that c has not had any -// reads or writes. It writes its initial settings frame and expects -// to be able to read the preface and settings frame from the -// client. If c has a ConnectionState method like a *tls.Conn, the -// ConnectionState is used to verify the TLS ciphersuite and to set -// the Request.TLS field in Handlers. -// -// ServeConn does not support h2c by itself. Any h2c support must be -// implemented in terms of providing a suitably-behaving net.Conn. -// -// The opts parameter is optional. If nil, default values are used. -func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { - baseCtx, cancel := serverConnBaseContext(c, opts) - defer cancel() - - sc := &serverConn{ - srv: s, - hs: opts.baseConfig(), - conn: c, - baseCtx: baseCtx, - remoteAddrStr: c.RemoteAddr().String(), - bw: newBufferedWriter(c), - handler: opts.handler(), - streams: make(map[uint32]*stream), - readFrameCh: make(chan readFrameResult), - wantWriteFrameCh: make(chan FrameWriteRequest, 8), - serveMsgCh: make(chan interface{}, 8), - wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync - bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way - doneServing: make(chan struct{}), - clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value" - advMaxStreams: s.maxConcurrentStreams(), - initialStreamSendWindowSize: initialWindowSize, - maxFrameSize: initialMaxFrameSize, - headerTableSize: initialHeaderTableSize, - serveG: newGoroutineLock(), - pushEnabled: true, - } - - s.state.registerConn(sc) - defer s.state.unregisterConn(sc) - - // The net/http package sets the write deadline from the - // http.Server.WriteTimeout during the TLS handshake, but then - // passes the connection off to us with the deadline already set. - // Write deadlines are set per stream in serverConn.newStream. - // Disarm the net.Conn write deadline here. - if sc.hs.WriteTimeout != 0 { - sc.conn.SetWriteDeadline(time.Time{}) - } - - if s.NewWriteScheduler != nil { - sc.writeSched = s.NewWriteScheduler() - } else { - sc.writeSched = NewRandomWriteScheduler() - } - - // These start at the RFC-specified defaults. If there is a higher - // configured value for inflow, that will be updated when we send a - // WINDOW_UPDATE shortly after sending SETTINGS. - sc.flow.add(initialWindowSize) - sc.inflow.add(initialWindowSize) - sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) - - fr := NewFramer(sc.bw, c) - fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) - fr.MaxHeaderListSize = sc.maxHeaderListSize() - fr.SetMaxReadFrameSize(s.maxReadFrameSize()) - sc.framer = fr - - if tc, ok := c.(connectionStater); ok { - sc.tlsState = new(tls.ConnectionState) - *sc.tlsState = tc.ConnectionState() - // 9.2 Use of TLS Features - // An implementation of HTTP/2 over TLS MUST use TLS - // 1.2 or higher with the restrictions on feature set - // and cipher suite described in this section. Due to - // implementation limitations, it might not be - // possible to fail TLS negotiation. An endpoint MUST - // immediately terminate an HTTP/2 connection that - // does not meet the TLS requirements described in - // this section with a connection error (Section - // 5.4.1) of type INADEQUATE_SECURITY. - if sc.tlsState.Version < tls.VersionTLS12 { - sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low") - return - } - - if sc.tlsState.ServerName == "" { - // Client must use SNI, but we don't enforce that anymore, - // since it was causing problems when connecting to bare IP - // addresses during development. - // - // TODO: optionally enforce? Or enforce at the time we receive - // a new request, and verify the ServerName matches the :authority? - // But that precludes proxy situations, perhaps. - // - // So for now, do nothing here again. - } - - if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) { - // "Endpoints MAY choose to generate a connection error - // (Section 5.4.1) of type INADEQUATE_SECURITY if one of - // the prohibited cipher suites are negotiated." - // - // We choose that. In my opinion, the spec is weak - // here. It also says both parties must support at least - // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no - // excuses here. If we really must, we could allow an - // "AllowInsecureWeakCiphers" option on the server later. - // Let's see how it plays out first. - sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite)) - return - } - } - - if hook := testHookGetServerConn; hook != nil { - hook(sc) - } - sc.serve() -} - -func (sc *serverConn) rejectConn(err ErrCode, debug string) { - sc.vlogf("http2: server rejecting conn: %v, %s", err, debug) - // ignoring errors. hanging up anyway. - sc.framer.WriteGoAway(0, err, []byte(debug)) - sc.bw.Flush() - sc.conn.Close() -} - -type serverConn struct { - // Immutable: - srv *Server - hs *http.Server - conn net.Conn - bw *bufferedWriter // writing to conn - handler http.Handler - baseCtx contextContext - framer *Framer - doneServing chan struct{} // closed when serverConn.serve ends - readFrameCh chan readFrameResult // written by serverConn.readFrames - wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve - wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes - bodyReadCh chan bodyReadMsg // from handlers -> serve - serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop - flow flow // conn-wide (not stream-specific) outbound flow control - inflow flow // conn-wide inbound flow control - tlsState *tls.ConnectionState // shared by all handlers, like net/http - remoteAddrStr string - writeSched WriteScheduler - - // Everything following is owned by the serve loop; use serveG.check(): - serveG goroutineLock // used to verify funcs are on serve() - pushEnabled bool - sawFirstSettings bool // got the initial SETTINGS frame after the preface - needToSendSettingsAck bool - unackedSettings int // how many SETTINGS have we sent without ACKs? - clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit) - advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client - curClientStreams uint32 // number of open streams initiated by the client - curPushedStreams uint32 // number of open streams initiated by server push - maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests - maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes - streams map[uint32]*stream - initialStreamSendWindowSize int32 - maxFrameSize int32 - headerTableSize uint32 - peerMaxHeaderListSize uint32 // zero means unknown (default) - canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case - writingFrame bool // started writing a frame (on serve goroutine or separate) - writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh - needsFrameFlush bool // last frame write wasn't a flush - inGoAway bool // we've started to or sent GOAWAY - inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop - needToSendGoAway bool // we need to schedule a GOAWAY frame write - goAwayCode ErrCode - shutdownTimer *time.Timer // nil until used - idleTimer *time.Timer // nil if unused - - // Owned by the writeFrameAsync goroutine: - headerWriteBuf bytes.Buffer - hpackEncoder *hpack.Encoder - - // Used by startGracefulShutdown. - shutdownOnce sync.Once -} - -func (sc *serverConn) maxHeaderListSize() uint32 { - n := sc.hs.MaxHeaderBytes - if n <= 0 { - n = http.DefaultMaxHeaderBytes - } - // http2's count is in a slightly different unit and includes 32 bytes per pair. - // So, take the net/http.Server value and pad it up a bit, assuming 10 headers. - const perFieldOverhead = 32 // per http2 spec - const typicalHeaders = 10 // conservative - return uint32(n + typicalHeaders*perFieldOverhead) -} - -func (sc *serverConn) curOpenStreams() uint32 { - sc.serveG.check() - return sc.curClientStreams + sc.curPushedStreams -} - -// stream represents a stream. This is the minimal metadata needed by -// the serve goroutine. Most of the actual stream state is owned by -// the http.Handler's goroutine in the responseWriter. Because the -// responseWriter's responseWriterState is recycled at the end of a -// handler, this struct intentionally has no pointer to the -// *responseWriter{,State} itself, as the Handler ending nils out the -// responseWriter's state field. -type stream struct { - // immutable: - sc *serverConn - id uint32 - body *pipe // non-nil if expecting DATA frames - cw closeWaiter // closed wait stream transitions to closed state - ctx contextContext - cancelCtx func() - - // owned by serverConn's serve loop: - bodyBytes int64 // body bytes seen so far - declBodyBytes int64 // or -1 if undeclared - flow flow // limits writing from Handler to client - inflow flow // what the client is allowed to POST/etc to us - parent *stream // or nil - numTrailerValues int64 - weight uint8 - state streamState - resetQueued bool // RST_STREAM queued for write; set by sc.resetStream - gotTrailerHeader bool // HEADER frame for trailers was seen - wroteHeaders bool // whether we wrote headers (not status 100) - writeDeadline *time.Timer // nil if unused - - trailer http.Header // accumulated trailers - reqTrailer http.Header // handler's Request.Trailer -} - -func (sc *serverConn) Framer() *Framer { return sc.framer } -func (sc *serverConn) CloseConn() error { return sc.conn.Close() } -func (sc *serverConn) Flush() error { return sc.bw.Flush() } -func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) { - return sc.hpackEncoder, &sc.headerWriteBuf -} - -func (sc *serverConn) state(streamID uint32) (streamState, *stream) { - sc.serveG.check() - // http://tools.ietf.org/html/rfc7540#section-5.1 - if st, ok := sc.streams[streamID]; ok { - return st.state, st - } - // "The first use of a new stream identifier implicitly closes all - // streams in the "idle" state that might have been initiated by - // that peer with a lower-valued stream identifier. For example, if - // a client sends a HEADERS frame on stream 7 without ever sending a - // frame on stream 5, then stream 5 transitions to the "closed" - // state when the first frame for stream 7 is sent or received." - if streamID%2 == 1 { - if streamID <= sc.maxClientStreamID { - return stateClosed, nil - } - } else { - if streamID <= sc.maxPushPromiseID { - return stateClosed, nil - } - } - return stateIdle, nil -} - -// setConnState calls the net/http ConnState hook for this connection, if configured. -// Note that the net/http package does StateNew and StateClosed for us. -// There is currently no plan for StateHijacked or hijacking HTTP/2 connections. -func (sc *serverConn) setConnState(state http.ConnState) { - if sc.hs.ConnState != nil { - sc.hs.ConnState(sc.conn, state) - } -} - -func (sc *serverConn) vlogf(format string, args ...interface{}) { - if VerboseLogs { - sc.logf(format, args...) - } -} - -func (sc *serverConn) logf(format string, args ...interface{}) { - if lg := sc.hs.ErrorLog; lg != nil { - lg.Printf(format, args...) - } else { - log.Printf(format, args...) - } -} - -// errno returns v's underlying uintptr, else 0. -// -// TODO: remove this helper function once http2 can use build -// tags. See comment in isClosedConnError. -func errno(v error) uintptr { - if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr { - return uintptr(rv.Uint()) - } - return 0 -} - -// isClosedConnError reports whether err is an error from use of a closed -// network connection. -func isClosedConnError(err error) bool { - if err == nil { - return false - } - - // TODO: remove this string search and be more like the Windows - // case below. That might involve modifying the standard library - // to return better error types. - str := err.Error() - if strings.Contains(str, "use of closed network connection") { - return true - } - - // TODO(bradfitz): x/tools/cmd/bundle doesn't really support - // build tags, so I can't make an http2_windows.go file with - // Windows-specific stuff. Fix that and move this, once we - // have a way to bundle this into std's net/http somehow. - if runtime.GOOS == "windows" { - if oe, ok := err.(*net.OpError); ok && oe.Op == "read" { - if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" { - const WSAECONNABORTED = 10053 - const WSAECONNRESET = 10054 - if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED { - return true - } - } - } - } - return false -} - -func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { - if err == nil { - return - } - if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout { - // Boring, expected errors. - sc.vlogf(format, args...) - } else { - sc.logf(format, args...) - } -} - -func (sc *serverConn) canonicalHeader(v string) string { - sc.serveG.check() - cv, ok := commonCanonHeader[v] - if ok { - return cv - } - cv, ok = sc.canonHeader[v] - if ok { - return cv - } - if sc.canonHeader == nil { - sc.canonHeader = make(map[string]string) - } - cv = http.CanonicalHeaderKey(v) - sc.canonHeader[v] = cv - return cv -} - -type readFrameResult struct { - f Frame // valid until readMore is called - err error - - // readMore should be called once the consumer no longer needs or - // retains f. After readMore, f is invalid and more frames can be - // read. - readMore func() -} - -// readFrames is the loop that reads incoming frames. -// It takes care to only read one frame at a time, blocking until the -// consumer is done with the frame. -// It's run on its own goroutine. -func (sc *serverConn) readFrames() { - gate := make(gate) - gateDone := gate.Done - for { - f, err := sc.framer.ReadFrame() - select { - case sc.readFrameCh <- readFrameResult{f, err, gateDone}: - case <-sc.doneServing: - return - } - select { - case <-gate: - case <-sc.doneServing: - return - } - if terminalReadFrameError(err) { - return - } - } -} - -// frameWriteResult is the message passed from writeFrameAsync to the serve goroutine. -type frameWriteResult struct { - wr FrameWriteRequest // what was written (or attempted) - err error // result of the writeFrame call -} - -// writeFrameAsync runs in its own goroutine and writes a single frame -// and then reports when it's done. -// At most one goroutine can be running writeFrameAsync at a time per -// serverConn. -func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) { - err := wr.write.writeFrame(sc) - sc.wroteFrameCh <- frameWriteResult{wr, err} -} - -func (sc *serverConn) closeAllStreamsOnConnClose() { - sc.serveG.check() - for _, st := range sc.streams { - sc.closeStream(st, errClientDisconnected) - } -} - -func (sc *serverConn) stopShutdownTimer() { - sc.serveG.check() - if t := sc.shutdownTimer; t != nil { - t.Stop() - } -} - -func (sc *serverConn) notePanic() { - // Note: this is for serverConn.serve panicking, not http.Handler code. - if testHookOnPanicMu != nil { - testHookOnPanicMu.Lock() - defer testHookOnPanicMu.Unlock() - } - if testHookOnPanic != nil { - if e := recover(); e != nil { - if testHookOnPanic(sc, e) { - panic(e) - } - } - } -} - -func (sc *serverConn) serve() { - sc.serveG.check() - defer sc.notePanic() - defer sc.conn.Close() - defer sc.closeAllStreamsOnConnClose() - defer sc.stopShutdownTimer() - defer close(sc.doneServing) // unblocks handlers trying to send - - if VerboseLogs { - sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs) - } - - sc.writeFrame(FrameWriteRequest{ - write: writeSettings{ - {SettingMaxFrameSize, sc.srv.maxReadFrameSize()}, - {SettingMaxConcurrentStreams, sc.advMaxStreams}, - {SettingMaxHeaderListSize, sc.maxHeaderListSize()}, - {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())}, - }, - }) - sc.unackedSettings++ - - // Each connection starts with intialWindowSize inflow tokens. - // If a higher value is configured, we add more tokens. - if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 { - sc.sendWindowUpdate(nil, int(diff)) - } - - if err := sc.readPreface(); err != nil { - sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err) - return - } - // Now that we've got the preface, get us out of the - // "StateNew" state. We can't go directly to idle, though. - // Active means we read some data and anticipate a request. We'll - // do another Active when we get a HEADERS frame. - sc.setConnState(http.StateActive) - sc.setConnState(http.StateIdle) - - if sc.srv.IdleTimeout != 0 { - sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer) - defer sc.idleTimer.Stop() - } - - go sc.readFrames() // closed by defer sc.conn.Close above - - settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer) - defer settingsTimer.Stop() - - loopNum := 0 - for { - loopNum++ - select { - case wr := <-sc.wantWriteFrameCh: - if se, ok := wr.write.(StreamError); ok { - sc.resetStream(se) - break - } - sc.writeFrame(wr) - case res := <-sc.wroteFrameCh: - sc.wroteFrame(res) - case res := <-sc.readFrameCh: - if !sc.processFrameFromReader(res) { - return - } - res.readMore() - if settingsTimer != nil { - settingsTimer.Stop() - settingsTimer = nil - } - case m := <-sc.bodyReadCh: - sc.noteBodyRead(m.st, m.n) - case msg := <-sc.serveMsgCh: - switch v := msg.(type) { - case func(int): - v(loopNum) // for testing - case *serverMessage: - switch v { - case settingsTimerMsg: - sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr()) - return - case idleTimerMsg: - sc.vlogf("connection is idle") - sc.goAway(ErrCodeNo) - case shutdownTimerMsg: - sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr()) - return - case gracefulShutdownMsg: - sc.startGracefulShutdownInternal() - default: - panic("unknown timer") - } - case *startPushRequest: - sc.startPush(v) - default: - panic(fmt.Sprintf("unexpected type %T", v)) - } - } - - // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY - // with no error code (graceful shutdown), don't start the timer until - // all open streams have been completed. - sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame - gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0 - if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) { - sc.shutDownIn(goAwayTimeout) - } - } -} - -func (sc *serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{}) { - select { - case <-sc.doneServing: - case <-sharedCh: - close(privateCh) - } -} - -type serverMessage int - -// Message values sent to serveMsgCh. -var ( - settingsTimerMsg = new(serverMessage) - idleTimerMsg = new(serverMessage) - shutdownTimerMsg = new(serverMessage) - gracefulShutdownMsg = new(serverMessage) -) - -func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) } -func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) } -func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) } - -func (sc *serverConn) sendServeMsg(msg interface{}) { - sc.serveG.checkNotOn() // NOT - select { - case sc.serveMsgCh <- msg: - case <-sc.doneServing: - } -} - -var errPrefaceTimeout = errors.New("timeout waiting for client preface") - -// readPreface reads the ClientPreface greeting from the peer or -// returns errPrefaceTimeout on timeout, or an error if the greeting -// is invalid. -func (sc *serverConn) readPreface() error { - errc := make(chan error, 1) - go func() { - // Read the client preface - buf := make([]byte, len(ClientPreface)) - if _, err := io.ReadFull(sc.conn, buf); err != nil { - errc <- err - } else if !bytes.Equal(buf, clientPreface) { - errc <- fmt.Errorf("bogus greeting %q", buf) - } else { - errc <- nil - } - }() - timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server? - defer timer.Stop() - select { - case <-timer.C: - return errPrefaceTimeout - case err := <-errc: - if err == nil { - if VerboseLogs { - sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr()) - } - } - return err - } -} - -var errChanPool = sync.Pool{ - New: func() interface{} { return make(chan error, 1) }, -} - -var writeDataPool = sync.Pool{ - New: func() interface{} { return new(writeData) }, -} - -// writeDataFromHandler writes DATA response frames from a handler on -// the given stream. -func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error { - ch := errChanPool.Get().(chan error) - writeArg := writeDataPool.Get().(*writeData) - *writeArg = writeData{stream.id, data, endStream} - err := sc.writeFrameFromHandler(FrameWriteRequest{ - write: writeArg, - stream: stream, - done: ch, - }) - if err != nil { - return err - } - var frameWriteDone bool // the frame write is done (successfully or not) - select { - case err = <-ch: - frameWriteDone = true - case <-sc.doneServing: - return errClientDisconnected - case <-stream.cw: - // If both ch and stream.cw were ready (as might - // happen on the final Write after an http.Handler - // ends), prefer the write result. Otherwise this - // might just be us successfully closing the stream. - // The writeFrameAsync and serve goroutines guarantee - // that the ch send will happen before the stream.cw - // close. - select { - case err = <-ch: - frameWriteDone = true - default: - return errStreamClosed - } - } - errChanPool.Put(ch) - if frameWriteDone { - writeDataPool.Put(writeArg) - } - return err -} - -// writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts -// if the connection has gone away. -// -// This must not be run from the serve goroutine itself, else it might -// deadlock writing to sc.wantWriteFrameCh (which is only mildly -// buffered and is read by serve itself). If you're on the serve -// goroutine, call writeFrame instead. -func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error { - sc.serveG.checkNotOn() // NOT - select { - case sc.wantWriteFrameCh <- wr: - return nil - case <-sc.doneServing: - // Serve loop is gone. - // Client has closed their connection to the server. - return errClientDisconnected - } -} - -// writeFrame schedules a frame to write and sends it if there's nothing -// already being written. -// -// There is no pushback here (the serve goroutine never blocks). It's -// the http.Handlers that block, waiting for their previous frames to -// make it onto the wire -// -// If you're not on the serve goroutine, use writeFrameFromHandler instead. -func (sc *serverConn) writeFrame(wr FrameWriteRequest) { - sc.serveG.check() - - // If true, wr will not be written and wr.done will not be signaled. - var ignoreWrite bool - - // We are not allowed to write frames on closed streams. RFC 7540 Section - // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on - // a closed stream." Our server never sends PRIORITY, so that exception - // does not apply. - // - // The serverConn might close an open stream while the stream's handler - // is still running. For example, the server might close a stream when it - // receives bad data from the client. If this happens, the handler might - // attempt to write a frame after the stream has been closed (since the - // handler hasn't yet been notified of the close). In this case, we simply - // ignore the frame. The handler will notice that the stream is closed when - // it waits for the frame to be written. - // - // As an exception to this rule, we allow sending RST_STREAM after close. - // This allows us to immediately reject new streams without tracking any - // state for those streams (except for the queued RST_STREAM frame). This - // may result in duplicate RST_STREAMs in some cases, but the client should - // ignore those. - if wr.StreamID() != 0 { - _, isReset := wr.write.(StreamError) - if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset { - ignoreWrite = true - } - } - - // Don't send a 100-continue response if we've already sent headers. - // See golang.org/issue/14030. - switch wr.write.(type) { - case *writeResHeaders: - wr.stream.wroteHeaders = true - case write100ContinueHeadersFrame: - if wr.stream.wroteHeaders { - // We do not need to notify wr.done because this frame is - // never written with wr.done != nil. - if wr.done != nil { - panic("wr.done != nil for write100ContinueHeadersFrame") - } - ignoreWrite = true - } - } - - if !ignoreWrite { - sc.writeSched.Push(wr) - } - sc.scheduleFrameWrite() -} - -// startFrameWrite starts a goroutine to write wr (in a separate -// goroutine since that might block on the network), and updates the -// serve goroutine's state about the world, updated from info in wr. -func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) { - sc.serveG.check() - if sc.writingFrame { - panic("internal error: can only be writing one frame at a time") - } - - st := wr.stream - if st != nil { - switch st.state { - case stateHalfClosedLocal: - switch wr.write.(type) { - case StreamError, handlerPanicRST, writeWindowUpdate: - // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE - // in this state. (We never send PRIORITY from the server, so that is not checked.) - default: - panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr)) - } - case stateClosed: - panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr)) - } - } - if wpp, ok := wr.write.(*writePushPromise); ok { - var err error - wpp.promisedID, err = wpp.allocatePromisedID() - if err != nil { - sc.writingFrameAsync = false - wr.replyToWriter(err) - return - } - } - - sc.writingFrame = true - sc.needsFrameFlush = true - if wr.write.staysWithinBuffer(sc.bw.Available()) { - sc.writingFrameAsync = false - err := wr.write.writeFrame(sc) - sc.wroteFrame(frameWriteResult{wr, err}) - } else { - sc.writingFrameAsync = true - go sc.writeFrameAsync(wr) - } -} - -// errHandlerPanicked is the error given to any callers blocked in a read from -// Request.Body when the main goroutine panics. Since most handlers read in the -// the main ServeHTTP goroutine, this will show up rarely. -var errHandlerPanicked = errors.New("http2: handler panicked") - -// wroteFrame is called on the serve goroutine with the result of -// whatever happened on writeFrameAsync. -func (sc *serverConn) wroteFrame(res frameWriteResult) { - sc.serveG.check() - if !sc.writingFrame { - panic("internal error: expected to be already writing a frame") - } - sc.writingFrame = false - sc.writingFrameAsync = false - - wr := res.wr - - if writeEndsStream(wr.write) { - st := wr.stream - if st == nil { - panic("internal error: expecting non-nil stream") - } - switch st.state { - case stateOpen: - // Here we would go to stateHalfClosedLocal in - // theory, but since our handler is done and - // the net/http package provides no mechanism - // for closing a ResponseWriter while still - // reading data (see possible TODO at top of - // this file), we go into closed state here - // anyway, after telling the peer we're - // hanging up on them. We'll transition to - // stateClosed after the RST_STREAM frame is - // written. - st.state = stateHalfClosedLocal - // Section 8.1: a server MAY request that the client abort - // transmission of a request without error by sending a - // RST_STREAM with an error code of NO_ERROR after sending - // a complete response. - sc.resetStream(streamError(st.id, ErrCodeNo)) - case stateHalfClosedRemote: - sc.closeStream(st, errHandlerComplete) - } - } else { - switch v := wr.write.(type) { - case StreamError: - // st may be unknown if the RST_STREAM was generated to reject bad input. - if st, ok := sc.streams[v.StreamID]; ok { - sc.closeStream(st, v) - } - case handlerPanicRST: - sc.closeStream(wr.stream, errHandlerPanicked) - } - } - - // Reply (if requested) to unblock the ServeHTTP goroutine. - wr.replyToWriter(res.err) - - sc.scheduleFrameWrite() -} - -// scheduleFrameWrite tickles the frame writing scheduler. -// -// If a frame is already being written, nothing happens. This will be called again -// when the frame is done being written. -// -// If a frame isn't being written we need to send one, the best frame -// to send is selected, preferring first things that aren't -// stream-specific (e.g. ACKing settings), and then finding the -// highest priority stream. -// -// If a frame isn't being written and there's nothing else to send, we -// flush the write buffer. -func (sc *serverConn) scheduleFrameWrite() { - sc.serveG.check() - if sc.writingFrame || sc.inFrameScheduleLoop { - return - } - sc.inFrameScheduleLoop = true - for !sc.writingFrameAsync { - if sc.needToSendGoAway { - sc.needToSendGoAway = false - sc.startFrameWrite(FrameWriteRequest{ - write: &writeGoAway{ - maxStreamID: sc.maxClientStreamID, - code: sc.goAwayCode, - }, - }) - continue - } - if sc.needToSendSettingsAck { - sc.needToSendSettingsAck = false - sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}}) - continue - } - if !sc.inGoAway || sc.goAwayCode == ErrCodeNo { - if wr, ok := sc.writeSched.Pop(); ok { - sc.startFrameWrite(wr) - continue - } - } - if sc.needsFrameFlush { - sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}}) - sc.needsFrameFlush = false // after startFrameWrite, since it sets this true - continue - } - break - } - sc.inFrameScheduleLoop = false -} - -// startGracefulShutdown gracefully shuts down a connection. This -// sends GOAWAY with ErrCodeNo to tell the client we're gracefully -// shutting down. The connection isn't closed until all current -// streams are done. -// -// startGracefulShutdown returns immediately; it does not wait until -// the connection has shut down. -func (sc *serverConn) startGracefulShutdown() { - sc.serveG.checkNotOn() // NOT - sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) }) -} - -// After sending GOAWAY, the connection will close after goAwayTimeout. -// If we close the connection immediately after sending GOAWAY, there may -// be unsent data in our kernel receive buffer, which will cause the kernel -// to send a TCP RST on close() instead of a FIN. This RST will abort the -// connection immediately, whether or not the client had received the GOAWAY. -// -// Ideally we should delay for at least 1 RTT + epsilon so the client has -// a chance to read the GOAWAY and stop sending messages. Measuring RTT -// is hard, so we approximate with 1 second. See golang.org/issue/18701. -// -// This is a var so it can be shorter in tests, where all requests uses the -// loopback interface making the expected RTT very small. -// -// TODO: configurable? -var goAwayTimeout = 1 * time.Second - -func (sc *serverConn) startGracefulShutdownInternal() { - sc.goAway(ErrCodeNo) -} - -func (sc *serverConn) goAway(code ErrCode) { - sc.serveG.check() - if sc.inGoAway { - return - } - sc.inGoAway = true - sc.needToSendGoAway = true - sc.goAwayCode = code - sc.scheduleFrameWrite() -} - -func (sc *serverConn) shutDownIn(d time.Duration) { - sc.serveG.check() - sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer) -} - -func (sc *serverConn) resetStream(se StreamError) { - sc.serveG.check() - sc.writeFrame(FrameWriteRequest{write: se}) - if st, ok := sc.streams[se.StreamID]; ok { - st.resetQueued = true - } -} - -// processFrameFromReader processes the serve loop's read from readFrameCh from the -// frame-reading goroutine. -// processFrameFromReader returns whether the connection should be kept open. -func (sc *serverConn) processFrameFromReader(res readFrameResult) bool { - sc.serveG.check() - err := res.err - if err != nil { - if err == ErrFrameTooLarge { - sc.goAway(ErrCodeFrameSize) - return true // goAway will close the loop - } - clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) - if clientGone { - // TODO: could we also get into this state if - // the peer does a half close - // (e.g. CloseWrite) because they're done - // sending frames but they're still wanting - // our open replies? Investigate. - // TODO: add CloseWrite to crypto/tls.Conn first - // so we have a way to test this? I suppose - // just for testing we could have a non-TLS mode. - return false - } - } else { - f := res.f - if VerboseLogs { - sc.vlogf("http2: server read frame %v", summarizeFrame(f)) - } - err = sc.processFrame(f) - if err == nil { - return true - } - } - - switch ev := err.(type) { - case StreamError: - sc.resetStream(ev) - return true - case goAwayFlowError: - sc.goAway(ErrCodeFlowControl) - return true - case ConnectionError: - sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev) - sc.goAway(ErrCode(ev)) - return true // goAway will handle shutdown - default: - if res.err != nil { - sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err) - } else { - sc.logf("http2: server closing client connection: %v", err) - } - return false - } -} - -func (sc *serverConn) processFrame(f Frame) error { - sc.serveG.check() - - // First frame received must be SETTINGS. - if !sc.sawFirstSettings { - if _, ok := f.(*SettingsFrame); !ok { - return ConnectionError(ErrCodeProtocol) - } - sc.sawFirstSettings = true - } - - switch f := f.(type) { - case *SettingsFrame: - return sc.processSettings(f) - case *MetaHeadersFrame: - return sc.processHeaders(f) - case *WindowUpdateFrame: - return sc.processWindowUpdate(f) - case *PingFrame: - return sc.processPing(f) - case *DataFrame: - return sc.processData(f) - case *RSTStreamFrame: - return sc.processResetStream(f) - case *PriorityFrame: - return sc.processPriority(f) - case *GoAwayFrame: - return sc.processGoAway(f) - case *PushPromiseFrame: - // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE - // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR. - return ConnectionError(ErrCodeProtocol) - default: - sc.vlogf("http2: server ignoring frame: %v", f.Header()) - return nil - } -} - -func (sc *serverConn) processPing(f *PingFrame) error { - sc.serveG.check() - if f.IsAck() { - // 6.7 PING: " An endpoint MUST NOT respond to PING frames - // containing this flag." - return nil - } - if f.StreamID != 0 { - // "PING frames are not associated with any individual - // stream. If a PING frame is received with a stream - // identifier field value other than 0x0, the recipient MUST - // respond with a connection error (Section 5.4.1) of type - // PROTOCOL_ERROR." - return ConnectionError(ErrCodeProtocol) - } - if sc.inGoAway && sc.goAwayCode != ErrCodeNo { - return nil - } - sc.writeFrame(FrameWriteRequest{write: writePingAck{f}}) - return nil -} - -func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error { - sc.serveG.check() - switch { - case f.StreamID != 0: // stream-level flow control - state, st := sc.state(f.StreamID) - if state == stateIdle { - // Section 5.1: "Receiving any frame other than HEADERS - // or PRIORITY on a stream in this state MUST be - // treated as a connection error (Section 5.4.1) of - // type PROTOCOL_ERROR." - return ConnectionError(ErrCodeProtocol) - } - if st == nil { - // "WINDOW_UPDATE can be sent by a peer that has sent a - // frame bearing the END_STREAM flag. This means that a - // receiver could receive a WINDOW_UPDATE frame on a "half - // closed (remote)" or "closed" stream. A receiver MUST - // NOT treat this as an error, see Section 5.1." - return nil - } - if !st.flow.add(int32(f.Increment)) { - return streamError(f.StreamID, ErrCodeFlowControl) - } - default: // connection-level flow control - if !sc.flow.add(int32(f.Increment)) { - return goAwayFlowError{} - } - } - sc.scheduleFrameWrite() - return nil -} - -func (sc *serverConn) processResetStream(f *RSTStreamFrame) error { - sc.serveG.check() - - state, st := sc.state(f.StreamID) - if state == stateIdle { - // 6.4 "RST_STREAM frames MUST NOT be sent for a - // stream in the "idle" state. If a RST_STREAM frame - // identifying an idle stream is received, the - // recipient MUST treat this as a connection error - // (Section 5.4.1) of type PROTOCOL_ERROR. - return ConnectionError(ErrCodeProtocol) - } - if st != nil { - st.cancelCtx() - sc.closeStream(st, streamError(f.StreamID, f.ErrCode)) - } - return nil -} - -func (sc *serverConn) closeStream(st *stream, err error) { - sc.serveG.check() - if st.state == stateIdle || st.state == stateClosed { - panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state)) - } - st.state = stateClosed - if st.writeDeadline != nil { - st.writeDeadline.Stop() - } - if st.isPushed() { - sc.curPushedStreams-- - } else { - sc.curClientStreams-- - } - delete(sc.streams, st.id) - if len(sc.streams) == 0 { - sc.setConnState(http.StateIdle) - if sc.srv.IdleTimeout != 0 { - sc.idleTimer.Reset(sc.srv.IdleTimeout) - } - if h1ServerKeepAlivesDisabled(sc.hs) { - sc.startGracefulShutdownInternal() - } - } - if p := st.body; p != nil { - // Return any buffered unread bytes worth of conn-level flow control. - // See golang.org/issue/16481 - sc.sendWindowUpdate(nil, p.Len()) - - p.CloseWithError(err) - } - st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc - sc.writeSched.CloseStream(st.id) -} - -func (sc *serverConn) processSettings(f *SettingsFrame) error { - sc.serveG.check() - if f.IsAck() { - sc.unackedSettings-- - if sc.unackedSettings < 0 { - // Why is the peer ACKing settings we never sent? - // The spec doesn't mention this case, but - // hang up on them anyway. - return ConnectionError(ErrCodeProtocol) - } - return nil - } - if err := f.ForeachSetting(sc.processSetting); err != nil { - return err - } - sc.needToSendSettingsAck = true - sc.scheduleFrameWrite() - return nil -} - -func (sc *serverConn) processSetting(s Setting) error { - sc.serveG.check() - if err := s.Valid(); err != nil { - return err - } - if VerboseLogs { - sc.vlogf("http2: server processing setting %v", s) - } - switch s.ID { - case SettingHeaderTableSize: - sc.headerTableSize = s.Val - sc.hpackEncoder.SetMaxDynamicTableSize(s.Val) - case SettingEnablePush: - sc.pushEnabled = s.Val != 0 - case SettingMaxConcurrentStreams: - sc.clientMaxStreams = s.Val - case SettingInitialWindowSize: - return sc.processSettingInitialWindowSize(s.Val) - case SettingMaxFrameSize: - sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31 - case SettingMaxHeaderListSize: - sc.peerMaxHeaderListSize = s.Val - default: - // Unknown setting: "An endpoint that receives a SETTINGS - // frame with any unknown or unsupported identifier MUST - // ignore that setting." - if VerboseLogs { - sc.vlogf("http2: server ignoring unknown setting %v", s) - } - } - return nil -} - -func (sc *serverConn) processSettingInitialWindowSize(val uint32) error { - sc.serveG.check() - // Note: val already validated to be within range by - // processSetting's Valid call. - - // "A SETTINGS frame can alter the initial flow control window - // size for all current streams. When the value of - // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST - // adjust the size of all stream flow control windows that it - // maintains by the difference between the new value and the - // old value." - old := sc.initialStreamSendWindowSize - sc.initialStreamSendWindowSize = int32(val) - growth := int32(val) - old // may be negative - for _, st := range sc.streams { - if !st.flow.add(growth) { - // 6.9.2 Initial Flow Control Window Size - // "An endpoint MUST treat a change to - // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow - // control window to exceed the maximum size as a - // connection error (Section 5.4.1) of type - // FLOW_CONTROL_ERROR." - return ConnectionError(ErrCodeFlowControl) - } - } - return nil -} - -func (sc *serverConn) processData(f *DataFrame) error { - sc.serveG.check() - if sc.inGoAway && sc.goAwayCode != ErrCodeNo { - return nil - } - data := f.Data() - - // "If a DATA frame is received whose stream is not in "open" - // or "half closed (local)" state, the recipient MUST respond - // with a stream error (Section 5.4.2) of type STREAM_CLOSED." - id := f.Header().StreamID - state, st := sc.state(id) - if id == 0 || state == stateIdle { - // Section 5.1: "Receiving any frame other than HEADERS - // or PRIORITY on a stream in this state MUST be - // treated as a connection error (Section 5.4.1) of - // type PROTOCOL_ERROR." - return ConnectionError(ErrCodeProtocol) - } - // RFC 7540, sec 6.1: If a DATA frame is received whose stream is not in - // "open" or "half-closed (local)" state, the recipient MUST respond with a - // stream error (Section 5.4.2) of type STREAM_CLOSED. - if state == stateClosed { - return streamError(id, ErrCodeStreamClosed) - } - if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued { - // This includes sending a RST_STREAM if the stream is - // in stateHalfClosedLocal (which currently means that - // the http.Handler returned, so it's done reading & - // done writing). Try to stop the client from sending - // more DATA. - - // But still enforce their connection-level flow control, - // and return any flow control bytes since we're not going - // to consume them. - if sc.inflow.available() < int32(f.Length) { - return streamError(id, ErrCodeFlowControl) - } - // Deduct the flow control from inflow, since we're - // going to immediately add it back in - // sendWindowUpdate, which also schedules sending the - // frames. - sc.inflow.take(int32(f.Length)) - sc.sendWindowUpdate(nil, int(f.Length)) // conn-level - - if st != nil && st.resetQueued { - // Already have a stream error in flight. Don't send another. - return nil - } - return streamError(id, ErrCodeStreamClosed) - } - if st.body == nil { - panic("internal error: should have a body in this state") - } - - // Sender sending more than they'd declared? - if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes { - st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes)) - // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the - // value of a content-length header field does not equal the sum of the - // DATA frame payload lengths that form the body. - return streamError(id, ErrCodeProtocol) - } - if f.Length > 0 { - // Check whether the client has flow control quota. - if st.inflow.available() < int32(f.Length) { - return streamError(id, ErrCodeFlowControl) - } - st.inflow.take(int32(f.Length)) - - if len(data) > 0 { - wrote, err := st.body.Write(data) - if err != nil { - return streamError(id, ErrCodeStreamClosed) - } - if wrote != len(data) { - panic("internal error: bad Writer") - } - st.bodyBytes += int64(len(data)) - } - - // Return any padded flow control now, since we won't - // refund it later on body reads. - if pad := int32(f.Length) - int32(len(data)); pad > 0 { - sc.sendWindowUpdate32(nil, pad) - sc.sendWindowUpdate32(st, pad) - } - } - if f.StreamEnded() { - st.endStream() - } - return nil -} - -func (sc *serverConn) processGoAway(f *GoAwayFrame) error { - sc.serveG.check() - if f.ErrCode != ErrCodeNo { - sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f) - } else { - sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f) - } - sc.startGracefulShutdownInternal() - // http://tools.ietf.org/html/rfc7540#section-6.8 - // We should not create any new streams, which means we should disable push. - sc.pushEnabled = false - return nil -} - -// isPushed reports whether the stream is server-initiated. -func (st *stream) isPushed() bool { - return st.id%2 == 0 -} - -// endStream closes a Request.Body's pipe. It is called when a DATA -// frame says a request body is over (or after trailers). -func (st *stream) endStream() { - sc := st.sc - sc.serveG.check() - - if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes { - st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes", - st.declBodyBytes, st.bodyBytes)) - } else { - st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest) - st.body.CloseWithError(io.EOF) - } - st.state = stateHalfClosedRemote -} - -// copyTrailersToHandlerRequest is run in the Handler's goroutine in -// its Request.Body.Read just before it gets io.EOF. -func (st *stream) copyTrailersToHandlerRequest() { - for k, vv := range st.trailer { - if _, ok := st.reqTrailer[k]; ok { - // Only copy it over it was pre-declared. - st.reqTrailer[k] = vv - } - } -} - -// onWriteTimeout is run on its own goroutine (from time.AfterFunc) -// when the stream's WriteTimeout has fired. -func (st *stream) onWriteTimeout() { - st.sc.writeFrameFromHandler(FrameWriteRequest{write: streamError(st.id, ErrCodeInternal)}) -} - -func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error { - sc.serveG.check() - id := f.StreamID - if sc.inGoAway { - // Ignore. - return nil - } - // http://tools.ietf.org/html/rfc7540#section-5.1.1 - // Streams initiated by a client MUST use odd-numbered stream - // identifiers. [...] An endpoint that receives an unexpected - // stream identifier MUST respond with a connection error - // (Section 5.4.1) of type PROTOCOL_ERROR. - if id%2 != 1 { - return ConnectionError(ErrCodeProtocol) - } - // A HEADERS frame can be used to create a new stream or - // send a trailer for an open one. If we already have a stream - // open, let it process its own HEADERS frame (trailers at this - // point, if it's valid). - if st := sc.streams[f.StreamID]; st != nil { - if st.resetQueued { - // We're sending RST_STREAM to close the stream, so don't bother - // processing this frame. - return nil - } - // RFC 7540, sec 5.1: If an endpoint receives additional frames, other than - // WINDOW_UPDATE, PRIORITY, or RST_STREAM, for a stream that is in - // this state, it MUST respond with a stream error (Section 5.4.2) of - // type STREAM_CLOSED. - if st.state == stateHalfClosedRemote { - return streamError(id, ErrCodeStreamClosed) - } - return st.processTrailerHeaders(f) - } - - // [...] The identifier of a newly established stream MUST be - // numerically greater than all streams that the initiating - // endpoint has opened or reserved. [...] An endpoint that - // receives an unexpected stream identifier MUST respond with - // a connection error (Section 5.4.1) of type PROTOCOL_ERROR. - if id <= sc.maxClientStreamID { - return ConnectionError(ErrCodeProtocol) - } - sc.maxClientStreamID = id - - if sc.idleTimer != nil { - sc.idleTimer.Stop() - } - - // http://tools.ietf.org/html/rfc7540#section-5.1.2 - // [...] Endpoints MUST NOT exceed the limit set by their peer. An - // endpoint that receives a HEADERS frame that causes their - // advertised concurrent stream limit to be exceeded MUST treat - // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR - // or REFUSED_STREAM. - if sc.curClientStreams+1 > sc.advMaxStreams { - if sc.unackedSettings == 0 { - // They should know better. - return streamError(id, ErrCodeProtocol) - } - // Assume it's a network race, where they just haven't - // received our last SETTINGS update. But actually - // this can't happen yet, because we don't yet provide - // a way for users to adjust server parameters at - // runtime. - return streamError(id, ErrCodeRefusedStream) - } - - initialState := stateOpen - if f.StreamEnded() { - initialState = stateHalfClosedRemote - } - st := sc.newStream(id, 0, initialState) - - if f.HasPriority() { - if err := checkPriority(f.StreamID, f.Priority); err != nil { - return err - } - sc.writeSched.AdjustStream(st.id, f.Priority) - } - - rw, req, err := sc.newWriterAndRequest(st, f) - if err != nil { - return err - } - st.reqTrailer = req.Trailer - if st.reqTrailer != nil { - st.trailer = make(http.Header) - } - st.body = req.Body.(*requestBody).pipe // may be nil - st.declBodyBytes = req.ContentLength - - handler := sc.handler.ServeHTTP - if f.Truncated { - // Their header list was too long. Send a 431 error. - handler = handleHeaderListTooLong - } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil { - handler = new400Handler(err) - } - - // The net/http package sets the read deadline from the - // http.Server.ReadTimeout during the TLS handshake, but then - // passes the connection off to us with the deadline already - // set. Disarm it here after the request headers are read, - // similar to how the http1 server works. Here it's - // technically more like the http1 Server's ReadHeaderTimeout - // (in Go 1.8), though. That's a more sane option anyway. - if sc.hs.ReadTimeout != 0 { - sc.conn.SetReadDeadline(time.Time{}) - } - - go sc.runHandler(rw, req, handler) - return nil -} - -func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error { - sc := st.sc - sc.serveG.check() - if st.gotTrailerHeader { - return ConnectionError(ErrCodeProtocol) - } - st.gotTrailerHeader = true - if !f.StreamEnded() { - return streamError(st.id, ErrCodeProtocol) - } - - if len(f.PseudoFields()) > 0 { - return streamError(st.id, ErrCodeProtocol) - } - if st.trailer != nil { - for _, hf := range f.RegularFields() { - key := sc.canonicalHeader(hf.Name) - if !httpguts.ValidTrailerHeader(key) { - // TODO: send more details to the peer somehow. But http2 has - // no way to send debug data at a stream level. Discuss with - // HTTP folk. - return streamError(st.id, ErrCodeProtocol) - } - st.trailer[key] = append(st.trailer[key], hf.Value) - } - } - st.endStream() - return nil -} - -func checkPriority(streamID uint32, p PriorityParam) error { - if streamID == p.StreamDep { - // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat - // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR." - // Section 5.3.3 says that a stream can depend on one of its dependencies, - // so it's only self-dependencies that are forbidden. - return streamError(streamID, ErrCodeProtocol) - } - return nil -} - -func (sc *serverConn) processPriority(f *PriorityFrame) error { - if sc.inGoAway { - return nil - } - if err := checkPriority(f.StreamID, f.PriorityParam); err != nil { - return err - } - sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam) - return nil -} - -func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream { - sc.serveG.check() - if id == 0 { - panic("internal error: cannot create stream with id 0") - } - - ctx, cancelCtx := contextWithCancel(sc.baseCtx) - st := &stream{ - sc: sc, - id: id, - state: state, - ctx: ctx, - cancelCtx: cancelCtx, - } - st.cw.Init() - st.flow.conn = &sc.flow // link to conn-level counter - st.flow.add(sc.initialStreamSendWindowSize) - st.inflow.conn = &sc.inflow // link to conn-level counter - st.inflow.add(sc.srv.initialStreamRecvWindowSize()) - if sc.hs.WriteTimeout != 0 { - st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout) - } - - sc.streams[id] = st - sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID}) - if st.isPushed() { - sc.curPushedStreams++ - } else { - sc.curClientStreams++ - } - if sc.curOpenStreams() == 1 { - sc.setConnState(http.StateActive) - } - - return st -} - -func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) { - sc.serveG.check() - - rp := requestParam{ - method: f.PseudoValue("method"), - scheme: f.PseudoValue("scheme"), - authority: f.PseudoValue("authority"), - path: f.PseudoValue("path"), - } - - isConnect := rp.method == "CONNECT" - if isConnect { - if rp.path != "" || rp.scheme != "" || rp.authority == "" { - return nil, nil, streamError(f.StreamID, ErrCodeProtocol) - } - } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") { - // See 8.1.2.6 Malformed Requests and Responses: - // - // Malformed requests or responses that are detected - // MUST be treated as a stream error (Section 5.4.2) - // of type PROTOCOL_ERROR." - // - // 8.1.2.3 Request Pseudo-Header Fields - // "All HTTP/2 requests MUST include exactly one valid - // value for the :method, :scheme, and :path - // pseudo-header fields" - return nil, nil, streamError(f.StreamID, ErrCodeProtocol) - } - - bodyOpen := !f.StreamEnded() - if rp.method == "HEAD" && bodyOpen { - // HEAD requests can't have bodies - return nil, nil, streamError(f.StreamID, ErrCodeProtocol) - } - - rp.header = make(http.Header) - for _, hf := range f.RegularFields() { - rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value) - } - if rp.authority == "" { - rp.authority = rp.header.Get("Host") - } - - rw, req, err := sc.newWriterAndRequestNoBody(st, rp) - if err != nil { - return nil, nil, err - } - if bodyOpen { - if vv, ok := rp.header["Content-Length"]; ok { - req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64) - } else { - req.ContentLength = -1 - } - req.Body.(*requestBody).pipe = &pipe{ - b: &dataBuffer{expected: req.ContentLength}, - } - } - return rw, req, nil -} - -type requestParam struct { - method string - scheme, authority, path string - header http.Header -} - -func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) { - sc.serveG.check() - - var tlsState *tls.ConnectionState // nil if not scheme https - if rp.scheme == "https" { - tlsState = sc.tlsState - } - - needsContinue := rp.header.Get("Expect") == "100-continue" - if needsContinue { - rp.header.Del("Expect") - } - // Merge Cookie headers into one "; "-delimited value. - if cookies := rp.header["Cookie"]; len(cookies) > 1 { - rp.header.Set("Cookie", strings.Join(cookies, "; ")) - } - - // Setup Trailers - var trailer http.Header - for _, v := range rp.header["Trailer"] { - for _, key := range strings.Split(v, ",") { - key = http.CanonicalHeaderKey(strings.TrimSpace(key)) - switch key { - case "Transfer-Encoding", "Trailer", "Content-Length": - // Bogus. (copy of http1 rules) - // Ignore. - default: - if trailer == nil { - trailer = make(http.Header) - } - trailer[key] = nil - } - } - } - delete(rp.header, "Trailer") - - var url_ *url.URL - var requestURI string - if rp.method == "CONNECT" { - url_ = &url.URL{Host: rp.authority} - requestURI = rp.authority // mimic HTTP/1 server behavior - } else { - var err error - url_, err = url.ParseRequestURI(rp.path) - if err != nil { - return nil, nil, streamError(st.id, ErrCodeProtocol) - } - requestURI = rp.path - } - - body := &requestBody{ - conn: sc, - stream: st, - needsContinue: needsContinue, - } - req := &http.Request{ - Method: rp.method, - URL: url_, - RemoteAddr: sc.remoteAddrStr, - Header: rp.header, - RequestURI: requestURI, - Proto: "HTTP/2.0", - ProtoMajor: 2, - ProtoMinor: 0, - TLS: tlsState, - Host: rp.authority, - Body: body, - Trailer: trailer, - } - req = requestWithContext(req, st.ctx) - - rws := responseWriterStatePool.Get().(*responseWriterState) - bwSave := rws.bw - *rws = responseWriterState{} // zero all the fields - rws.conn = sc - rws.bw = bwSave - rws.bw.Reset(chunkWriter{rws}) - rws.stream = st - rws.req = req - rws.body = body - - rw := &responseWriter{rws: rws} - return rw, req, nil -} - -// Run on its own goroutine. -func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) { - didPanic := true - defer func() { - rw.rws.stream.cancelCtx() - if didPanic { - e := recover() - sc.writeFrameFromHandler(FrameWriteRequest{ - write: handlerPanicRST{rw.rws.stream.id}, - stream: rw.rws.stream, - }) - // Same as net/http: - if shouldLogPanic(e) { - const size = 64 << 10 - buf := make([]byte, size) - buf = buf[:runtime.Stack(buf, false)] - sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf) - } - return - } - rw.handlerDone() - }() - handler(rw, req) - didPanic = false -} - -func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) { - // 10.5.1 Limits on Header Block Size: - // .. "A server that receives a larger header block than it is - // willing to handle can send an HTTP 431 (Request Header Fields Too - // Large) status code" - const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+ - w.WriteHeader(statusRequestHeaderFieldsTooLarge) - io.WriteString(w, "

HTTP Error 431

Request Header Field(s) Too Large

") -} - -// called from handler goroutines. -// h may be nil. -func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error { - sc.serveG.checkNotOn() // NOT on - var errc chan error - if headerData.h != nil { - // If there's a header map (which we don't own), so we have to block on - // waiting for this frame to be written, so an http.Flush mid-handler - // writes out the correct value of keys, before a handler later potentially - // mutates it. - errc = errChanPool.Get().(chan error) - } - if err := sc.writeFrameFromHandler(FrameWriteRequest{ - write: headerData, - stream: st, - done: errc, - }); err != nil { - return err - } - if errc != nil { - select { - case err := <-errc: - errChanPool.Put(errc) - return err - case <-sc.doneServing: - return errClientDisconnected - case <-st.cw: - return errStreamClosed - } - } - return nil -} - -// called from handler goroutines. -func (sc *serverConn) write100ContinueHeaders(st *stream) { - sc.writeFrameFromHandler(FrameWriteRequest{ - write: write100ContinueHeadersFrame{st.id}, - stream: st, - }) -} - -// A bodyReadMsg tells the server loop that the http.Handler read n -// bytes of the DATA from the client on the given stream. -type bodyReadMsg struct { - st *stream - n int -} - -// called from handler goroutines. -// Notes that the handler for the given stream ID read n bytes of its body -// and schedules flow control tokens to be sent. -func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) { - sc.serveG.checkNotOn() // NOT on - if n > 0 { - select { - case sc.bodyReadCh <- bodyReadMsg{st, n}: - case <-sc.doneServing: - } - } -} - -func (sc *serverConn) noteBodyRead(st *stream, n int) { - sc.serveG.check() - sc.sendWindowUpdate(nil, n) // conn-level - if st.state != stateHalfClosedRemote && st.state != stateClosed { - // Don't send this WINDOW_UPDATE if the stream is closed - // remotely. - sc.sendWindowUpdate(st, n) - } -} - -// st may be nil for conn-level -func (sc *serverConn) sendWindowUpdate(st *stream, n int) { - sc.serveG.check() - // "The legal range for the increment to the flow control - // window is 1 to 2^31-1 (2,147,483,647) octets." - // A Go Read call on 64-bit machines could in theory read - // a larger Read than this. Very unlikely, but we handle it here - // rather than elsewhere for now. - const maxUint31 = 1<<31 - 1 - for n >= maxUint31 { - sc.sendWindowUpdate32(st, maxUint31) - n -= maxUint31 - } - sc.sendWindowUpdate32(st, int32(n)) -} - -// st may be nil for conn-level -func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) { - sc.serveG.check() - if n == 0 { - return - } - if n < 0 { - panic("negative update") - } - var streamID uint32 - if st != nil { - streamID = st.id - } - sc.writeFrame(FrameWriteRequest{ - write: writeWindowUpdate{streamID: streamID, n: uint32(n)}, - stream: st, - }) - var ok bool - if st == nil { - ok = sc.inflow.add(n) - } else { - ok = st.inflow.add(n) - } - if !ok { - panic("internal error; sent too many window updates without decrements?") - } -} - -// requestBody is the Handler's Request.Body type. -// Read and Close may be called concurrently. -type requestBody struct { - stream *stream - conn *serverConn - closed bool // for use by Close only - sawEOF bool // for use by Read only - pipe *pipe // non-nil if we have a HTTP entity message body - needsContinue bool // need to send a 100-continue -} - -func (b *requestBody) Close() error { - if b.pipe != nil && !b.closed { - b.pipe.BreakWithError(errClosedBody) - } - b.closed = true - return nil -} - -func (b *requestBody) Read(p []byte) (n int, err error) { - if b.needsContinue { - b.needsContinue = false - b.conn.write100ContinueHeaders(b.stream) - } - if b.pipe == nil || b.sawEOF { - return 0, io.EOF - } - n, err = b.pipe.Read(p) - if err == io.EOF { - b.sawEOF = true - } - if b.conn == nil && inTests { - return - } - b.conn.noteBodyReadFromHandler(b.stream, n, err) - return -} - -// responseWriter is the http.ResponseWriter implementation. It's -// intentionally small (1 pointer wide) to minimize garbage. The -// responseWriterState pointer inside is zeroed at the end of a -// request (in handlerDone) and calls on the responseWriter thereafter -// simply crash (caller's mistake), but the much larger responseWriterState -// and buffers are reused between multiple requests. -type responseWriter struct { - rws *responseWriterState -} - -// Optional http.ResponseWriter interfaces implemented. -var ( - _ http.CloseNotifier = (*responseWriter)(nil) - _ http.Flusher = (*responseWriter)(nil) - _ stringWriter = (*responseWriter)(nil) -) - -type responseWriterState struct { - // immutable within a request: - stream *stream - req *http.Request - body *requestBody // to close at end of request, if DATA frames didn't - conn *serverConn - - // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc - bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState} - - // mutated by http.Handler goroutine: - handlerHeader http.Header // nil until called - snapHeader http.Header // snapshot of handlerHeader at WriteHeader time - trailers []string // set in writeChunk - status int // status code passed to WriteHeader - wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet. - sentHeader bool // have we sent the header frame? - handlerDone bool // handler has finished - dirty bool // a Write failed; don't reuse this responseWriterState - - sentContentLen int64 // non-zero if handler set a Content-Length header - wroteBytes int64 - - closeNotifierMu sync.Mutex // guards closeNotifierCh - closeNotifierCh chan bool // nil until first used -} - -type chunkWriter struct{ rws *responseWriterState } - -func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) } - -func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 } - -// declareTrailer is called for each Trailer header when the -// response header is written. It notes that a header will need to be -// written in the trailers at the end of the response. -func (rws *responseWriterState) declareTrailer(k string) { - k = http.CanonicalHeaderKey(k) - if !httpguts.ValidTrailerHeader(k) { - // Forbidden by RFC 7230, section 4.1.2. - rws.conn.logf("ignoring invalid trailer %q", k) - return - } - if !strSliceContains(rws.trailers, k) { - rws.trailers = append(rws.trailers, k) - } -} - -// writeChunk writes chunks from the bufio.Writer. But because -// bufio.Writer may bypass its chunking, sometimes p may be -// arbitrarily large. -// -// writeChunk is also responsible (on the first chunk) for sending the -// HEADER response. -func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { - if !rws.wroteHeader { - rws.writeHeader(200) - } - - isHeadResp := rws.req.Method == "HEAD" - if !rws.sentHeader { - rws.sentHeader = true - var ctype, clen string - if clen = rws.snapHeader.Get("Content-Length"); clen != "" { - rws.snapHeader.Del("Content-Length") - clen64, err := strconv.ParseInt(clen, 10, 64) - if err == nil && clen64 >= 0 { - rws.sentContentLen = clen64 - } else { - clen = "" - } - } - if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) { - clen = strconv.Itoa(len(p)) - } - _, hasContentType := rws.snapHeader["Content-Type"] - if !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 { - if cto := rws.snapHeader.Get("X-Content-Type-Options"); strings.EqualFold("nosniff", cto) { - // nosniff is an explicit directive not to guess a content-type. - // Content-sniffing is no less susceptible to polyglot attacks via - // hosted content when done on the server. - ctype = "application/octet-stream" - rws.conn.logf("http2: WriteHeader called with X-Content-Type-Options:nosniff but no Content-Type") - } else { - ctype = http.DetectContentType(p) - } - } - var date string - if _, ok := rws.snapHeader["Date"]; !ok { - // TODO(bradfitz): be faster here, like net/http? measure. - date = time.Now().UTC().Format(http.TimeFormat) - } - - for _, v := range rws.snapHeader["Trailer"] { - foreachHeaderElement(v, rws.declareTrailer) - } - - // "Connection" headers aren't allowed in HTTP/2 (RFC 7540, 8.1.2.2), - // but respect "Connection" == "close" to mean sending a GOAWAY and tearing - // down the TCP connection when idle, like we do for HTTP/1. - // TODO: remove more Connection-specific header fields here, in addition - // to "Connection". - if _, ok := rws.snapHeader["Connection"]; ok { - v := rws.snapHeader.Get("Connection") - delete(rws.snapHeader, "Connection") - if v == "close" { - rws.conn.startGracefulShutdown() - } - } - - endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp - err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ - streamID: rws.stream.id, - httpResCode: rws.status, - h: rws.snapHeader, - endStream: endStream, - contentType: ctype, - contentLength: clen, - date: date, - }) - if err != nil { - rws.dirty = true - return 0, err - } - if endStream { - return 0, nil - } - } - if isHeadResp { - return len(p), nil - } - if len(p) == 0 && !rws.handlerDone { - return 0, nil - } - - if rws.handlerDone { - rws.promoteUndeclaredTrailers() - } - - endStream := rws.handlerDone && !rws.hasTrailers() - if len(p) > 0 || endStream { - // only send a 0 byte DATA frame if we're ending the stream. - if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil { - rws.dirty = true - return 0, err - } - } - - if rws.handlerDone && rws.hasTrailers() { - err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{ - streamID: rws.stream.id, - h: rws.handlerHeader, - trailers: rws.trailers, - endStream: true, - }) - if err != nil { - rws.dirty = true - } - return len(p), err - } - return len(p), nil -} - -// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys -// that, if present, signals that the map entry is actually for -// the response trailers, and not the response headers. The prefix -// is stripped after the ServeHTTP call finishes and the values are -// sent in the trailers. -// -// This mechanism is intended only for trailers that are not known -// prior to the headers being written. If the set of trailers is fixed -// or known before the header is written, the normal Go trailers mechanism -// is preferred: -// https://golang.org/pkg/net/http/#ResponseWriter -// https://golang.org/pkg/net/http/#example_ResponseWriter_trailers -const TrailerPrefix = "Trailer:" - -// promoteUndeclaredTrailers permits http.Handlers to set trailers -// after the header has already been flushed. Because the Go -// ResponseWriter interface has no way to set Trailers (only the -// Header), and because we didn't want to expand the ResponseWriter -// interface, and because nobody used trailers, and because RFC 7230 -// says you SHOULD (but not must) predeclare any trailers in the -// header, the official ResponseWriter rules said trailers in Go must -// be predeclared, and then we reuse the same ResponseWriter.Header() -// map to mean both Headers and Trailers. When it's time to write the -// Trailers, we pick out the fields of Headers that were declared as -// trailers. That worked for a while, until we found the first major -// user of Trailers in the wild: gRPC (using them only over http2), -// and gRPC libraries permit setting trailers mid-stream without -// predeclarnig them. So: change of plans. We still permit the old -// way, but we also permit this hack: if a Header() key begins with -// "Trailer:", the suffix of that key is a Trailer. Because ':' is an -// invalid token byte anyway, there is no ambiguity. (And it's already -// filtered out) It's mildly hacky, but not terrible. -// -// This method runs after the Handler is done and promotes any Header -// fields to be trailers. -func (rws *responseWriterState) promoteUndeclaredTrailers() { - for k, vv := range rws.handlerHeader { - if !strings.HasPrefix(k, TrailerPrefix) { - continue - } - trailerKey := strings.TrimPrefix(k, TrailerPrefix) - rws.declareTrailer(trailerKey) - rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv - } - - if len(rws.trailers) > 1 { - sorter := sorterPool.Get().(*sorter) - sorter.SortStrings(rws.trailers) - sorterPool.Put(sorter) - } -} - -func (w *responseWriter) Flush() { - rws := w.rws - if rws == nil { - panic("Header called after Handler finished") - } - if rws.bw.Buffered() > 0 { - if err := rws.bw.Flush(); err != nil { - // Ignore the error. The frame writer already knows. - return - } - } else { - // The bufio.Writer won't call chunkWriter.Write - // (writeChunk with zero bytes, so we have to do it - // ourselves to force the HTTP response header and/or - // final DATA frame (with END_STREAM) to be sent. - rws.writeChunk(nil) - } -} - -func (w *responseWriter) CloseNotify() <-chan bool { - rws := w.rws - if rws == nil { - panic("CloseNotify called after Handler finished") - } - rws.closeNotifierMu.Lock() - ch := rws.closeNotifierCh - if ch == nil { - ch = make(chan bool, 1) - rws.closeNotifierCh = ch - cw := rws.stream.cw - go func() { - cw.Wait() // wait for close - ch <- true - }() - } - rws.closeNotifierMu.Unlock() - return ch -} - -func (w *responseWriter) Header() http.Header { - rws := w.rws - if rws == nil { - panic("Header called after Handler finished") - } - if rws.handlerHeader == nil { - rws.handlerHeader = make(http.Header) - } - return rws.handlerHeader -} - -// checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode. -func checkWriteHeaderCode(code int) { - // Issue 22880: require valid WriteHeader status codes. - // For now we only enforce that it's three digits. - // In the future we might block things over 599 (600 and above aren't defined - // at http://httpwg.org/specs/rfc7231.html#status.codes) - // and we might block under 200 (once we have more mature 1xx support). - // But for now any three digits. - // - // We used to send "HTTP/1.1 000 0" on the wire in responses but there's - // no equivalent bogus thing we can realistically send in HTTP/2, - // so we'll consistently panic instead and help people find their bugs - // early. (We can't return an error from WriteHeader even if we wanted to.) - if code < 100 || code > 999 { - panic(fmt.Sprintf("invalid WriteHeader code %v", code)) - } -} - -func (w *responseWriter) WriteHeader(code int) { - rws := w.rws - if rws == nil { - panic("WriteHeader called after Handler finished") - } - rws.writeHeader(code) -} - -func (rws *responseWriterState) writeHeader(code int) { - if !rws.wroteHeader { - checkWriteHeaderCode(code) - rws.wroteHeader = true - rws.status = code - if len(rws.handlerHeader) > 0 { - rws.snapHeader = cloneHeader(rws.handlerHeader) - } - } -} - -func cloneHeader(h http.Header) http.Header { - h2 := make(http.Header, len(h)) - for k, vv := range h { - vv2 := make([]string, len(vv)) - copy(vv2, vv) - h2[k] = vv2 - } - return h2 -} - -// The Life Of A Write is like this: -// -// * Handler calls w.Write or w.WriteString -> -// * -> rws.bw (*bufio.Writer) -> -// * (Handler might call Flush) -// * -> chunkWriter{rws} -// * -> responseWriterState.writeChunk(p []byte) -// * -> responseWriterState.writeChunk (most of the magic; see comment there) -func (w *responseWriter) Write(p []byte) (n int, err error) { - return w.write(len(p), p, "") -} - -func (w *responseWriter) WriteString(s string) (n int, err error) { - return w.write(len(s), nil, s) -} - -// either dataB or dataS is non-zero. -func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) { - rws := w.rws - if rws == nil { - panic("Write called after Handler finished") - } - if !rws.wroteHeader { - w.WriteHeader(200) - } - if !bodyAllowedForStatus(rws.status) { - return 0, http.ErrBodyNotAllowed - } - rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set - if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen { - // TODO: send a RST_STREAM - return 0, errors.New("http2: handler wrote more than declared Content-Length") - } - - if dataB != nil { - return rws.bw.Write(dataB) - } else { - return rws.bw.WriteString(dataS) - } -} - -func (w *responseWriter) handlerDone() { - rws := w.rws - dirty := rws.dirty - rws.handlerDone = true - w.Flush() - w.rws = nil - if !dirty { - // Only recycle the pool if all prior Write calls to - // the serverConn goroutine completed successfully. If - // they returned earlier due to resets from the peer - // there might still be write goroutines outstanding - // from the serverConn referencing the rws memory. See - // issue 20704. - responseWriterStatePool.Put(rws) - } -} - -// Push errors. -var ( - ErrRecursivePush = errors.New("http2: recursive push not allowed") - ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS") -) - -// pushOptions is the internal version of http.PushOptions, which we -// cannot include here because it's only defined in Go 1.8 and later. -type pushOptions struct { - Method string - Header http.Header -} - -func (w *responseWriter) push(target string, opts pushOptions) error { - st := w.rws.stream - sc := st.sc - sc.serveG.checkNotOn() - - // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream." - // http://tools.ietf.org/html/rfc7540#section-6.6 - if st.isPushed() { - return ErrRecursivePush - } - - // Default options. - if opts.Method == "" { - opts.Method = "GET" - } - if opts.Header == nil { - opts.Header = http.Header{} - } - wantScheme := "http" - if w.rws.req.TLS != nil { - wantScheme = "https" - } - - // Validate the request. - u, err := url.Parse(target) - if err != nil { - return err - } - if u.Scheme == "" { - if !strings.HasPrefix(target, "/") { - return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target) - } - u.Scheme = wantScheme - u.Host = w.rws.req.Host - } else { - if u.Scheme != wantScheme { - return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme) - } - if u.Host == "" { - return errors.New("URL must have a host") - } - } - for k := range opts.Header { - if strings.HasPrefix(k, ":") { - return fmt.Errorf("promised request headers cannot include pseudo header %q", k) - } - // These headers are meaningful only if the request has a body, - // but PUSH_PROMISE requests cannot have a body. - // http://tools.ietf.org/html/rfc7540#section-8.2 - // Also disallow Host, since the promised URL must be absolute. - switch strings.ToLower(k) { - case "content-length", "content-encoding", "trailer", "te", "expect", "host": - return fmt.Errorf("promised request headers cannot include %q", k) - } - } - if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil { - return err - } - - // The RFC effectively limits promised requests to GET and HEAD: - // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]" - // http://tools.ietf.org/html/rfc7540#section-8.2 - if opts.Method != "GET" && opts.Method != "HEAD" { - return fmt.Errorf("method %q must be GET or HEAD", opts.Method) - } - - msg := &startPushRequest{ - parent: st, - method: opts.Method, - url: u, - header: cloneHeader(opts.Header), - done: errChanPool.Get().(chan error), - } - - select { - case <-sc.doneServing: - return errClientDisconnected - case <-st.cw: - return errStreamClosed - case sc.serveMsgCh <- msg: - } - - select { - case <-sc.doneServing: - return errClientDisconnected - case <-st.cw: - return errStreamClosed - case err := <-msg.done: - errChanPool.Put(msg.done) - return err - } -} - -type startPushRequest struct { - parent *stream - method string - url *url.URL - header http.Header - done chan error -} - -func (sc *serverConn) startPush(msg *startPushRequest) { - sc.serveG.check() - - // http://tools.ietf.org/html/rfc7540#section-6.6. - // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that - // is in either the "open" or "half-closed (remote)" state. - if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote { - // responseWriter.Push checks that the stream is peer-initiaed. - msg.done <- errStreamClosed - return - } - - // http://tools.ietf.org/html/rfc7540#section-6.6. - if !sc.pushEnabled { - msg.done <- http.ErrNotSupported - return - } - - // PUSH_PROMISE frames must be sent in increasing order by stream ID, so - // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE - // is written. Once the ID is allocated, we start the request handler. - allocatePromisedID := func() (uint32, error) { - sc.serveG.check() - - // Check this again, just in case. Technically, we might have received - // an updated SETTINGS by the time we got around to writing this frame. - if !sc.pushEnabled { - return 0, http.ErrNotSupported - } - // http://tools.ietf.org/html/rfc7540#section-6.5.2. - if sc.curPushedStreams+1 > sc.clientMaxStreams { - return 0, ErrPushLimitReached - } - - // http://tools.ietf.org/html/rfc7540#section-5.1.1. - // Streams initiated by the server MUST use even-numbered identifiers. - // A server that is unable to establish a new stream identifier can send a GOAWAY - // frame so that the client is forced to open a new connection for new streams. - if sc.maxPushPromiseID+2 >= 1<<31 { - sc.startGracefulShutdownInternal() - return 0, ErrPushLimitReached - } - sc.maxPushPromiseID += 2 - promisedID := sc.maxPushPromiseID - - // http://tools.ietf.org/html/rfc7540#section-8.2. - // Strictly speaking, the new stream should start in "reserved (local)", then - // transition to "half closed (remote)" after sending the initial HEADERS, but - // we start in "half closed (remote)" for simplicity. - // See further comments at the definition of stateHalfClosedRemote. - promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote) - rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{ - method: msg.method, - scheme: msg.url.Scheme, - authority: msg.url.Host, - path: msg.url.RequestURI(), - header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE - }) - if err != nil { - // Should not happen, since we've already validated msg.url. - panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err)) - } - - go sc.runHandler(rw, req, sc.handler.ServeHTTP) - return promisedID, nil - } - - sc.writeFrame(FrameWriteRequest{ - write: &writePushPromise{ - streamID: msg.parent.id, - method: msg.method, - url: msg.url, - h: msg.header, - allocatePromisedID: allocatePromisedID, - }, - stream: msg.parent, - done: msg.done, - }) -} - -// foreachHeaderElement splits v according to the "#rule" construction -// in RFC 7230 section 7 and calls fn for each non-empty element. -func foreachHeaderElement(v string, fn func(string)) { - v = textproto.TrimString(v) - if v == "" { - return - } - if !strings.Contains(v, ",") { - fn(v) - return - } - for _, f := range strings.Split(v, ",") { - if f = textproto.TrimString(f); f != "" { - fn(f) - } - } -} - -// From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2 -var connHeaders = []string{ - "Connection", - "Keep-Alive", - "Proxy-Connection", - "Transfer-Encoding", - "Upgrade", -} - -// checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request, -// per RFC 7540 Section 8.1.2.2. -// The returned error is reported to users. -func checkValidHTTP2RequestHeaders(h http.Header) error { - for _, k := range connHeaders { - if _, ok := h[k]; ok { - return fmt.Errorf("request header %q is not valid in HTTP/2", k) - } - } - te := h["Te"] - if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) { - return errors.New(`request header "TE" may only be "trailers" in HTTP/2`) - } - return nil -} - -func new400Handler(err error) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - http.Error(w, err.Error(), http.StatusBadRequest) - } -} - -// h1ServerKeepAlivesDisabled reports whether hs has its keep-alives -// disabled. See comments on h1ServerShutdownChan above for why -// the code is written this way. -func h1ServerKeepAlivesDisabled(hs *http.Server) bool { - var x interface{} = hs - type I interface { - doKeepAlives() bool - } - if hs, ok := x.(I); ok { - return !hs.doKeepAlives() - } - return false -} diff --git a/examples/golang.org/x/net/http2/server_push_test.go b/examples/golang.org/x/net/http2/server_push_test.go deleted file mode 100644 index 918fd30..0000000 --- a/examples/golang.org/x/net/http2/server_push_test.go +++ /dev/null @@ -1,521 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package http2 - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "sync" - "testing" - "time" -) - -func TestServer_Push_Success(t *testing.T) { - const ( - mainBody = "index page" - pushedBody = "pushed page" - userAgent = "testagent" - cookie = "testcookie" - ) - - var stURL string - checkPromisedReq := func(r *http.Request, wantMethod string, wantH http.Header) error { - if got, want := r.Method, wantMethod; got != want { - return fmt.Errorf("promised Req.Method=%q, want %q", got, want) - } - if got, want := r.Header, wantH; !reflect.DeepEqual(got, want) { - return fmt.Errorf("promised Req.Header=%q, want %q", got, want) - } - if got, want := "https://"+r.Host, stURL; got != want { - return fmt.Errorf("promised Req.Host=%q, want %q", got, want) - } - if r.Body == nil { - return fmt.Errorf("nil Body") - } - if buf, err := ioutil.ReadAll(r.Body); err != nil || len(buf) != 0 { - return fmt.Errorf("ReadAll(Body)=%q,%v, want '',nil", buf, err) - } - return nil - } - - errc := make(chan error, 3) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - // Push "/pushed?get" as a GET request, using an absolute URL. - opt := &http.PushOptions{ - Header: http.Header{ - "User-Agent": {userAgent}, - }, - } - if err := w.(http.Pusher).Push(stURL+"/pushed?get", opt); err != nil { - errc <- fmt.Errorf("error pushing /pushed?get: %v", err) - return - } - // Push "/pushed?head" as a HEAD request, using a path. - opt = &http.PushOptions{ - Method: "HEAD", - Header: http.Header{ - "User-Agent": {userAgent}, - "Cookie": {cookie}, - }, - } - if err := w.(http.Pusher).Push("/pushed?head", opt); err != nil { - errc <- fmt.Errorf("error pushing /pushed?head: %v", err) - return - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(mainBody))) - w.WriteHeader(200) - io.WriteString(w, mainBody) - errc <- nil - - case "/pushed?get": - wantH := http.Header{} - wantH.Set("User-Agent", userAgent) - if err := checkPromisedReq(r, "GET", wantH); err != nil { - errc <- fmt.Errorf("/pushed?get: %v", err) - return - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(pushedBody))) - w.WriteHeader(200) - io.WriteString(w, pushedBody) - errc <- nil - - case "/pushed?head": - wantH := http.Header{} - wantH.Set("User-Agent", userAgent) - wantH.Set("Cookie", cookie) - if err := checkPromisedReq(r, "HEAD", wantH); err != nil { - errc <- fmt.Errorf("/pushed?head: %v", err) - return - } - w.WriteHeader(204) - errc <- nil - - default: - errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) - } - }) - stURL = st.ts.URL - - // Send one request, which should push two responses. - st.greet() - getSlash(st) - for k := 0; k < 3; k++ { - select { - case <-time.After(2 * time.Second): - t.Errorf("timeout waiting for handler %d to finish", k) - case err := <-errc: - if err != nil { - t.Fatal(err) - } - } - } - - checkPushPromise := func(f Frame, promiseID uint32, wantH [][2]string) error { - pp, ok := f.(*PushPromiseFrame) - if !ok { - return fmt.Errorf("got a %T; want *PushPromiseFrame", f) - } - if !pp.HeadersEnded() { - return fmt.Errorf("want END_HEADERS flag in PushPromiseFrame") - } - if got, want := pp.PromiseID, promiseID; got != want { - return fmt.Errorf("got PromiseID %v; want %v", got, want) - } - gotH := st.decodeHeader(pp.HeaderBlockFragment()) - if !reflect.DeepEqual(gotH, wantH) { - return fmt.Errorf("got promised headers %v; want %v", gotH, wantH) - } - return nil - } - checkHeaders := func(f Frame, wantH [][2]string) error { - hf, ok := f.(*HeadersFrame) - if !ok { - return fmt.Errorf("got a %T; want *HeadersFrame", f) - } - gotH := st.decodeHeader(hf.HeaderBlockFragment()) - if !reflect.DeepEqual(gotH, wantH) { - return fmt.Errorf("got response headers %v; want %v", gotH, wantH) - } - return nil - } - checkData := func(f Frame, wantData string) error { - df, ok := f.(*DataFrame) - if !ok { - return fmt.Errorf("got a %T; want *DataFrame", f) - } - if gotData := string(df.Data()); gotData != wantData { - return fmt.Errorf("got response data %q; want %q", gotData, wantData) - } - return nil - } - - // Stream 1 has 2 PUSH_PROMISE + HEADERS + DATA - // Stream 2 has HEADERS + DATA - // Stream 4 has HEADERS - expected := map[uint32][]func(Frame) error{ - 1: { - func(f Frame) error { - return checkPushPromise(f, 2, [][2]string{ - {":method", "GET"}, - {":scheme", "https"}, - {":authority", st.ts.Listener.Addr().String()}, - {":path", "/pushed?get"}, - {"user-agent", userAgent}, - }) - }, - func(f Frame) error { - return checkPushPromise(f, 4, [][2]string{ - {":method", "HEAD"}, - {":scheme", "https"}, - {":authority", st.ts.Listener.Addr().String()}, - {":path", "/pushed?head"}, - {"cookie", cookie}, - {"user-agent", userAgent}, - }) - }, - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "200"}, - {"content-type", "text/html"}, - {"content-length", strconv.Itoa(len(mainBody))}, - }) - }, - func(f Frame) error { - return checkData(f, mainBody) - }, - }, - 2: { - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "200"}, - {"content-type", "text/html"}, - {"content-length", strconv.Itoa(len(pushedBody))}, - }) - }, - func(f Frame) error { - return checkData(f, pushedBody) - }, - }, - 4: { - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "204"}, - }) - }, - }, - } - - consumed := map[uint32]int{} - for k := 0; len(expected) > 0; k++ { - f, err := st.readFrame() - if err != nil { - for id, left := range expected { - t.Errorf("stream %d: missing %d frames", id, len(left)) - } - t.Fatalf("readFrame %d: %v", k, err) - } - id := f.Header().StreamID - label := fmt.Sprintf("stream %d, frame %d", id, consumed[id]) - if len(expected[id]) == 0 { - t.Fatalf("%s: unexpected frame %#+v", label, f) - } - check := expected[id][0] - expected[id] = expected[id][1:] - if len(expected[id]) == 0 { - delete(expected, id) - } - if err := check(f); err != nil { - t.Fatalf("%s: %v", label, err) - } - consumed[id]++ - } -} - -func TestServer_Push_SuccessNoRace(t *testing.T) { - // Regression test for issue #18326. Ensure the request handler can mutate - // pushed request headers without racing with the PUSH_PROMISE write. - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - opt := &http.PushOptions{ - Header: http.Header{"User-Agent": {"testagent"}}, - } - if err := w.(http.Pusher).Push("/pushed", opt); err != nil { - errc <- fmt.Errorf("error pushing: %v", err) - return - } - w.WriteHeader(200) - errc <- nil - - case "/pushed": - // Update request header, ensure there is no race. - r.Header.Set("User-Agent", "newagent") - r.Header.Set("Cookie", "cookie") - w.WriteHeader(200) - errc <- nil - - default: - errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) - } - }) - - // Send one request, which should push one response. - st.greet() - getSlash(st) - for k := 0; k < 2; k++ { - select { - case <-time.After(2 * time.Second): - t.Errorf("timeout waiting for handler %d to finish", k) - case err := <-errc: - if err != nil { - t.Fatal(err) - } - } - } -} - -func TestServer_Push_RejectRecursivePush(t *testing.T) { - // Expect two requests, but might get three if there's a bug and the second push succeeds. - errc := make(chan error, 3) - handler := func(w http.ResponseWriter, r *http.Request) error { - baseURL := "https://" + r.Host - switch r.URL.Path { - case "/": - if err := w.(http.Pusher).Push(baseURL+"/push1", nil); err != nil { - return fmt.Errorf("first Push()=%v, want nil", err) - } - return nil - - case "/push1": - if got, want := w.(http.Pusher).Push(baseURL+"/push2", nil), ErrRecursivePush; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - - default: - return fmt.Errorf("unexpected path: %q", r.URL.Path) - } - } - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - errc <- handler(w, r) - }) - defer st.Close() - st.greet() - getSlash(st) - if err := <-errc; err != nil { - t.Errorf("First request failed: %v", err) - } - if err := <-errc; err != nil { - t.Errorf("Second request failed: %v", err) - } -} - -func testServer_Push_RejectSingleRequest(t *testing.T, doPush func(http.Pusher, *http.Request) error, settings ...Setting) { - // Expect one request, but might get two if there's a bug and the push succeeds. - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - errc <- doPush(w.(http.Pusher), r) - }) - defer st.Close() - st.greet() - if err := st.fr.WriteSettings(settings...); err != nil { - st.t.Fatalf("WriteSettings: %v", err) - } - st.wantSettingsAck() - getSlash(st) - if err := <-errc; err != nil { - t.Error(err) - } - // Should not get a PUSH_PROMISE frame. - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Error("stream should end after headers") - } -} - -func TestServer_Push_RejectIfDisabled(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if got, want := p.Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - }, - Setting{SettingEnablePush, 0}) -} - -func TestServer_Push_RejectWhenNoConcurrentStreams(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if got, want := p.Push("https://"+r.Host+"/pushed", nil), ErrPushLimitReached; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - }, - Setting{SettingMaxConcurrentStreams, 0}) -} - -func TestServer_Push_RejectWrongScheme(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("http://"+r.Host+"/pushed", nil); err == nil { - return errors.New("Push() should have failed (push target URL is http)") - } - return nil - }) -} - -func TestServer_Push_RejectMissingHost(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("https:pushed", nil); err == nil { - return errors.New("Push() should have failed (push target URL missing host)") - } - return nil - }) -} - -func TestServer_Push_RejectRelativePath(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("../test", nil); err == nil { - return errors.New("Push() should have failed (push target is a relative path)") - } - return nil - }) -} - -func TestServer_Push_RejectForbiddenMethod(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Method: "POST"}); err == nil { - return errors.New("Push() should have failed (cannot promise a POST)") - } - return nil - }) -} - -func TestServer_Push_RejectForbiddenHeader(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - header := http.Header{ - "Content-Length": {"10"}, - "Content-Encoding": {"gzip"}, - "Trailer": {"Foo"}, - "Te": {"trailers"}, - "Host": {"test.com"}, - ":authority": {"test.com"}, - } - if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Header: header}); err == nil { - return errors.New("Push() should have failed (forbidden headers)") - } - return nil - }) -} - -func TestServer_Push_StateTransitions(t *testing.T) { - const body = "foo" - - gotPromise := make(chan bool) - finishedPush := make(chan bool) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - if err := w.(http.Pusher).Push("/pushed", nil); err != nil { - t.Errorf("Push error: %v", err) - } - // Don't finish this request until the push finishes so we don't - // nondeterministically interleave output frames with the push. - <-finishedPush - case "/pushed": - <-gotPromise - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(body))) - w.WriteHeader(200) - io.WriteString(w, body) - }) - defer st.Close() - - st.greet() - if st.stream(2) != nil { - t.Fatal("stream 2 should be empty") - } - if got, want := st.streamState(2), stateIdle; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - getSlash(st) - // After the PUSH_PROMISE is sent, the stream should be stateHalfClosedRemote. - st.wantPushPromise() - if got, want := st.streamState(2), stateHalfClosedRemote; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - // We stall the HTTP handler for "/pushed" until the above check. If we don't - // stall the handler, then the handler might write HEADERS and DATA and finish - // the stream before we check st.streamState(2) -- should that happen, we'll - // see stateClosed and fail the above check. - close(gotPromise) - st.wantHeaders() - if df := st.wantData(); !df.StreamEnded() { - t.Fatal("expected END_STREAM flag on DATA") - } - if got, want := st.streamState(2), stateClosed; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - close(finishedPush) -} - -func TestServer_Push_RejectAfterGoAway(t *testing.T) { - var readyOnce sync.Once - ready := make(chan struct{}) - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - select { - case <-ready: - case <-time.After(5 * time.Second): - errc <- fmt.Errorf("timeout waiting for GOAWAY to be processed") - } - if got, want := w.(http.Pusher).Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { - errc <- fmt.Errorf("Push()=%v, want %v", got, want) - } - errc <- nil - }) - defer st.Close() - st.greet() - getSlash(st) - - // Send GOAWAY and wait for it to be processed. - st.fr.WriteGoAway(1, ErrCodeNo, nil) - go func() { - for { - select { - case <-ready: - return - default: - } - st.sc.serveMsgCh <- func(loopNum int) { - if !st.sc.pushEnabled { - readyOnce.Do(func() { close(ready) }) - } - } - } - }() - if err := <-errc; err != nil { - t.Error(err) - } -} diff --git a/examples/golang.org/x/net/http2/server_test.go b/examples/golang.org/x/net/http2/server_test.go deleted file mode 100644 index 6a27c47..0000000 --- a/examples/golang.org/x/net/http2/server_test.go +++ /dev/null @@ -1,3888 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/http/httptest" - "os" - "os/exec" - "reflect" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/http2/hpack" -) - -var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered") - -func stderrv() io.Writer { - if *stderrVerbose { - return os.Stderr - } - - return ioutil.Discard -} - -type serverTester struct { - cc net.Conn // client conn - t testing.TB - ts *httptest.Server - fr *Framer - serverLogBuf bytes.Buffer // logger for httptest.Server - logFilter []string // substrings to filter out - scMu sync.Mutex // guards sc - sc *serverConn - hpackDec *hpack.Decoder - decodedHeaders [][2]string - - // If http2debug!=2, then we capture Frame debug logs that will be written - // to t.Log after a test fails. The read and write logs use separate locks - // and buffers so we don't accidentally introduce synchronization between - // the read and write goroutines, which may hide data races. - frameReadLogMu sync.Mutex - frameReadLogBuf bytes.Buffer - frameWriteLogMu sync.Mutex - frameWriteLogBuf bytes.Buffer - - // writing headers: - headerBuf bytes.Buffer - hpackEnc *hpack.Encoder -} - -func init() { - testHookOnPanicMu = new(sync.Mutex) - goAwayTimeout = 25 * time.Millisecond -} - -func resetHooks() { - testHookOnPanicMu.Lock() - testHookOnPanic = nil - testHookOnPanicMu.Unlock() -} - -type serverTesterOpt string - -var optOnlyServer = serverTesterOpt("only_server") -var optQuiet = serverTesterOpt("quiet_logging") -var optFramerReuseFrames = serverTesterOpt("frame_reuse_frames") - -func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester { - resetHooks() - - ts := httptest.NewUnstartedServer(handler) - - tlsConfig := &tls.Config{ - InsecureSkipVerify: true, - NextProtos: []string{NextProtoTLS}, - } - - var onlyServer, quiet, framerReuseFrames bool - h2server := new(Server) - for _, opt := range opts { - switch v := opt.(type) { - case func(*tls.Config): - v(tlsConfig) - case func(*httptest.Server): - v(ts) - case func(*Server): - v(h2server) - case serverTesterOpt: - switch v { - case optOnlyServer: - onlyServer = true - case optQuiet: - quiet = true - case optFramerReuseFrames: - framerReuseFrames = true - } - case func(net.Conn, http.ConnState): - ts.Config.ConnState = v - default: - t.Fatalf("unknown newServerTester option type %T", v) - } - } - - ConfigureServer(ts.Config, h2server) - - st := &serverTester{ - t: t, - ts: ts, - } - st.hpackEnc = hpack.NewEncoder(&st.headerBuf) - st.hpackDec = hpack.NewDecoder(initialHeaderTableSize, st.onHeaderField) - - ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config - if quiet { - ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) - } else { - ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv(), twriter{t: t, st: st}, &st.serverLogBuf), "", log.LstdFlags) - } - ts.StartTLS() - - if VerboseLogs { - t.Logf("Running test server at: %s", ts.URL) - } - testHookGetServerConn = func(v *serverConn) { - st.scMu.Lock() - defer st.scMu.Unlock() - st.sc = v - } - log.SetOutput(io.MultiWriter(stderrv(), twriter{t: t, st: st})) - if !onlyServer { - cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig) - if err != nil { - t.Fatal(err) - } - st.cc = cc - st.fr = NewFramer(cc, cc) - if framerReuseFrames { - st.fr.SetReuseFrames() - } - if !logFrameReads && !logFrameWrites { - st.fr.debugReadLoggerf = func(m string, v ...interface{}) { - m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" - st.frameReadLogMu.Lock() - fmt.Fprintf(&st.frameReadLogBuf, m, v...) - st.frameReadLogMu.Unlock() - } - st.fr.debugWriteLoggerf = func(m string, v ...interface{}) { - m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" - st.frameWriteLogMu.Lock() - fmt.Fprintf(&st.frameWriteLogBuf, m, v...) - st.frameWriteLogMu.Unlock() - } - st.fr.logReads = true - st.fr.logWrites = true - } - } - return st -} - -func (st *serverTester) closeConn() { - st.scMu.Lock() - defer st.scMu.Unlock() - st.sc.conn.Close() -} - -func (st *serverTester) addLogFilter(phrase string) { - st.logFilter = append(st.logFilter, phrase) -} - -func (st *serverTester) stream(id uint32) *stream { - ch := make(chan *stream, 1) - st.sc.serveMsgCh <- func(int) { - ch <- st.sc.streams[id] - } - return <-ch -} - -func (st *serverTester) streamState(id uint32) streamState { - ch := make(chan streamState, 1) - st.sc.serveMsgCh <- func(int) { - state, _ := st.sc.state(id) - ch <- state - } - return <-ch -} - -// loopNum reports how many times this conn's select loop has gone around. -func (st *serverTester) loopNum() int { - lastc := make(chan int, 1) - st.sc.serveMsgCh <- func(loopNum int) { - lastc <- loopNum - } - return <-lastc -} - -// awaitIdle heuristically awaits for the server conn's select loop to be idle. -// The heuristic is that the server connection's serve loop must schedule -// 50 times in a row without any channel sends or receives occurring. -func (st *serverTester) awaitIdle() { - remain := 50 - last := st.loopNum() - for remain > 0 { - n := st.loopNum() - if n == last+1 { - remain-- - } else { - remain = 50 - } - last = n - } -} - -func (st *serverTester) Close() { - if st.t.Failed() { - st.frameReadLogMu.Lock() - if st.frameReadLogBuf.Len() > 0 { - st.t.Logf("Framer read log:\n%s", st.frameReadLogBuf.String()) - } - st.frameReadLogMu.Unlock() - - st.frameWriteLogMu.Lock() - if st.frameWriteLogBuf.Len() > 0 { - st.t.Logf("Framer write log:\n%s", st.frameWriteLogBuf.String()) - } - st.frameWriteLogMu.Unlock() - - // If we failed already (and are likely in a Fatal, - // unwindowing), force close the connection, so the - // httptest.Server doesn't wait forever for the conn - // to close. - if st.cc != nil { - st.cc.Close() - } - } - st.ts.Close() - if st.cc != nil { - st.cc.Close() - } - log.SetOutput(os.Stderr) -} - -// greet initiates the client's HTTP/2 connection into a state where -// frames may be sent. -func (st *serverTester) greet() { - st.greetAndCheckSettings(func(Setting) error { return nil }) -} - -func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error) { - st.writePreface() - st.writeInitialSettings() - st.wantSettings().ForeachSetting(checkSetting) - st.writeSettingsAck() - - // The initial WINDOW_UPDATE and SETTINGS ACK can come in any order. - var gotSettingsAck bool - var gotWindowUpdate bool - - for i := 0; i < 2; i++ { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - switch f := f.(type) { - case *SettingsFrame: - if !f.Header().Flags.Has(FlagSettingsAck) { - st.t.Fatal("Settings Frame didn't have ACK set") - } - gotSettingsAck = true - - case *WindowUpdateFrame: - if f.FrameHeader.StreamID != 0 { - st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID) - } - incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize) - if f.Increment != incr { - st.t.Fatalf("WindowUpdate increment = %d; want %d", f.Increment, incr) - } - gotWindowUpdate = true - - default: - st.t.Fatalf("Wanting a settings ACK or window update, received a %T", f) - } - } - - if !gotSettingsAck { - st.t.Fatalf("Didn't get a settings ACK") - } - if !gotWindowUpdate { - st.t.Fatalf("Didn't get a window update") - } -} - -func (st *serverTester) writePreface() { - n, err := st.cc.Write(clientPreface) - if err != nil { - st.t.Fatalf("Error writing client preface: %v", err) - } - if n != len(clientPreface) { - st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface)) - } -} - -func (st *serverTester) writeInitialSettings() { - if err := st.fr.WriteSettings(); err != nil { - st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) - } -} - -func (st *serverTester) writeSettingsAck() { - if err := st.fr.WriteSettingsAck(); err != nil { - st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) - } -} - -func (st *serverTester) writeHeaders(p HeadersFrameParam) { - if err := st.fr.WriteHeaders(p); err != nil { - st.t.Fatalf("Error writing HEADERS: %v", err) - } -} - -func (st *serverTester) writePriority(id uint32, p PriorityParam) { - if err := st.fr.WritePriority(id, p); err != nil { - st.t.Fatalf("Error writing PRIORITY: %v", err) - } -} - -func (st *serverTester) encodeHeaderField(k, v string) { - err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } -} - -// encodeHeaderRaw is the magic-free version of encodeHeader. -// It takes 0 or more (k, v) pairs and encodes them. -func (st *serverTester) encodeHeaderRaw(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - st.headerBuf.Reset() - for len(headers) > 0 { - k, v := headers[0], headers[1] - st.encodeHeaderField(k, v) - headers = headers[2:] - } - return st.headerBuf.Bytes() -} - -// encodeHeader encodes headers and returns their HPACK bytes. headers -// must contain an even number of key/value pairs. There may be -// multiple pairs for keys (e.g. "cookie"). The :method, :path, and -// :scheme headers default to GET, / and https. The :authority header -// defaults to st.ts.Listener.Addr(). -func (st *serverTester) encodeHeader(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - - st.headerBuf.Reset() - defaultAuthority := st.ts.Listener.Addr().String() - - if len(headers) == 0 { - // Fast path, mostly for benchmarks, so test code doesn't pollute - // profiles when we're looking to improve server allocations. - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":scheme", "https") - st.encodeHeaderField(":authority", defaultAuthority) - st.encodeHeaderField(":path", "/") - return st.headerBuf.Bytes() - } - - if len(headers) == 2 && headers[0] == ":method" { - // Another fast path for benchmarks. - st.encodeHeaderField(":method", headers[1]) - st.encodeHeaderField(":scheme", "https") - st.encodeHeaderField(":authority", defaultAuthority) - st.encodeHeaderField(":path", "/") - return st.headerBuf.Bytes() - } - - pseudoCount := map[string]int{} - keys := []string{":method", ":scheme", ":authority", ":path"} - vals := map[string][]string{ - ":method": {"GET"}, - ":scheme": {"https"}, - ":authority": {defaultAuthority}, - ":path": {"/"}, - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if _, ok := vals[k]; !ok { - keys = append(keys, k) - } - if strings.HasPrefix(k, ":") { - pseudoCount[k]++ - if pseudoCount[k] == 1 { - vals[k] = []string{v} - } else { - // Allows testing of invalid headers w/ dup pseudo fields. - vals[k] = append(vals[k], v) - } - } else { - vals[k] = append(vals[k], v) - } - } - for _, k := range keys { - for _, v := range vals[k] { - st.encodeHeaderField(k, v) - } - } - return st.headerBuf.Bytes() -} - -// bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set. -func (st *serverTester) bodylessReq1(headers ...string) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(headers...), - EndStream: true, - EndHeaders: true, - }) -} - -func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { - if err := st.fr.WriteData(streamID, endStream, data); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, pad []byte) { - if err := st.fr.WriteDataPadded(streamID, endStream, data, pad); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func readFrameTimeout(fr *Framer, wait time.Duration) (Frame, error) { - ch := make(chan interface{}, 1) - go func() { - fr, err := fr.ReadFrame() - if err != nil { - ch <- err - } else { - ch <- fr - } - }() - t := time.NewTimer(wait) - select { - case v := <-ch: - t.Stop() - if fr, ok := v.(Frame); ok { - return fr, nil - } - return nil, v.(error) - case <-t.C: - return nil, errors.New("timeout waiting for frame") - } -} - -func (st *serverTester) readFrame() (Frame, error) { - return readFrameTimeout(st.fr, 2*time.Second) -} - -func (st *serverTester) wantHeaders() *HeadersFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a HEADERS frame: %v", err) - } - hf, ok := f.(*HeadersFrame) - if !ok { - st.t.Fatalf("got a %T; want *HeadersFrame", f) - } - return hf -} - -func (st *serverTester) wantContinuation() *ContinuationFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err) - } - cf, ok := f.(*ContinuationFrame) - if !ok { - st.t.Fatalf("got a %T; want *ContinuationFrame", f) - } - return cf -} - -func (st *serverTester) wantData() *DataFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a DATA frame: %v", err) - } - df, ok := f.(*DataFrame) - if !ok { - st.t.Fatalf("got a %T; want *DataFrame", f) - } - return df -} - -func (st *serverTester) wantSettings() *SettingsFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - st.t.Fatalf("got a %T; want *SettingsFrame", f) - } - return sf -} - -func (st *serverTester) wantPing() *PingFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a PING frame: %v", err) - } - pf, ok := f.(*PingFrame) - if !ok { - st.t.Fatalf("got a %T; want *PingFrame", f) - } - return pf -} - -func (st *serverTester) wantGoAway() *GoAwayFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err) - } - gf, ok := f.(*GoAwayFrame) - if !ok { - st.t.Fatalf("got a %T; want *GoAwayFrame", f) - } - return gf -} - -func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting an RSTStream frame: %v", err) - } - rs, ok := f.(*RSTStreamFrame) - if !ok { - st.t.Fatalf("got a %T; want *RSTStreamFrame", f) - } - if rs.FrameHeader.StreamID != streamID { - st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID) - } - if rs.ErrCode != errCode { - st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode) - } -} - -func (st *serverTester) wantWindowUpdate(streamID, incr uint32) { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err) - } - wu, ok := f.(*WindowUpdateFrame) - if !ok { - st.t.Fatalf("got a %T; want *WindowUpdateFrame", f) - } - if wu.FrameHeader.StreamID != streamID { - st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID) - } - if wu.Increment != incr { - st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr) - } -} - -func (st *serverTester) wantSettingsAck() { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - st.t.Fatalf("Wanting a settings ACK, received a %T", f) - } - if !sf.Header().Flags.Has(FlagSettingsAck) { - st.t.Fatal("Settings Frame didn't have ACK set") - } -} - -func (st *serverTester) wantPushPromise() *PushPromiseFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - ppf, ok := f.(*PushPromiseFrame) - if !ok { - st.t.Fatalf("Wanted PushPromise, received %T", ppf) - } - return ppf -} - -func TestServer(t *testing.T) { - gotReq := make(chan bool, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Foo", "Bar") - gotReq <- true - }) - defer st.Close() - - covers("3.5", ` - The server connection preface consists of a potentially empty - SETTINGS frame ([SETTINGS]) that MUST be the first frame the - server sends in the HTTP/2 connection. - `) - - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - - select { - case <-gotReq: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for request") - } -} - -func TestServer_Request_Get(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader("foo-bar", "some-value"), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Method != "GET" { - t.Errorf("Method = %q; want GET", r.Method) - } - if r.URL.Path != "/" { - t.Errorf("URL.Path = %q; want /", r.URL.Path) - } - if r.ContentLength != 0 { - t.Errorf("ContentLength = %v; want 0", r.ContentLength) - } - if r.Close { - t.Error("Close = true; want false") - } - if !strings.Contains(r.RemoteAddr, ":") { - t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr) - } - if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 { - t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor) - } - wantHeader := http.Header{ - "Foo-Bar": []string{"some-value"}, - } - if !reflect.DeepEqual(r.Header, wantHeader) { - t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) - } - if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { - t.Errorf("Read = %d, %v; want 0, EOF", n, err) - } - }) -} - -func TestServer_Request_Get_PathSlashes(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":path", "/%2f/"), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.RequestURI != "/%2f/" { - t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI) - } - if r.URL.Path != "///" { - t.Errorf("URL.Path = %q; want ///", r.URL.Path) - } - }) -} - -// TODO: add a test with EndStream=true on the HEADERS but setting a -// Content-Length anyway. Should we just omit it and force it to -// zero? - -func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != 0 { - t.Errorf("ContentLength = %v; want 0", r.ContentLength) - } - if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { - t.Errorf("Read = %d, %v; want 0, EOF", n, err) - } - }) -} - -func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) { - testBodyContents(t, -1, "", func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, nil) // just kidding. empty body. - }) -} - -func TestServer_Request_Post_Body_OneData(t *testing.T) { - const content = "Some content" - testBodyContents(t, -1, content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte(content)) - }) -} - -func TestServer_Request_Post_Body_TwoData(t *testing.T) { - const content = "Some content" - testBodyContents(t, -1, content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, false, []byte(content[:5])) - st.writeData(1, true, []byte(content[5:])) - }) -} - -func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) { - const content = "Some content" - testBodyContents(t, int64(len(content)), content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", strconv.Itoa(len(content)), - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte(content)) - }) -} - -func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) { - testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes", - func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", "3", - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte("12")) - }) -} - -func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) { - testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes", - func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", "4", - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte("12345")) - }) -} - -func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) { - testServerRequest(t, write, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != wantContentLength { - t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) - } - all, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(all) != wantBody { - t.Errorf("Read = %q; want %q", all, wantBody) - } - if err := r.Body.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - }) -} - -func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) { - testServerRequest(t, write, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != wantContentLength { - t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) - } - all, err := ioutil.ReadAll(r.Body) - if err == nil { - t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.", - wantReadError, all) - } - if !strings.Contains(err.Error(), wantReadError) { - t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError) - } - if err := r.Body.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - }) -} - -// Using a Host header, instead of :authority -func TestServer_Request_Get_Host(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":authority", "", "host", host), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Host != host { - t.Errorf("Host = %q; want %q", r.Host, host) - } - }) -} - -// Using an :authority pseudo-header, instead of Host -func TestServer_Request_Get_Authority(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":authority", host), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Host != host { - t.Errorf("Host = %q; want %q", r.Host, host) - } - }) -} - -func TestServer_Request_WithContinuation(t *testing.T) { - wantHeader := http.Header{ - "Foo-One": []string{"value-one"}, - "Foo-Two": []string{"value-two"}, - "Foo-Three": []string{"value-three"}, - } - testServerRequest(t, func(st *serverTester) { - fullHeaders := st.encodeHeader( - "foo-one", "value-one", - "foo-two", "value-two", - "foo-three", "value-three", - ) - remain := fullHeaders - chunks := 0 - for len(remain) > 0 { - const maxChunkSize = 5 - chunk := remain - if len(chunk) > maxChunkSize { - chunk = chunk[:maxChunkSize] - } - remain = remain[len(chunk):] - - if chunks == 0 { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: chunk, - EndStream: true, // no DATA frames - EndHeaders: false, // we'll have continuation frames - }) - } else { - err := st.fr.WriteContinuation(1, len(remain) == 0, chunk) - if err != nil { - t.Fatal(err) - } - } - chunks++ - } - if chunks < 2 { - t.Fatal("too few chunks") - } - }, func(r *http.Request) { - if !reflect.DeepEqual(r.Header, wantHeader) { - t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) - } - }) -} - -// Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field") -func TestServer_Request_CookieConcat(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.bodylessReq1( - ":authority", host, - "cookie", "a=b", - "cookie", "c=d", - "cookie", "e=f", - ) - }, func(r *http.Request) { - const want = "a=b; c=d; e=f" - if got := r.Header.Get("Cookie"); got != want { - t.Errorf("Cookie = %q; want %q", got, want) - } - }) -} - -func TestServer_Request_Reject_CapitalHeader(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameColon(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has:colon", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameNULL(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has\x00null", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameEmpty(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldValueNewline(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\nnewline") }) -} - -func TestServer_Request_Reject_HeaderFieldValueCR(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\rcarriage") }) -} - -func TestServer_Request_Reject_HeaderFieldValueDEL(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\x7fdel") }) -} - -func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") }) -} - -func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) { - // 8.1.2.3 Request Pseudo-Header Fields - // "All HTTP/2 requests MUST include exactly one valid value" ... - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter("duplicate pseudo-header") - st.bodylessReq1(":method", "GET", ":method", "POST") - }) -} - -func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) { - // 8.1.2.3 Request Pseudo-Header Fields - // "All pseudo-header fields MUST appear in the header block - // before regular header fields. Any request or response that - // contains a pseudo-header field that appears in a header - // block after a regular header field MUST be treated as - // malformed (Section 8.1.2.6)." - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter("pseudo-header after regular header") - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"}) - enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"}) - enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"}) - enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"}) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") }) -} - -func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") }) -} - -func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") }) -} - -func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter(`invalid pseudo-header ":unknown_thing"`) - st.bodylessReq1(":unknown_thing", "") - }) -} - -func testRejectRequest(t *testing.T, send func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("server request made it to handler; should've been rejected") - }) - defer st.Close() - - st.greet() - send(st) - st.wantRSTStream(1, ErrCodeProtocol) -} - -func testRejectRequestWithProtocolError(t *testing.T, send func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("server request made it to handler; should've been rejected") - }, optQuiet) - defer st.Close() - - st.greet() - send(st) - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeProtocol { - t.Errorf("err code = %v; want %v", gf.ErrCode, ErrCodeProtocol) - } -} - -// Section 5.1, on idle connections: "Receiving any frame other than -// HEADERS or PRIORITY on a stream in this state MUST be treated as a -// connection error (Section 5.4.1) of type PROTOCOL_ERROR." -func TestRejectFrameOnIdle_WindowUpdate(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteWindowUpdate(123, 456) - }) -} -func TestRejectFrameOnIdle_Data(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteData(123, true, nil) - }) -} -func TestRejectFrameOnIdle_RSTStream(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteRSTStream(123, ErrCodeCancel) - }) -} - -func TestServer_Request_Connect(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if g, w := r.Method, "CONNECT"; g != w { - t.Errorf("Method = %q; want %q", g, w) - } - if g, w := r.RequestURI, "example.com:123"; g != w { - t.Errorf("RequestURI = %q; want %q", g, w) - } - if g, w := r.URL.Host, "example.com:123"; g != w { - t.Errorf("URL.Host = %q; want %q", g, w) - } - }) -} - -func TestServer_Request_Connect_InvalidPath(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ":path", "/bogus", - ), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Request_Connect_InvalidScheme(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ":scheme", "https", - ), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Ping(t *testing.T) { - st := newServerTester(t, nil) - defer st.Close() - st.greet() - - // Server should ignore this one, since it has ACK set. - ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128} - if err := st.fr.WritePing(true, ackPingData); err != nil { - t.Fatal(err) - } - - // But the server should reply to this one, since ACK is false. - pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} - if err := st.fr.WritePing(false, pingData); err != nil { - t.Fatal(err) - } - - pf := st.wantPing() - if !pf.Flags.Has(FlagPingAck) { - t.Error("response ping doesn't have ACK set") - } - if pf.Data != pingData { - t.Errorf("response ping has data %q; want %q", pf.Data, pingData) - } -} - -func TestServer_RejectsLargeFrames(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("see golang.org/issue/13434") - } - - st := newServerTester(t, nil) - defer st.Close() - st.greet() - - // Write too large of a frame (too large by one byte) - // We ignore the return value because it's expected that the server - // will only read the first 9 bytes (the headre) and then disconnect. - st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1)) - - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeFrameSize { - t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize) - } - if st.serverLogBuf.Len() != 0 { - // Previously we spun here for a bit until the GOAWAY disconnect - // timer fired, logging while we fired. - t.Errorf("unexpected server output: %.500s\n", st.serverLogBuf.Bytes()) - } -} - -func TestServer_Handler_Sends_WindowUpdate(t *testing.T) { - puppet := newHandlerPuppet() - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - puppet.act(w, r) - }) - defer st.Close() - defer puppet.done() - - st.greet() - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // data coming - EndHeaders: true, - }) - st.writeData(1, false, []byte("abcdef")) - puppet.do(readBodyHandler(t, "abc")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - puppet.do(readBodyHandler(t, "def")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - st.writeData(1, true, []byte("ghijkl")) // END_STREAM here - puppet.do(readBodyHandler(t, "ghi")) - puppet.do(readBodyHandler(t, "jkl")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM -} - -// the version of the TestServer_Handler_Sends_WindowUpdate with padding. -// See golang.org/issue/16556 -func TestServer_Handler_Sends_WindowUpdate_Padding(t *testing.T) { - puppet := newHandlerPuppet() - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - puppet.act(w, r) - }) - defer st.Close() - defer puppet.done() - - st.greet() - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - st.writeDataPadded(1, false, []byte("abcdef"), []byte{0, 0, 0, 0}) - - // Expect to immediately get our 5 bytes of padding back for - // both the connection and stream (4 bytes of padding + 1 byte of length) - st.wantWindowUpdate(0, 5) - st.wantWindowUpdate(1, 5) - - puppet.do(readBodyHandler(t, "abc")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - puppet.do(readBodyHandler(t, "def")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) -} - -func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) { - st := newServerTester(t, nil) - defer st.Close() - st.greet() - if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil { - t.Fatal(err) - } - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeFlowControl { - t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl) - } - if gf.LastStreamID != 0 { - t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0) - } -} - -func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) { - inHandler := make(chan bool) - blockHandler := make(chan bool) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - <-blockHandler - }) - defer st.Close() - defer close(blockHandler) - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - // Send a bogus window update: - if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil { - t.Fatal(err) - } - st.wantRSTStream(1, ErrCodeFlowControl) -} - -// testServerPostUnblock sends a hanging POST with unsent data to handler, -// then runs fn once in the handler, and verifies that the error returned from -// handler is acceptable. It fails if takes over 5 seconds for handler to exit. -func testServerPostUnblock(t *testing.T, - handler func(http.ResponseWriter, *http.Request) error, - fn func(*serverTester), - checkErr func(error), - otherHeaders ...string) { - inHandler := make(chan bool) - errc := make(chan error, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - errc <- handler(w, r) - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - fn(st) - select { - case err := <-errc: - if checkErr != nil { - checkErr(err) - } - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for Handler to return") - } -} - -func TestServer_RSTStream_Unblocks_Read(t *testing.T) { - testServerPostUnblock(t, - func(w http.ResponseWriter, r *http.Request) (err error) { - _, err = r.Body.Read(make([]byte, 1)) - return - }, - func(st *serverTester) { - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }, - func(err error) { - want := StreamError{StreamID: 0x1, Code: 0x8} - if !reflect.DeepEqual(err, want) { - t.Errorf("Read error = %v; want %v", err, want) - } - }, - ) -} - -func TestServer_RSTStream_Unblocks_Header_Write(t *testing.T) { - // Run this test a bunch, because it doesn't always - // deadlock. But with a bunch, it did. - n := 50 - if testing.Short() { - n = 5 - } - for i := 0; i < n; i++ { - testServer_RSTStream_Unblocks_Header_Write(t) - } -} - -func testServer_RSTStream_Unblocks_Header_Write(t *testing.T) { - inHandler := make(chan bool, 1) - unblockHandler := make(chan bool, 1) - headerWritten := make(chan bool, 1) - wroteRST := make(chan bool, 1) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - <-wroteRST - w.Header().Set("foo", "bar") - w.WriteHeader(200) - w.(http.Flusher).Flush() - headerWritten <- true - <-unblockHandler - }) - defer st.Close() - - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - wroteRST <- true - st.awaitIdle() - select { - case <-headerWritten: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for header write") - } - unblockHandler <- true -} - -func TestServer_DeadConn_Unblocks_Read(t *testing.T) { - testServerPostUnblock(t, - func(w http.ResponseWriter, r *http.Request) (err error) { - _, err = r.Body.Read(make([]byte, 1)) - return - }, - func(st *serverTester) { st.cc.Close() }, - func(err error) { - if err == nil { - t.Error("unexpected nil error from Request.Body.Read") - } - }, - ) -} - -var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error { - <-w.(http.CloseNotifier).CloseNotify() - return nil -} - -func TestServer_CloseNotify_After_RSTStream(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }, nil) -} - -func TestServer_CloseNotify_After_ConnClose(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil) -} - -// that CloseNotify unblocks after a stream error due to the client's -// problem that's unrelated to them explicitly canceling it (which is -// TestServer_CloseNotify_After_RSTStream above) -func TestServer_CloseNotify_After_StreamError(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { - // data longer than declared Content-Length => stream error - st.writeData(1, true, []byte("1234")) - }, nil, "content-length", "3") -} - -func TestServer_StateTransitions(t *testing.T) { - var st *serverTester - inHandler := make(chan bool) - writeData := make(chan bool) - leaveHandler := make(chan bool) - st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - if st.stream(1) == nil { - t.Errorf("nil stream 1 in handler") - } - if got, want := st.streamState(1), stateOpen; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - writeData <- true - if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF { - t.Errorf("body read = %d, %v; want 0, EOF", n, err) - } - if got, want := st.streamState(1), stateHalfClosedRemote; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - - <-leaveHandler - }) - st.greet() - if st.stream(1) != nil { - t.Fatal("stream 1 should be empty") - } - if got := st.streamState(1); got != stateIdle { - t.Fatalf("stream 1 should be idle; got %v", got) - } - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - <-writeData - st.writeData(1, true, nil) - - leaveHandler <- true - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("expected END_STREAM flag") - } - - if got, want := st.streamState(1), stateClosed; got != want { - t.Errorf("at end, state is %v; want %v", got, want) - } - if st.stream(1) != nil { - t.Fatal("at end, stream 1 should be gone") - } -} - -// test HEADERS w/o EndHeaders + another HEADERS (should get rejected) -func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - st.writeHeaders(HeadersFrameParam{ // Not a continuation. - StreamID: 3, // different stream. - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -// test HEADERS w/o EndHeaders + PING (should get rejected) -func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - if err := st.fr.WritePing(false, [8]byte{}); err != nil { - t.Fatal(err) - } - }) -} - -// test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected) -func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { - t.Fatal(err) - } - }) -} - -// test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID -func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { - t.Fatal(err) - } - }) -} - -// No HEADERS on stream 0. -func TestServer_Rejects_Headers0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writeHeaders(HeadersFrameParam{ - StreamID: 0, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -// No CONTINUATION on stream 0. -func TestServer_Rejects_Continuation0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil { - t.Fatal(err) - } - }) -} - -// No PRIORITY on stream 0. -func TestServer_Rejects_Priority0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writePriority(0, PriorityParam{StreamDep: 1}) - }) -} - -// No HEADERS frame with a self-dependence. -func TestServer_Rejects_HeadersSelfDependence(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - Priority: PriorityParam{StreamDep: 1}, - }) - }) -} - -// No PRIORTY frame with a self-dependence. -func TestServer_Rejects_PrioritySelfDependence(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writePriority(1, PriorityParam{StreamDep: 1}) - }) -} - -func TestServer_Rejects_PushPromise(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - pp := PushPromiseParam{ - StreamID: 1, - PromiseID: 3, - } - if err := st.fr.WritePushPromise(pp); err != nil { - t.Fatal(err) - } - }) -} - -// testServerRejectsConn tests that the server hangs up with a GOAWAY -// frame and a server close after the client does something -// deserving a CONNECTION_ERROR. -func testServerRejectsConn(t *testing.T, writeReq func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - st.addLogFilter("connection error: PROTOCOL_ERROR") - defer st.Close() - st.greet() - writeReq(st) - - st.wantGoAway() - errc := make(chan error, 1) - go func() { - fr, err := st.fr.ReadFrame() - if err == nil { - err = fmt.Errorf("got frame of type %T", fr) - } - errc <- err - }() - select { - case err := <-errc: - if err != io.EOF { - t.Errorf("ReadFrame = %v; want io.EOF", err) - } - case <-time.After(2 * time.Second): - t.Error("timeout waiting for disconnect") - } -} - -// testServerRejectsStream tests that the server sends a RST_STREAM with the provided -// error code after a client sends a bogus request. -func testServerRejectsStream(t *testing.T, code ErrCode, writeReq func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - defer st.Close() - st.greet() - writeReq(st) - st.wantRSTStream(1, code) -} - -// testServerRequest sets up an idle HTTP/2 connection and lets you -// write a single request with writeReq, and then verify that the -// *http.Request is built correctly in checkReq. -func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) { - gotReq := make(chan bool, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if r.Body == nil { - t.Fatal("nil Body") - } - checkReq(r) - gotReq <- true - }) - defer st.Close() - - st.greet() - writeReq(st) - - select { - case <-gotReq: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for request") - } -} - -func getSlash(st *serverTester) { st.bodylessReq1() } - -func TestServer_Response_NoData(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - // Nothing. - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("want END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - }) -} - -func TestServer_Response_NoData_Header_FooBar(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Foo-Bar", "some-value") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("want END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo-bar", "some-value"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) { - const msg = "this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Content-Type", "foo/bar") - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("don't want END_STREAM, expecting data") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "foo/bar"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - df := st.wantData() - if !df.StreamEnded() { - t.Error("expected DATA to have END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - }) -} - -func TestServer_Response_Nosniff_WithoutContentType(t *testing.T) { - const msg = "this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("X-Content-Type-Options", "nosniff") - w.WriteHeader(200) - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("don't want END_STREAM, expecting data") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"x-content-type-options", "nosniff"}, - {"content-type", "application/octet-stream"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - df := st.wantData() - if !df.StreamEnded() { - t.Error("expected DATA to have END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - }) -} - -func TestServer_Response_TransferEncoding_chunked(t *testing.T) { - const msg = "hi" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Transfer-Encoding", "chunked") // should be stripped - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -// Header accessed only after the initial write. -func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) { - const msg = "this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - w.Header().Set("foo", "should be ignored") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -// Header accessed before the initial write and later mutated. -func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) { - const msg = "this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("foo", "proper value") - io.WriteString(w, msg) - w.Header().Set("foo", "should be ignored") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo", "proper value"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -func TestServer_Response_Data_SniffLenType(t *testing.T) { - const msg = "this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("don't want END_STREAM, expecting data") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - df := st.wantData() - if !df.StreamEnded() { - t.Error("expected DATA to have END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - }) -} - -func TestServer_Response_Header_Flush_MidWrite(t *testing.T) { - const msg = "this is HTML" - const msg2 = ", and this is the next chunk" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - io.WriteString(w, msg2) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, // sniffed - // and no content-length - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - { - df := st.wantData() - if df.StreamEnded() { - t.Error("unexpected END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - } - { - df := st.wantData() - if !df.StreamEnded() { - t.Error("wanted END_STREAM flag on last data chunk") - } - if got := string(df.Data()); got != msg2 { - t.Errorf("got DATA %q; want %q", got, msg2) - } - } - }) -} - -func TestServer_Response_LargeWrite(t *testing.T) { - const size = 1 << 20 - const maxFrameSize = 16 << 10 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - n, err := w.Write(bytes.Repeat([]byte("a"), size)) - if err != nil { - return fmt.Errorf("Write error: %v", err) - } - if n != size { - return fmt.Errorf("wrong size %d from Write", n) - } - return nil - }, func(st *serverTester) { - if err := st.fr.WriteSettings( - Setting{SettingInitialWindowSize, 0}, - Setting{SettingMaxFrameSize, maxFrameSize}, - ); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - // Give the handler quota to write: - if err := st.fr.WriteWindowUpdate(1, size); err != nil { - t.Fatal(err) - } - // Give the handler quota to write to connection-level - // window as well - if err := st.fr.WriteWindowUpdate(0, size); err != nil { - t.Fatal(err) - } - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, // sniffed - // and no content-length - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - var bytes, frames int - for { - df := st.wantData() - bytes += len(df.Data()) - frames++ - for _, b := range df.Data() { - if b != 'a' { - t.Fatal("non-'a' byte seen in DATA") - } - } - if df.StreamEnded() { - break - } - } - if bytes != size { - t.Errorf("Got %d bytes; want %d", bytes, size) - } - if want := int(size / maxFrameSize); frames < want || frames > want*2 { - t.Errorf("Got %d frames; want %d", frames, size) - } - }) -} - -// Test that the handler can't write more than the client allows -func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) { - // Make these reads. Before each read, the client adds exactly enough - // flow-control to satisfy the read. Numbers chosen arbitrarily. - reads := []int{123, 1, 13, 127} - size := 0 - for _, n := range reads { - size += n - } - - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - n, err := w.Write(bytes.Repeat([]byte("a"), size)) - if err != nil { - return fmt.Errorf("Write error: %v", err) - } - if n != size { - return fmt.Errorf("wrong size %d from Write", n) - } - return nil - }, func(st *serverTester) { - // Set the window size to something explicit for this test. - // It's also how much initial data we expect. - if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - df := st.wantData() - if got := len(df.Data()); got != reads[0] { - t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got) - } - - for _, quota := range reads[1:] { - if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil { - t.Fatal(err) - } - df := st.wantData() - if int(quota) != len(df.Data()) { - t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota) - } - } - }) -} - -// Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM. -func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) { - const size = 1 << 20 - const maxFrameSize = 16 << 10 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - errc := make(chan error, 1) - go func() { - _, err := w.Write(bytes.Repeat([]byte("a"), size)) - errc <- err - }() - select { - case err := <-errc: - if err == nil { - return errors.New("unexpected nil error from Write in handler") - } - return nil - case <-time.After(2 * time.Second): - return errors.New("timeout waiting for Write in handler") - } - }, func(st *serverTester) { - if err := st.fr.WriteSettings( - Setting{SettingInitialWindowSize, 0}, - Setting{SettingMaxFrameSize, maxFrameSize}, - ); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }) -} - -func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - // Nothing; send empty DATA - return nil - }, func(st *serverTester) { - // Handler gets no data quota: - if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - df := st.wantData() - if got := len(df.Data()); got != 0 { - t.Fatalf("unexpected %d DATA bytes; want 0", got) - } - if !df.StreamEnded() { - t.Fatal("DATA didn't have END_STREAM") - } - }) -} - -func TestServer_Response_Automatic100Continue(t *testing.T) { - const msg = "foo" - const reply = "bar" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - if v := r.Header.Get("Expect"); v != "" { - t.Errorf("Expect header = %q; want empty", v) - } - buf := make([]byte, len(msg)) - // This read should trigger the 100-continue being sent. - if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg { - return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg) - } - _, err := io.WriteString(w, reply) - return err - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"), - EndStream: false, - EndHeaders: true, - }) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "100"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Fatalf("Got headers %v; want %v", goth, wanth) - } - - // Okay, they sent status 100, so we can send our - // gigantic and/or sensitive "foo" payload now. - st.writeData(1, true, []byte(msg)) - - st.wantWindowUpdate(0, uint32(len(msg))) - - hf = st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("expected data to follow") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth = st.decodeHeader(hf.HeaderBlockFragment()) - wanth = [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", strconv.Itoa(len(reply))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - - df := st.wantData() - if string(df.Data()) != reply { - t.Errorf("Client read %q; want %q", df.Data(), reply) - } - if !df.StreamEnded() { - t.Errorf("expect data stream end") - } - }) -} - -func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) { - errc := make(chan error, 1) - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - p := []byte("some data.\n") - for { - _, err := w.Write(p) - if err != nil { - errc <- err - return nil - } - } - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, - EndHeaders: true, - }) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - // Close the connection and wait for the handler to (hopefully) notice. - st.cc.Close() - select { - case <-errc: - case <-time.After(5 * time.Second): - t.Error("timeout") - } - }) -} - -func TestServer_Rejects_Too_Many_Streams(t *testing.T) { - const testPath = "/some/path" - - inHandler := make(chan uint32) - leaveHandler := make(chan bool) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - id := w.(*responseWriter).rws.stream.id - inHandler <- id - if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath { - t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath) - } - <-leaveHandler - }) - defer st.Close() - st.greet() - nextStreamID := uint32(1) - streamID := func() uint32 { - defer func() { nextStreamID += 2 }() - return nextStreamID - } - sendReq := func(id uint32, headers ...string) { - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(headers...), - EndStream: true, - EndHeaders: true, - }) - } - for i := 0; i < defaultMaxStreams; i++ { - sendReq(streamID()) - <-inHandler - } - defer func() { - for i := 0; i < defaultMaxStreams; i++ { - leaveHandler <- true - } - }() - - // And this one should cross the limit: - // (It's also sent as a CONTINUATION, to verify we still track the decoder context, - // even if we're rejecting it) - rejectID := streamID() - headerBlock := st.encodeHeader(":path", testPath) - frag1, frag2 := headerBlock[:3], headerBlock[3:] - st.writeHeaders(HeadersFrameParam{ - StreamID: rejectID, - BlockFragment: frag1, - EndStream: true, - EndHeaders: false, // CONTINUATION coming - }) - if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil { - t.Fatal(err) - } - st.wantRSTStream(rejectID, ErrCodeProtocol) - - // But let a handler finish: - leaveHandler <- true - st.wantHeaders() - - // And now another stream should be able to start: - goodID := streamID() - sendReq(goodID, ":path", testPath) - select { - case got := <-inHandler: - if got != goodID { - t.Errorf("Got stream %d; want %d", got, goodID) - } - case <-time.After(3 * time.Second): - t.Error("timeout waiting for handler") - } -} - -// So many response headers that the server needs to use CONTINUATION frames: -func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - h := w.Header() - for i := 0; i < 5000; i++ { - h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i)) - } - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.HeadersEnded() { - t.Fatal("got unwanted END_HEADERS flag") - } - n := 0 - for { - n++ - cf := st.wantContinuation() - if cf.HeadersEnded() { - break - } - } - if n < 5 { - t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n) - } - }) -} - -// This previously crashed (reported by Mathieu Lonjaret as observed -// while using Camlistore) because we got a DATA frame from the client -// after the handler exited and our logic at the time was wrong, -// keeping a stream in the map in stateClosed, which tickled an -// invariant check later when we tried to remove that stream (via -// defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop -// ended. -func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - // nothing - return nil - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, // DATA is coming - EndHeaders: true, - }) - hf := st.wantHeaders() - if !hf.HeadersEnded() || !hf.StreamEnded() { - t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf) - } - - // Sent when the a Handler closes while a client has - // indicated it's still sending DATA: - st.wantRSTStream(1, ErrCodeNo) - - // Now the handler has ended, so it's ended its - // stream, but the client hasn't closed its side - // (stateClosedLocal). So send more data and verify - // it doesn't crash with an internal invariant panic, like - // it did before. - st.writeData(1, true, []byte("foo")) - - // Sent after a peer sends data anyway (admittedly the - // previous RST_STREAM might've still been in-flight), - // but they'll get the more friendly 'cancel' code - // first. - st.wantRSTStream(1, ErrCodeStreamClosed) - - // Set up a bunch of machinery to record the panic we saw - // previously. - var ( - panMu sync.Mutex - panicVal interface{} - ) - - testHookOnPanicMu.Lock() - testHookOnPanic = func(sc *serverConn, pv interface{}) bool { - panMu.Lock() - panicVal = pv - panMu.Unlock() - return true - } - testHookOnPanicMu.Unlock() - - // Now force the serve loop to end, via closing the connection. - st.cc.Close() - select { - case <-st.sc.doneServing: - // Loop has exited. - panMu.Lock() - got := panicVal - panMu.Unlock() - if got != nil { - t.Errorf("Got panic: %v", got) - } - case <-time.After(5 * time.Second): - t.Error("timeout") - } - }) -} - -func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) } -func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) } - -func testRejectTLS(t *testing.T, max uint16) { - st := newServerTester(t, nil, func(c *tls.Config) { - c.MaxVersion = max - }) - defer st.Close() - gf := st.wantGoAway() - if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { - t.Errorf("Got error code %v; want %v", got, want) - } -} - -func TestServer_Rejects_TLSBadCipher(t *testing.T) { - st := newServerTester(t, nil, func(c *tls.Config) { - // Only list bad ones: - c.CipherSuites = []uint16{ - tls.TLS_RSA_WITH_RC4_128_SHA, - tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, - } - }) - defer st.Close() - gf := st.wantGoAway() - if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { - t.Errorf("Got error code %v; want %v", got, want) - } -} - -func TestServer_Advertises_Common_Cipher(t *testing.T) { - const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - st := newServerTester(t, nil, func(c *tls.Config) { - // Have the client only support the one required by the spec. - c.CipherSuites = []uint16{requiredSuite} - }, func(ts *httptest.Server) { - var srv *http.Server = ts.Config - // Have the server configured with no specific cipher suites. - // This tests that Go's defaults include the required one. - srv.TLSConfig = nil - }) - defer st.Close() - st.greet() -} - -func (st *serverTester) onHeaderField(f hpack.HeaderField) { - if f.Name == "date" { - return - } - st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value}) -} - -func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) { - st.decodedHeaders = nil - if _, err := st.hpackDec.Write(headerBlock); err != nil { - st.t.Fatalf("hpack decoding error: %v", err) - } - if err := st.hpackDec.Close(); err != nil { - st.t.Fatalf("hpack decoding error: %v", err) - } - return st.decodedHeaders -} - -// testServerResponse sets up an idle HTTP/2 connection. The client function should -// write a single request that must be handled by the handler. This waits up to 5s -// for client to return, then up to an additional 2s for the handler to return. -func testServerResponse(t testing.TB, - handler func(http.ResponseWriter, *http.Request) error, - client func(*serverTester), -) { - errc := make(chan error, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if r.Body == nil { - t.Fatal("nil Body") - } - errc <- handler(w, r) - }) - defer st.Close() - - donec := make(chan bool) - go func() { - defer close(donec) - st.greet() - client(st) - }() - - select { - case <-donec: - case <-time.After(5 * time.Second): - t.Fatal("timeout in client") - } - - select { - case err := <-errc: - if err != nil { - t.Fatalf("Error in handler: %v", err) - } - case <-time.After(2 * time.Second): - t.Fatal("timeout in handler") - } -} - -// readBodyHandler returns an http Handler func that reads len(want) -// bytes from r.Body and fails t if the contents read were not -// the value of want. -func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - buf := make([]byte, len(want)) - _, err := io.ReadFull(r.Body, buf) - if err != nil { - t.Error(err) - return - } - if string(buf) != want { - t.Errorf("read %q; want %q", buf, want) - } - } -} - -// TestServerWithCurl currently fails, hence the LenientCipherSuites test. See: -// https://github.com/tatsuhiro-t/nghttp2/issues/140 & -// http://sourceforge.net/p/curl/bugs/1472/ -func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) } -func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) } - -func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) { - if runtime.GOOS != "linux" { - t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") - } - if testing.Short() { - t.Skip("skipping curl test in short mode") - } - requireCurl(t) - var gotConn int32 - testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) } - - const msg = "Hello from curl!\n" - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Foo", "Bar") - w.Header().Set("Client-Proto", r.Proto) - io.WriteString(w, msg) - })) - ConfigureServer(ts.Config, &Server{ - PermitProhibitedCipherSuites: permitProhibitedCipherSuites, - }) - ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config - ts.StartTLS() - defer ts.Close() - - t.Logf("Running test server for curl to hit at: %s", ts.URL) - container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL) - defer kill(container) - resc := make(chan interface{}, 1) - go func() { - res, err := dockerLogs(container) - if err != nil { - resc <- err - } else { - resc <- res - } - }() - select { - case res := <-resc: - if err, ok := res.(error); ok { - t.Fatal(err) - } - body := string(res.([]byte)) - // Search for both "key: value" and "key:value", since curl changed their format - // Our Dockerfile contains the latest version (no space), but just in case people - // didn't rebuild, check both. - if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") { - t.Errorf("didn't see foo: Bar header") - t.Logf("Got: %s", body) - } - if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") { - t.Errorf("didn't see client-proto: HTTP/2 header") - t.Logf("Got: %s", res) - } - if !strings.Contains(string(res.([]byte)), msg) { - t.Errorf("didn't see %q content", msg) - t.Logf("Got: %s", res) - } - case <-time.After(3 * time.Second): - t.Errorf("timeout waiting for curl") - } - - if atomic.LoadInt32(&gotConn) == 0 { - t.Error("never saw an http2 connection") - } -} - -var doh2load = flag.Bool("h2load", false, "Run h2load test") - -func TestServerWithH2Load(t *testing.T) { - if !*doh2load { - t.Skip("Skipping without --h2load flag.") - } - if runtime.GOOS != "linux" { - t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") - } - requireH2load(t) - - msg := strings.Repeat("Hello, h2load!\n", 5000) - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - io.WriteString(w, msg) - })) - ts.StartTLS() - defer ts.Close() - - cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl", - "-n100000", "-c100", "-m100", ts.URL) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - t.Fatal(err) - } -} - -// Issue 12843 -func TestServerDoS_MaxHeaderListSize(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - defer st.Close() - - // shake hands - frameSize := defaultMaxReadFrameSize - var advHeaderListSize *uint32 - st.greetAndCheckSettings(func(s Setting) error { - switch s.ID { - case SettingMaxFrameSize: - if s.Val < minMaxFrameSize { - frameSize = minMaxFrameSize - } else if s.Val > maxFrameSize { - frameSize = maxFrameSize - } else { - frameSize = int(s.Val) - } - case SettingMaxHeaderListSize: - advHeaderListSize = &s.Val - } - return nil - }) - - if advHeaderListSize == nil { - t.Errorf("server didn't advertise a max header list size") - } else if *advHeaderListSize == 0 { - t.Errorf("server advertised a max header list size of 0") - } - - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - cookie := strings.Repeat("*", 4058) - st.encodeHeaderField("cookie", cookie) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.headerBuf.Bytes(), - EndStream: true, - EndHeaders: false, - }) - - // Capture the short encoding of a duplicate ~4K cookie, now - // that we've already sent it once. - st.headerBuf.Reset() - st.encodeHeaderField("cookie", cookie) - - // Now send 1MB of it. - const size = 1 << 20 - b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len()) - for len(b) > 0 { - chunk := b - if len(chunk) > frameSize { - chunk = chunk[:frameSize] - } - b = b[len(chunk):] - st.fr.WriteContinuation(1, len(b) == 0, chunk) - } - - h := st.wantHeaders() - if !h.HeadersEnded() { - t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) - } - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "431"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", "63"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -func TestCompressionErrorOnWrite(t *testing.T) { - const maxStrLen = 8 << 10 - var serverConfig *http.Server - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }, func(ts *httptest.Server) { - serverConfig = ts.Config - serverConfig.MaxHeaderBytes = maxStrLen - }) - st.addLogFilter("connection error: COMPRESSION_ERROR") - defer st.Close() - st.greet() - - maxAllowed := st.sc.framer.maxHeaderStringLen() - - // Crank this up, now that we have a conn connected with the - // hpack.Decoder's max string length set has been initialized - // from the earlier low ~8K value. We want this higher so don't - // hit the max header list size. We only want to test hitting - // the max string size. - serverConfig.MaxHeaderBytes = 1 << 20 - - // First a request with a header that's exactly the max allowed size - // for the hpack compression. It's still too long for the header list - // size, so we'll get the 431 error, but that keeps the compression - // context still valid. - hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed)) - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - if !h.HeadersEnded() { - t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) - } - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "431"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", "63"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } - df := st.wantData() - if !strings.Contains(string(df.Data()), "HTTP Error 431") { - t.Errorf("Unexpected data body: %q", df.Data()) - } - if !df.StreamEnded() { - t.Fatalf("expect data stream end") - } - - // And now send one that's just one byte too big. - hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1)) - st.writeHeaders(HeadersFrameParam{ - StreamID: 3, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeCompression { - t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) - } -} - -func TestCompressionErrorOnClose(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }) - st.addLogFilter("connection error: COMPRESSION_ERROR") - defer st.Close() - st.greet() - - hbf := st.encodeHeader("foo", "bar") - hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails. - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeCompression { - t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) - } -} - -// test that a server handler can read trailers from a client -func TestServerReadsTrailers(t *testing.T) { - const testBody = "some test body" - writeReq := func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"), - EndStream: false, - EndHeaders: true, - }) - st.writeData(1, false, []byte(testBody)) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeaderRaw( - "foo", "foov", - "bar", "barv", - "baz", "bazv", - "surprise", "wasn't declared; shouldn't show up", - ), - EndStream: true, - EndHeaders: true, - }) - } - checkReq := func(r *http.Request) { - wantTrailer := http.Header{ - "Foo": nil, - "Bar": nil, - "Baz": nil, - } - if !reflect.DeepEqual(r.Trailer, wantTrailer) { - t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer) - } - slurp, err := ioutil.ReadAll(r.Body) - if string(slurp) != testBody { - t.Errorf("read body %q; want %q", slurp, testBody) - } - if err != nil { - t.Fatalf("Body slurp: %v", err) - } - wantTrailerAfter := http.Header{ - "Foo": {"foov"}, - "Bar": {"barv"}, - "Baz": {"bazv"}, - } - if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) { - t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter) - } - } - testServerRequest(t, writeReq, checkReq) -} - -// test that a server handler can send trailers -func TestServerWritesTrailers_WithFlush(t *testing.T) { testServerWritesTrailers(t, true) } -func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) } - -func testServerWritesTrailers(t *testing.T, withFlush bool) { - // See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B") - w.Header().Add("Trailer", "Server-Trailer-C") - w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered - - // Regular headers: - w.Header().Set("Foo", "Bar") - w.Header().Set("Content-Length", "5") // len("Hello") - - io.WriteString(w, "Hello") - if withFlush { - w.(http.Flusher).Flush() - } - w.Header().Set("Server-Trailer-A", "valuea") - w.Header().Set("Server-Trailer-C", "valuec") // skipping B - // After a flush, random keys like Server-Surprise shouldn't show up: - w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!") - // But we do permit promoting keys to trailers after a - // flush if they start with the magic - // otherwise-invalid "Trailer:" prefix: - w.Header().Set("Trailer:Post-Header-Trailer", "hi1") - w.Header().Set("Trailer:post-header-trailer2", "hi2") - w.Header().Set("Trailer:Range", "invalid") - w.Header().Set("Trailer:Foo\x01Bogus", "invalid") - w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 7230 4.1.2") - w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 7230 4.1.2") - w.Header().Set("Trailer", "should not be included; Forbidden by RFC 7230 4.1.2") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("response HEADERS had END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("response HEADERS didn't have END_HEADERS") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo", "Bar"}, - {"trailer", "Server-Trailer-A, Server-Trailer-B"}, - {"trailer", "Server-Trailer-C"}, - {"trailer", "Transfer-Encoding, Content-Length, Trailer"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", "5"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - df := st.wantData() - if string(df.Data()) != "Hello" { - t.Fatalf("Client read %q; want Hello", df.Data()) - } - if df.StreamEnded() { - t.Fatalf("data frame had STREAM_ENDED") - } - tf := st.wantHeaders() // for the trailers - if !tf.StreamEnded() { - t.Fatalf("trailers HEADERS lacked END_STREAM") - } - if !tf.HeadersEnded() { - t.Fatalf("trailers HEADERS lacked END_HEADERS") - } - wanth = [][2]string{ - {"post-header-trailer", "hi1"}, - {"post-header-trailer2", "hi2"}, - {"server-trailer-a", "valuea"}, - {"server-trailer-c", "valuec"}, - } - goth = st.decodeHeader(tf.HeaderBlockFragment()) - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - }) -} - -// validate transmitted header field names & values -// golang.org/issue/14048 -func TestServerDoesntWriteInvalidHeaders(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Add("OK1", "x") - w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key - w.Header().Add("Bad1\x00", "x") // null in key - w.Header().Add("Bad2", "x\x00y") // null in value - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Error("response HEADERS lacked END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("response HEADERS didn't have END_HEADERS") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"ok1", "x"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - }) -} - -func BenchmarkServerGets(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - - const msg = "Hello, world" - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - - // Give the server quota to reply. (plus it has the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - - for i := 0; i < b.N; i++ { - id := 1 + uint32(i)*2 - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } - } -} - -func BenchmarkServerPosts(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - - const msg = "Hello, world" - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - // Consume the (empty) body from th peer before replying, otherwise - // the server will sometimes (depending on scheduling) send the peer a - // a RST_STREAM with the CANCEL error code. - if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { - b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - - // Give the server quota to reply. (plus it has the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - - for i := 0; i < b.N; i++ { - id := 1 + uint32(i)*2 - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - st.writeData(id, true, nil) - st.wantHeaders() - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } - } -} - -// Send a stream of messages from server to client in separate data frames. -// Brings up performance issues seen in long streams. -// Created to show problem in go issue #18502 -func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) { - benchmarkServerToClientStream(b) -} - -// Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8 -// Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer. -func BenchmarkServerToClientStreamReuseFrames(b *testing.B) { - benchmarkServerToClientStream(b, optFramerReuseFrames) -} - -func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msgLen = 1 - // default window size - const windowSize = 1<<16 - 1 - - // next message to send from the server and for the client to expect - nextMsg := func(i int) []byte { - msg := make([]byte, msgLen) - msg[0] = byte(i) - if len(msg) != msgLen { - panic("invalid test setup msg length") - } - return msg - } - - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - // Consume the (empty) body from th peer before replying, otherwise - // the server will sometimes (depending on scheduling) send the peer a - // a RST_STREAM with the CANCEL error code. - if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { - b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) - } - for i := 0; i < b.N; i += 1 { - w.Write(nextMsg(i)) - w.(http.Flusher).Flush() - } - }, newServerOpts...) - defer st.Close() - st.greet() - - const id = uint32(1) - - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - - st.writeData(id, true, nil) - st.wantHeaders() - - var pendingWindowUpdate = uint32(0) - - for i := 0; i < b.N; i += 1 { - expected := nextMsg(i) - df := st.wantData() - if bytes.Compare(expected, df.data) != 0 { - b.Fatalf("Bad message received; want %v; got %v", expected, df.data) - } - // try to send infrequent but large window updates so they don't overwhelm the test - pendingWindowUpdate += uint32(len(df.data)) - if pendingWindowUpdate >= windowSize/2 { - if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil { - b.Fatal(err) - } - if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil { - b.Fatal(err) - } - pendingWindowUpdate = 0 - } - } - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } -} - -// go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53 -// Verify we don't hang. -func TestIssue53(t *testing.T) { - const data = "PRI * HTTP/2.0\r\n\r\nSM" + - "\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad" - s := &http.Server{ - ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags), - Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte("hello")) - }), - } - s2 := &Server{ - MaxReadFrameSize: 1 << 16, - PermitProhibitedCipherSuites: true, - } - c := &issue53Conn{[]byte(data), false, false} - s2.ServeConn(c, &ServeConnOpts{BaseConfig: s}) - if !c.closed { - t.Fatal("connection is not closed") - } -} - -type issue53Conn struct { - data []byte - closed bool - written bool -} - -func (c *issue53Conn) Read(b []byte) (n int, err error) { - if len(c.data) == 0 { - return 0, io.EOF - } - n = copy(b, c.data) - c.data = c.data[n:] - return -} - -func (c *issue53Conn) Write(b []byte) (n int, err error) { - c.written = true - return len(b), nil -} - -func (c *issue53Conn) Close() error { - c.closed = true - return nil -} - -func (c *issue53Conn) LocalAddr() net.Addr { - return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} -} -func (c *issue53Conn) RemoteAddr() net.Addr { - return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} -} -func (c *issue53Conn) SetDeadline(t time.Time) error { return nil } -func (c *issue53Conn) SetReadDeadline(t time.Time) error { return nil } -func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil } - -// golang.org/issue/12895 -func TestConfigureServer(t *testing.T) { - tests := []struct { - name string - tlsConfig *tls.Config - wantErr string - }{ - { - name: "empty server", - }, - { - name: "just the required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, - }, - }, - { - name: "just the alternative required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, - }, - }, - { - name: "missing required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}, - }, - wantErr: "is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.", - }, - { - name: "required after bad", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, - }, - wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after", - }, - { - name: "bad after required", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA}, - }, - }, - } - for _, tt := range tests { - srv := &http.Server{TLSConfig: tt.tlsConfig} - err := ConfigureServer(srv, nil) - if (err != nil) != (tt.wantErr != "") { - if tt.wantErr != "" { - t.Errorf("%s: success, but want error", tt.name) - } else { - t.Errorf("%s: unexpected error: %v", tt.name, err) - } - } - if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) { - t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr) - } - if err == nil && !srv.TLSConfig.PreferServerCipherSuites { - t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name) - } - } -} - -func TestServerRejectHeadWithBody(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "HEAD"), - EndStream: false, // what we're testing, a bogus HEAD request with body - EndHeaders: true, - }) - st.wantRSTStream(1, ErrCodeProtocol) -} - -func TestServerNoAutoContentLengthOnHead(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. (or smaller than one frame) - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "HEAD"), - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "200"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -// golang.org/issue/13495 -func TestServerNoDuplicateContentType(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.Header()["Content-Type"] = []string{""} - fmt.Fprintf(w, "hi") - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "200"}, - {"content-type", ""}, - {"content-length", "41"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -func disableGoroutineTracking() (restore func()) { - old := DebugGoroutines - DebugGoroutines = false - return func() { DebugGoroutines = old } -} - -func BenchmarkServer_GetRequest(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msg = "Hello, world." - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - n, err := io.Copy(ioutil.Discard, r.Body) - if err != nil || n > 0 { - b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - - st.greet() - // Give the server quota to reply. (plus it has the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - hbf := st.encodeHeader(":method", "GET") - for i := 0; i < b.N; i++ { - streamID := uint32(1 + 2*i) - st.writeHeaders(HeadersFrameParam{ - StreamID: streamID, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - st.wantData() - } -} - -func BenchmarkServer_PostRequest(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msg = "Hello, world." - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - n, err := io.Copy(ioutil.Discard, r.Body) - if err != nil || n > 0 { - b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - // Give the server quota to reply. (plus it has the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - hbf := st.encodeHeader(":method", "POST") - for i := 0; i < b.N; i++ { - streamID := uint32(1 + 2*i) - st.writeHeaders(HeadersFrameParam{ - StreamID: streamID, - BlockFragment: hbf, - EndStream: false, - EndHeaders: true, - }) - st.writeData(streamID, true, nil) - st.wantHeaders() - st.wantData() - } -} - -type connStateConn struct { - net.Conn - cs tls.ConnectionState -} - -func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs } - -// golang.org/issue/12737 -- handle any net.Conn, not just -// *tls.Conn. -func TestServerHandleCustomConn(t *testing.T) { - var s Server - c1, c2 := net.Pipe() - clientDone := make(chan struct{}) - handlerDone := make(chan struct{}) - var req *http.Request - go func() { - defer close(clientDone) - defer c2.Close() - fr := NewFramer(c2, c2) - io.WriteString(c2, ClientPreface) - fr.WriteSettings() - fr.WriteSettingsAck() - f, err := fr.ReadFrame() - if err != nil { - t.Error(err) - return - } - if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() { - t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f)) - return - } - f, err = fr.ReadFrame() - if err != nil { - t.Error(err) - return - } - if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() { - t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f)) - return - } - var henc hpackEncoder - fr.WriteHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"), - EndStream: true, - EndHeaders: true, - }) - go io.Copy(ioutil.Discard, c2) - <-handlerDone - }() - const testString = "my custom ConnectionState" - fakeConnState := tls.ConnectionState{ - ServerName: testString, - Version: tls.VersionTLS12, - CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - } - go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{ - BaseConfig: &http.Server{ - Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer close(handlerDone) - req = r - }), - }}) - select { - case <-clientDone: - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for handler") - } - if req.TLS == nil { - t.Fatalf("Request.TLS is nil. Got: %#v", req) - } - if req.TLS.ServerName != testString { - t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString) - } -} - -// golang.org/issue/14214 -func TestServer_Rejects_ConnHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("should not get to Handler") - }) - defer st.Close() - st.greet() - st.bodylessReq1("connection", "foo") - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "400"}, - {"content-type", "text/plain; charset=utf-8"}, - {"x-content-type-options", "nosniff"}, - {"content-length", "51"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } -} - -type hpackEncoder struct { - enc *hpack.Encoder - buf bytes.Buffer -} - -func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - he.buf.Reset() - if he.enc == nil { - he.enc = hpack.NewEncoder(&he.buf) - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } - headers = headers[2:] - } - return he.buf.Bytes() -} - -func TestCheckValidHTTP2Request(t *testing.T) { - tests := []struct { - h http.Header - want error - }{ - { - h: http.Header{"Te": {"trailers"}}, - want: nil, - }, - { - h: http.Header{"Te": {"trailers", "bogus"}}, - want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`), - }, - { - h: http.Header{"Foo": {""}}, - want: nil, - }, - { - h: http.Header{"Connection": {""}}, - want: errors.New(`request header "Connection" is not valid in HTTP/2`), - }, - { - h: http.Header{"Proxy-Connection": {""}}, - want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`), - }, - { - h: http.Header{"Keep-Alive": {""}}, - want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`), - }, - { - h: http.Header{"Upgrade": {""}}, - want: errors.New(`request header "Upgrade" is not valid in HTTP/2`), - }, - } - for i, tt := range tests { - got := checkValidHTTP2RequestHeaders(tt.h) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want) - } - } -} - -// golang.org/issue/14030 -func TestExpect100ContinueAfterHandlerWrites(t *testing.T) { - const msg = "Hello" - const msg2 = "World" - - doRead := make(chan bool, 1) - defer close(doRead) // fallback cleanup - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - - // Do a read, which might force a 100-continue status to be sent. - <-doRead - r.Body.Read(make([]byte, 10)) - - io.WriteString(w, msg2) - - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20)) - req.Header.Set("Expect", "100-continue") - - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - buf := make([]byte, len(msg)) - if _, err := io.ReadFull(res.Body, buf); err != nil { - t.Fatal(err) - } - if string(buf) != msg { - t.Fatalf("msg = %q; want %q", buf, msg) - } - - doRead <- true - - if _, err := io.ReadFull(res.Body, buf); err != nil { - t.Fatal(err) - } - if string(buf) != msg2 { - t.Fatalf("second msg = %q; want %q", buf, msg2) - } -} - -type funcReader func([]byte) (n int, err error) - -func (f funcReader) Read(p []byte) (n int, err error) { return f(p) } - -// golang.org/issue/16481 -- return flow control when streams close with unread data. -// (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport) -func TestUnreadFlowControlReturned_Server(t *testing.T) { - unblock := make(chan bool, 1) - defer close(unblock) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // Don't read the 16KB request body. Wait until the client's - // done sending it and then return. This should cause the Server - // to then return those 16KB of flow control to the client. - <-unblock - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - // This previously hung on the 4th iteration. - for i := 0; i < 6; i++ { - body := io.MultiReader( - io.LimitReader(neverEnding('A'), 16<<10), - funcReader(func([]byte) (n int, err error) { - unblock <- true - return 0, io.EOF - }), - ) - req, _ := http.NewRequest("POST", st.ts.URL, body) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - } - -} - -func TestServerIdleTimeout(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - }, func(h2s *Server) { - h2s.IdleTimeout = 500 * time.Millisecond - }) - defer st.Close() - - st.greet() - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } -} - -func TestServerIdleTimeout_AfterRequest(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - const timeout = 250 * time.Millisecond - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - time.Sleep(timeout * 2) - }, func(h2s *Server) { - h2s.IdleTimeout = timeout - }) - defer st.Close() - - st.greet() - - // Send a request which takes twice the timeout. Verifies the - // idle timeout doesn't fire while we're in a request: - st.bodylessReq1() - st.wantHeaders() - - // But the idle timeout should be rearmed after the request - // is done: - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } -} - -// grpc-go closes the Request.Body currently with a Read. -// Verify that it doesn't race. -// See https://github.com/grpc/grpc-go/pull/938 -func TestRequestBodyReadCloseRace(t *testing.T) { - for i := 0; i < 100; i++ { - body := &requestBody{ - pipe: &pipe{ - b: new(bytes.Buffer), - }, - } - body.pipe.CloseWithError(io.EOF) - - done := make(chan bool, 1) - buf := make([]byte, 10) - go func() { - time.Sleep(1 * time.Millisecond) - body.Close() - done <- true - }() - body.Read(buf) - <-done - } -} - -func TestIssue20704Race(t *testing.T) { - if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { - t.Skip("skipping in short mode") - } - const ( - itemSize = 1 << 10 - itemCount = 100 - ) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - for i := 0; i < itemCount; i++ { - _, err := w.Write(make([]byte, itemSize)) - if err != nil { - return - } - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - cl := &http.Client{Transport: tr} - - for i := 0; i < 1000; i++ { - resp, err := cl.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - // Force a RST stream to the server by closing without - // reading the body: - resp.Body.Close() - } -} - -func TestServer_Rejects_TooSmall(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - ioutil.ReadAll(r.Body) - return nil - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", "4", - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte("12345")) - - st.wantRSTStream(1, ErrCodeProtocol) - }) -} - -// Tests that a handler setting "Connection: close" results in a GOAWAY being sent, -// and the connection still completing. -func TestServerHandlerConnectionClose(t *testing.T) { - unblockHandler := make(chan bool, 1) - defer close(unblockHandler) // backup; in case of errors - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Connection", "close") - w.Header().Set("Foo", "bar") - w.(http.Flusher).Flush() - <-unblockHandler - return nil - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - var sawGoAway bool - var sawRes bool - for { - f, err := st.readFrame() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - switch f := f.(type) { - case *GoAwayFrame: - sawGoAway = true - unblockHandler <- true - if f.LastStreamID != 1 || f.ErrCode != ErrCodeNo { - t.Errorf("unexpected GOAWAY frame: %v", summarizeFrame(f)) - } - case *HeadersFrame: - goth := st.decodeHeader(f.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo", "bar"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("got headers %v; want %v", goth, wanth) - } - sawRes = true - case *DataFrame: - if f.StreamID != 1 || !f.StreamEnded() || len(f.Data()) != 0 { - t.Errorf("unexpected DATA frame: %v", summarizeFrame(f)) - } - default: - t.Logf("unexpected frame: %v", summarizeFrame(f)) - } - } - if !sawGoAway { - t.Errorf("didn't see GOAWAY") - } - if !sawRes { - t.Errorf("didn't see response") - } - }) -} - -func TestServer_Headers_HalfCloseRemote(t *testing.T) { - var st *serverTester - writeData := make(chan bool) - writeHeaders := make(chan bool) - leaveHandler := make(chan bool) - st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if st.stream(1) == nil { - t.Errorf("nil stream 1 in handler") - } - if got, want := st.streamState(1), stateOpen; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - writeData <- true - if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF { - t.Errorf("body read = %d, %v; want 0, EOF", n, err) - } - if got, want := st.streamState(1), stateHalfClosedRemote; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - writeHeaders <- true - - <-leaveHandler - }) - st.greet() - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-writeData - st.writeData(1, true, nil) - - <-writeHeaders - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, // keep it open - EndHeaders: true, - }) - - defer close(leaveHandler) - - st.wantRSTStream(1, ErrCodeStreamClosed) -} diff --git a/examples/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml b/examples/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml deleted file mode 100644 index 31a84be..0000000 --- a/examples/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml +++ /dev/null @@ -1,5021 +0,0 @@ - - - - - - - - - - - - - - - - - - - Hypertext Transfer Protocol version 2 - - - Twist -
- mbelshe@chromium.org -
-
- - - Google, Inc -
- fenix@google.com -
-
- - - Mozilla -
- - 331 E Evelyn Street - Mountain View - CA - 94041 - US - - martin.thomson@gmail.com -
-
- - - Applications - HTTPbis - HTTP - SPDY - Web - - - - This specification describes an optimized expression of the semantics of the Hypertext - Transfer Protocol (HTTP). HTTP/2 enables a more efficient use of network resources and a - reduced perception of latency by introducing header field compression and allowing multiple - concurrent messages on the same connection. It also introduces unsolicited push of - representations from servers to clients. - - - This specification is an alternative to, but does not obsolete, the HTTP/1.1 message syntax. - HTTP's existing semantics remain unchanged. - - - - - - Discussion of this draft takes place on the HTTPBIS working group mailing list - (ietf-http-wg@w3.org), which is archived at . - - - Working Group information can be found at ; that specific to HTTP/2 are at . - - - The changes in this draft are summarized in . - - - -
- - -
- - - The Hypertext Transfer Protocol (HTTP) is a wildly successful protocol. However, the - HTTP/1.1 message format () has - several characteristics that have a negative overall effect on application performance - today. - - - In particular, HTTP/1.0 allowed only one request to be outstanding at a time on a given - TCP connection. HTTP/1.1 added request pipelining, but this only partially addressed - request concurrency and still suffers from head-of-line blocking. Therefore, HTTP/1.1 - clients that need to make many requests typically use multiple connections to a server in - order to achieve concurrency and thereby reduce latency. - - - Furthermore, HTTP header fields are often repetitive and verbose, causing unnecessary - network traffic, as well as causing the initial TCP congestion - window to quickly fill. This can result in excessive latency when multiple requests are - made on a new TCP connection. - - - HTTP/2 addresses these issues by defining an optimized mapping of HTTP's semantics to an - underlying connection. Specifically, it allows interleaving of request and response - messages on the same connection and uses an efficient coding for HTTP header fields. It - also allows prioritization of requests, letting more important requests complete more - quickly, further improving performance. - - - The resulting protocol is more friendly to the network, because fewer TCP connections can - be used in comparison to HTTP/1.x. This means less competition with other flows, and - longer-lived connections, which in turn leads to better utilization of available network - capacity. - - - Finally, HTTP/2 also enables more efficient processing of messages through use of binary - message framing. - -
- -
- - HTTP/2 provides an optimized transport for HTTP semantics. HTTP/2 supports all of the core - features of HTTP/1.1, but aims to be more efficient in several ways. - - - The basic protocol unit in HTTP/2 is a frame. Each frame - type serves a different purpose. For example, HEADERS and - DATA frames form the basis of HTTP requests and - responses; other frame types like SETTINGS, - WINDOW_UPDATE, and PUSH_PROMISE are used in support of other - HTTP/2 features. - - - Multiplexing of requests is achieved by having each HTTP request-response exchange - associated with its own stream. Streams are largely - independent of each other, so a blocked or stalled request or response does not prevent - progress on other streams. - - - Flow control and prioritization ensure that it is possible to efficiently use multiplexed - streams. Flow control helps to ensure that only data that - can be used by a receiver is transmitted. Prioritization ensures that limited resources can be directed - to the most important streams first. - - - HTTP/2 adds a new interaction mode, whereby a server can push - responses to a client. Server push allows a server to speculatively send a client - data that the server anticipates the client will need, trading off some network usage - against a potential latency gain. The server does this by synthesizing a request, which it - sends as a PUSH_PROMISE frame. The server is then able to send a response to - the synthetic request on a separate stream. - - - Frames that contain HTTP header fields are compressed. - HTTP requests can be highly redundant, so compression can reduce the size of requests and - responses significantly. - - -
- - The HTTP/2 specification is split into four parts: - - - Starting HTTP/2 covers how an HTTP/2 connection is - initiated. - - - The framing and streams layers describe the way HTTP/2 frames are - structured and formed into multiplexed streams. - - - Frame and error - definitions include details of the frame and error types used in HTTP/2. - - - HTTP mappings and additional - requirements describe how HTTP semantics are expressed using frames and - streams. - - - - - While some of the frame and stream layer concepts are isolated from HTTP, this - specification does not define a completely generic framing layer. The framing and streams - layers are tailored to the needs of the HTTP protocol and server push. - -
- -
- - The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD - NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as - described in RFC 2119. - - - All numeric values are in network byte order. Values are unsigned unless otherwise - indicated. Literal values are provided in decimal or hexadecimal as appropriate. - Hexadecimal literals are prefixed with 0x to distinguish them - from decimal literals. - - - The following terms are used: - - - The endpoint initiating the HTTP/2 connection. - - - A transport-layer connection between two endpoints. - - - An error that affects the entire HTTP/2 connection. - - - Either the client or server of the connection. - - - The smallest unit of communication within an HTTP/2 connection, consisting of a header - and a variable-length sequence of octets structured according to the frame type. - - - An endpoint. When discussing a particular endpoint, "peer" refers to the endpoint - that is remote to the primary subject of discussion. - - - An endpoint that is receiving frames. - - - An endpoint that is transmitting frames. - - - The endpoint which did not initiate the HTTP/2 connection. - - - A bi-directional flow of frames across a virtual channel within the HTTP/2 connection. - - - An error on the individual HTTP/2 stream. - - - - - Finally, the terms "gateway", "intermediary", "proxy", and "tunnel" are defined - in . - -
-
- -
- - An HTTP/2 connection is an application layer protocol running on top of a TCP connection - (). The client is the TCP connection initiator. - - - HTTP/2 uses the same "http" and "https" URI schemes used by HTTP/1.1. HTTP/2 shares the same - default port numbers: 80 for "http" URIs and 443 for "https" URIs. As a result, - implementations processing requests for target resource URIs like http://example.org/foo or https://example.com/bar are required to first discover whether the - upstream server (the immediate peer to which the client wishes to establish a connection) - supports HTTP/2. - - - - The means by which support for HTTP/2 is determined is different for "http" and "https" - URIs. Discovery for "http" URIs is described in . Discovery - for "https" URIs is described in . - - -
- - The protocol defined in this document has two identifiers. - - - - The string "h2" identifies the protocol where HTTP/2 uses TLS. This identifier is used in the TLS application layer protocol negotiation extension (ALPN) - field and any place that HTTP/2 over TLS is identified. - - - The "h2" string is serialized into an ALPN protocol identifier as the two octet - sequence: 0x68, 0x32. - - - - - The string "h2c" identifies the protocol where HTTP/2 is run over cleartext TCP. - This identifier is used in the HTTP/1.1 Upgrade header field and any place that - HTTP/2 over TCP is identified. - - - - - - Negotiating "h2" or "h2c" implies the use of the transport, security, framing and message - semantics described in this document. - - - RFC Editor's Note: please remove the remainder of this section prior to the - publication of a final version of this document. - - - Only implementations of the final, published RFC can identify themselves as "h2" or "h2c". - Until such an RFC exists, implementations MUST NOT identify themselves using these - strings. - - - Examples and text throughout the rest of this document use "h2" as a matter of - editorial convenience only. Implementations of draft versions MUST NOT identify using - this string. - - - Implementations of draft versions of the protocol MUST add the string "-" and the - corresponding draft number to the identifier. For example, draft-ietf-httpbis-http2-11 - over TLS is identified using the string "h2-11". - - - Non-compatible experiments that are based on these draft versions MUST append the string - "-" and an experiment name to the identifier. For example, an experimental implementation - of packet mood-based encoding based on draft-ietf-httpbis-http2-09 might identify itself - as "h2-09-emo". Note that any label MUST conform to the "token" syntax defined in - . Experimenters are - encouraged to coordinate their experiments on the ietf-http-wg@w3.org mailing list. - -
- -
- - A client that makes a request for an "http" URI without prior knowledge about support for - HTTP/2 uses the HTTP Upgrade mechanism (). The client makes an HTTP/1.1 request that includes an Upgrade - header field identifying HTTP/2 with the "h2c" token. The HTTP/1.1 request MUST include - exactly one HTTP2-Settings header field. - -
- For example: - - -]]> -
- - Requests that contain an entity body MUST be sent in their entirety before the client can - send HTTP/2 frames. This means that a large request entity can block the use of the - connection until it is completely sent. - - - If concurrency of an initial request with subsequent requests is important, an OPTIONS - request can be used to perform the upgrade to HTTP/2, at the cost of an additional - round-trip. - - - A server that does not support HTTP/2 can respond to the request as though the Upgrade - header field were absent: - -
- -HTTP/1.1 200 OK -Content-Length: 243 -Content-Type: text/html - -... - -
- - A server MUST ignore a "h2" token in an Upgrade header field. Presence of a token with - "h2" implies HTTP/2 over TLS, which is instead negotiated as described in . - - - A server that supports HTTP/2 can accept the upgrade with a 101 (Switching Protocols) - response. After the empty line that terminates the 101 response, the server can begin - sending HTTP/2 frames. These frames MUST include a response to the request that initiated - the Upgrade. - - -
- - For example: - - -HTTP/1.1 101 Switching Protocols -Connection: Upgrade -Upgrade: h2c - -[ HTTP/2 connection ... - -
- - The first HTTP/2 frame sent by the server is a SETTINGS frame () as the server connection preface (). Upon receiving the 101 response, the client sends a connection preface, which includes a - SETTINGS frame. - - - The HTTP/1.1 request that is sent prior to upgrade is assigned stream identifier 1 and is - assigned default priority values. Stream 1 is - implicitly half closed from the client toward the server, since the request is completed - as an HTTP/1.1 request. After commencing the HTTP/2 connection, stream 1 is used for the - response. - - -
- - A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Settings header field. The HTTP2-Settings header field is a connection-specific header field - that includes parameters that govern the HTTP/2 connection, provided in anticipation of - the server accepting the request to upgrade. - -
- -
- - A server MUST NOT upgrade the connection to HTTP/2 if this header field is not present, - or if more than one is present. A server MUST NOT send this header field. - - - - The content of the HTTP2-Settings header field is the - payload of a SETTINGS frame (), encoded as a - base64url string (that is, the URL- and filename-safe Base64 encoding described in , with any trailing '=' characters omitted). The - ABNF production for token68 is - defined in . - - - Since the upgrade is only intended to apply to the immediate connection, a client - sending HTTP2-Settings MUST also send HTTP2-Settings as a connection option in the Connection header field to prevent it from being forwarded - downstream. - - - A server decodes and interprets these values as it would any other - SETTINGS frame. Acknowledgement of the - SETTINGS parameters is not necessary, since a 101 response serves as implicit - acknowledgment. Providing these values in the Upgrade request gives a client an - opportunity to provide parameters prior to receiving any frames from the server. - -
-
- -
- - A client that makes a request to an "https" URI uses TLS - with the application layer protocol negotiation extension. - - - HTTP/2 over TLS uses the "h2" application token. The "h2c" token MUST NOT be sent by a - client or selected by a server. - - - Once TLS negotiation is complete, both the client and the server send a connection preface. - -
- -
- - A client can learn that a particular server supports HTTP/2 by other means. For example, - describes a mechanism for advertising this capability. - - - A client MAY immediately send HTTP/2 frames to a server that is known to support HTTP/2, - after the connection preface; a server can - identify such a connection by the presence of the connection preface. This only affects - the establishment of HTTP/2 connections over cleartext TCP; implementations that support - HTTP/2 over TLS MUST use protocol negotiation in TLS. - - - Without additional information, prior support for HTTP/2 is not a strong signal that a - given server will support HTTP/2 for future connections. For example, it is possible for - server configurations to change, for configurations to differ between instances in - clustered servers, or for network conditions to change. - -
- -
- - Upon establishment of a TCP connection and determination that HTTP/2 will be used by both - peers, each endpoint MUST send a connection preface as a final confirmation and to - establish the initial SETTINGS parameters for the HTTP/2 connection. The client and - server each send a different connection preface. - - - The client connection preface starts with a sequence of 24 octets, which in hex notation - are: - -
- -
- - (the string PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n). This sequence - is followed by a SETTINGS frame (). The - SETTINGS frame MAY be empty. The client sends the client connection - preface immediately upon receipt of a 101 Switching Protocols response (indicating a - successful upgrade), or as the first application data octets of a TLS connection. If - starting an HTTP/2 connection with prior knowledge of server support for the protocol, the - client connection preface is sent upon connection establishment. - - - - - The client connection preface is selected so that a large proportion of HTTP/1.1 or - HTTP/1.0 servers and intermediaries do not attempt to process further frames. Note - that this does not address the concerns raised in . - - - - - The server connection preface consists of a potentially empty SETTINGS - frame () that MUST be the first frame the server sends in the - HTTP/2 connection. - - - The SETTINGS frames received from a peer as part of the connection preface - MUST be acknowledged (see ) after sending the connection - preface. - - - To avoid unnecessary latency, clients are permitted to send additional frames to the - server immediately after sending the client connection preface, without waiting to receive - the server connection preface. It is important to note, however, that the server - connection preface SETTINGS frame might include parameters that necessarily - alter how a client is expected to communicate with the server. Upon receiving the - SETTINGS frame, the client is expected to honor any parameters established. - In some configurations, it is possible for the server to transmit SETTINGS - before the client sends additional frames, providing an opportunity to avoid this issue. - - - Clients and servers MUST treat an invalid connection preface as a connection error of type - PROTOCOL_ERROR. A GOAWAY frame () - MAY be omitted in this case, since an invalid preface indicates that the peer is not using - HTTP/2. - -
-
- -
- - Once the HTTP/2 connection is established, endpoints can begin exchanging frames. - - -
- - All frames begin with a fixed 9-octet header followed by a variable-length payload. - -
- -
- - The fields of the frame header are defined as: - - - - The length of the frame payload expressed as an unsigned 24-bit integer. Values - greater than 214 (16,384) MUST NOT be sent unless the receiver has - set a larger value for SETTINGS_MAX_FRAME_SIZE. - - - The 9 octets of the frame header are not included in this value. - - - - - The 8-bit type of the frame. The frame type determines the format and semantics of - the frame. Implementations MUST ignore and discard any frame that has a type that - is unknown. - - - - - An 8-bit field reserved for frame-type specific boolean flags. - - - Flags are assigned semantics specific to the indicated frame type. Flags that have - no defined semantics for a particular frame type MUST be ignored, and MUST be left - unset (0) when sending. - - - - - A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST - remain unset (0) when sending and MUST be ignored when receiving. - - - - - A 31-bit stream identifier (see ). The value 0 is - reserved for frames that are associated with the connection as a whole as opposed to - an individual stream. - - - - - - The structure and content of the frame payload is dependent entirely on the frame type. - -
- -
- - The size of a frame payload is limited by the maximum size that a receiver advertises in - the SETTINGS_MAX_FRAME_SIZE setting. This setting can have any value - between 214 (16,384) and 224-1 (16,777,215) octets, - inclusive. - - - All implementations MUST be capable of receiving and minimally processing frames up to - 214 octets in length, plus the 9 octet frame - header. The size of the frame header is not included when describing frame sizes. - - - Certain frame types, such as PING, impose additional limits - on the amount of payload data allowed. - - - - - If a frame size exceeds any defined limit, or is too small to contain mandatory frame - data, the endpoint MUST send a FRAME_SIZE_ERROR error. A frame size error - in a frame that could alter the state of the entire connection MUST be treated as a connection error; this includes any frame carrying - a header block (that is, HEADERS, - PUSH_PROMISE, and CONTINUATION), SETTINGS, - and any WINDOW_UPDATE frame with a stream identifier of 0. - - - Endpoints are not obligated to use all available space in a frame. Responsiveness can be - improved by using frames that are smaller than the permitted maximum size. Sending large - frames can result in delays in sending time-sensitive frames (such - RST_STREAM, WINDOW_UPDATE, or PRIORITY) - which if blocked by the transmission of a large frame, could affect performance. - -
- -
- - Just as in HTTP/1, a header field in HTTP/2 is a name with one or more associated values. - They are used within HTTP request and response messages as well as server push operations - (see ). - - - Header lists are collections of zero or more header fields. When transmitted over a - connection, a header list is serialized into a header block using HTTP Header Compression. The serialized header block is then - divided into one or more octet sequences, called header block fragments, and transmitted - within the payload of HEADERS, PUSH_PROMISE or CONTINUATION frames. - - - The Cookie header field is treated specially by the HTTP - mapping (see ). - - - A receiving endpoint reassembles the header block by concatenating its fragments, then - decompresses the block to reconstruct the header list. - - - A complete header block consists of either: - - - a single HEADERS or PUSH_PROMISE frame, - with the END_HEADERS flag set, or - - - a HEADERS or PUSH_PROMISE frame with the END_HEADERS - flag cleared and one or more CONTINUATION frames, - where the last CONTINUATION frame has the END_HEADERS flag set. - - - - - Header compression is stateful. One compression context and one decompression context is - used for the entire connection. Each header block is processed as a discrete unit. - Header blocks MUST be transmitted as a contiguous sequence of frames, with no interleaved - frames of any other type or from any other stream. The last frame in a sequence of - HEADERS or CONTINUATION frames MUST have the END_HEADERS - flag set. The last frame in a sequence of PUSH_PROMISE or - CONTINUATION frames MUST have the END_HEADERS flag set. This allows a - header block to be logically equivalent to a single frame. - - - Header block fragments can only be sent as the payload of HEADERS, - PUSH_PROMISE or CONTINUATION frames, because these frames - carry data that can modify the compression context maintained by a receiver. An endpoint - receiving HEADERS, PUSH_PROMISE or - CONTINUATION frames MUST reassemble header blocks and perform decompression - even if the frames are to be discarded. A receiver MUST terminate the connection with a - connection error of type - COMPRESSION_ERROR if it does not decompress a header block. - -
-
- -
- - A "stream" is an independent, bi-directional sequence of frames exchanged between the client - and server within an HTTP/2 connection. Streams have several important characteristics: - - - A single HTTP/2 connection can contain multiple concurrently open streams, with either - endpoint interleaving frames from multiple streams. - - - Streams can be established and used unilaterally or shared by either the client or - server. - - - Streams can be closed by either endpoint. - - - The order in which frames are sent on a stream is significant. Recipients process frames - in the order they are received. In particular, the order of HEADERS, - and DATA frames is semantically significant. - - - Streams are identified by an integer. Stream identifiers are assigned to streams by the - endpoint initiating the stream. - - - - -
- - The lifecycle of a stream is shown in . - - -
- - | |<-----------' | - | R | closed | R | - `-------------------->| |<--------------------' - +--------+ - - H: HEADERS frame (with implied CONTINUATIONs) - PP: PUSH_PROMISE frame (with implied CONTINUATIONs) - ES: END_STREAM flag - R: RST_STREAM frame -]]> - -
- - - Note that this diagram shows stream state transitions and the frames and flags that affect - those transitions only. In this regard, CONTINUATION frames do not result - in state transitions; they are effectively part of the HEADERS or - PUSH_PROMISE that they follow. For this purpose, the END_STREAM flag is - processed as a separate event to the frame that bears it; a HEADERS frame - with the END_STREAM flag set can cause two state transitions. - - - Both endpoints have a subjective view of the state of a stream that could be different - when frames are in transit. Endpoints do not coordinate the creation of streams; they are - created unilaterally by either endpoint. The negative consequences of a mismatch in - states are limited to the "closed" state after sending RST_STREAM, where - frames might be received for some time after closing. - - - Streams have the following states: - - - - - - All streams start in the "idle" state. In this state, no frames have been - exchanged. - - - The following transitions are valid from this state: - - - Sending or receiving a HEADERS frame causes the stream to become - "open". The stream identifier is selected as described in . The same HEADERS frame can also - cause a stream to immediately become "half closed". - - - Sending a PUSH_PROMISE frame marks the associated stream for - later use. The stream state for the reserved stream transitions to "reserved - (local)". - - - Receiving a PUSH_PROMISE frame marks the associated stream as - reserved by the remote peer. The state of the stream becomes "reserved - (remote)". - - - - - Receiving any frames other than HEADERS or - PUSH_PROMISE on a stream in this state MUST be treated as a connection error of type - PROTOCOL_ERROR. - - - - - - - A stream in the "reserved (local)" state is one that has been promised by sending a - PUSH_PROMISE frame. A PUSH_PROMISE frame reserves an - idle stream by associating the stream with an open stream that was initiated by the - remote peer (see ). - - - In this state, only the following transitions are possible: - - - The endpoint can send a HEADERS frame. This causes the stream to - open in a "half closed (remote)" state. - - - Either endpoint can send a RST_STREAM frame to cause the stream - to become "closed". This releases the stream reservation. - - - - - An endpoint MUST NOT send any type of frame other than HEADERS or - RST_STREAM in this state. - - - A PRIORITY frame MAY be received in this state. Receiving any type - of frame other than RST_STREAM or PRIORITY on a stream - in this state MUST be treated as a connection - error of type PROTOCOL_ERROR. - - - - - - - A stream in the "reserved (remote)" state has been reserved by a remote peer. - - - In this state, only the following transitions are possible: - - - Receiving a HEADERS frame causes the stream to transition to - "half closed (local)". - - - Either endpoint can send a RST_STREAM frame to cause the stream - to become "closed". This releases the stream reservation. - - - - - An endpoint MAY send a PRIORITY frame in this state to reprioritize - the reserved stream. An endpoint MUST NOT send any type of frame other than - RST_STREAM, WINDOW_UPDATE, or PRIORITY - in this state. - - - Receiving any type of frame other than HEADERS or - RST_STREAM on a stream in this state MUST be treated as a connection error of type - PROTOCOL_ERROR. - - - - - - - A stream in the "open" state may be used by both peers to send frames of any type. - In this state, sending peers observe advertised stream - level flow control limits. - - - From this state either endpoint can send a frame with an END_STREAM flag set, which - causes the stream to transition into one of the "half closed" states: an endpoint - sending an END_STREAM flag causes the stream state to become "half closed (local)"; - an endpoint receiving an END_STREAM flag causes the stream state to become "half - closed (remote)". - - - Either endpoint can send a RST_STREAM frame from this state, causing - it to transition immediately to "closed". - - - - - - - A stream that is in the "half closed (local)" state cannot be used for sending - frames. Only WINDOW_UPDATE, PRIORITY and - RST_STREAM frames can be sent in this state. - - - A stream transitions from this state to "closed" when a frame that contains an - END_STREAM flag is received, or when either peer sends a RST_STREAM - frame. - - - A receiver can ignore WINDOW_UPDATE frames in this state, which might - arrive for a short period after a frame bearing the END_STREAM flag is sent. - - - PRIORITY frames received in this state are used to reprioritize - streams that depend on the current stream. - - - - - - - A stream that is "half closed (remote)" is no longer being used by the peer to send - frames. In this state, an endpoint is no longer obligated to maintain a receiver - flow control window if it performs flow control. - - - If an endpoint receives additional frames for a stream that is in this state, other - than WINDOW_UPDATE, PRIORITY or - RST_STREAM, it MUST respond with a stream error of type - STREAM_CLOSED. - - - A stream that is "half closed (remote)" can be used by the endpoint to send frames - of any type. In this state, the endpoint continues to observe advertised stream level flow control limits. - - - A stream can transition from this state to "closed" by sending a frame that contains - an END_STREAM flag, or when either peer sends a RST_STREAM frame. - - - - - - - The "closed" state is the terminal state. - - - An endpoint MUST NOT send frames other than PRIORITY on a closed - stream. An endpoint that receives any frame other than PRIORITY - after receiving a RST_STREAM MUST treat that as a stream error of type - STREAM_CLOSED. Similarly, an endpoint that receives any frames after - receiving a frame with the END_STREAM flag set MUST treat that as a connection error of type - STREAM_CLOSED, unless the frame is permitted as described below. - - - WINDOW_UPDATE or RST_STREAM frames can be received in - this state for a short period after a DATA or HEADERS - frame containing an END_STREAM flag is sent. Until the remote peer receives and - processes RST_STREAM or the frame bearing the END_STREAM flag, it - might send frames of these types. Endpoints MUST ignore - WINDOW_UPDATE or RST_STREAM frames received in this - state, though endpoints MAY choose to treat frames that arrive a significant time - after sending END_STREAM as a connection - error of type PROTOCOL_ERROR. - - - PRIORITY frames can be sent on closed streams to prioritize streams - that are dependent on the closed stream. Endpoints SHOULD process - PRIORITY frame, though they can be ignored if the stream has been - removed from the dependency tree (see ). - - - If this state is reached as a result of sending a RST_STREAM frame, - the peer that receives the RST_STREAM might have already sent - or - enqueued for sending - frames on the stream that cannot be withdrawn. An endpoint - MUST ignore frames that it receives on closed streams after it has sent a - RST_STREAM frame. An endpoint MAY choose to limit the period over - which it ignores frames and treat frames that arrive after this time as being in - error. - - - Flow controlled frames (i.e., DATA) received after sending - RST_STREAM are counted toward the connection flow control window. - Even though these frames might be ignored, because they are sent before the sender - receives the RST_STREAM, the sender will consider the frames to count - against the flow control window. - - - An endpoint might receive a PUSH_PROMISE frame after it sends - RST_STREAM. PUSH_PROMISE causes a stream to become - "reserved" even if the associated stream has been reset. Therefore, a - RST_STREAM is needed to close an unwanted promised stream. - - - - - - In the absence of more specific guidance elsewhere in this document, implementations - SHOULD treat the receipt of a frame that is not expressly permitted in the description of - a state as a connection error of type - PROTOCOL_ERROR. Frame of unknown types are ignored. - - - An example of the state transitions for an HTTP request/response exchange can be found in - . An example of the state transitions for server push can be - found in and . - - -
- - Streams are identified with an unsigned 31-bit integer. Streams initiated by a client - MUST use odd-numbered stream identifiers; those initiated by the server MUST use - even-numbered stream identifiers. A stream identifier of zero (0x0) is used for - connection control messages; the stream identifier zero cannot be used to establish a - new stream. - - - HTTP/1.1 requests that are upgraded to HTTP/2 (see ) are - responded to with a stream identifier of one (0x1). After the upgrade - completes, stream 0x1 is "half closed (local)" to the client. Therefore, stream 0x1 - cannot be selected as a new stream identifier by a client that upgrades from HTTP/1.1. - - - The identifier of a newly established stream MUST be numerically greater than all - streams that the initiating endpoint has opened or reserved. This governs streams that - are opened using a HEADERS frame and streams that are reserved using - PUSH_PROMISE. An endpoint that receives an unexpected stream identifier - MUST respond with a connection error of - type PROTOCOL_ERROR. - - - The first use of a new stream identifier implicitly closes all streams in the "idle" - state that might have been initiated by that peer with a lower-valued stream identifier. - For example, if a client sends a HEADERS frame on stream 7 without ever - sending a frame on stream 5, then stream 5 transitions to the "closed" state when the - first frame for stream 7 is sent or received. - - - Stream identifiers cannot be reused. Long-lived connections can result in an endpoint - exhausting the available range of stream identifiers. A client that is unable to - establish a new stream identifier can establish a new connection for new streams. A - server that is unable to establish a new stream identifier can send a - GOAWAY frame so that the client is forced to open a new connection for - new streams. - -
- -
- - A peer can limit the number of concurrently active streams using the - SETTINGS_MAX_CONCURRENT_STREAMS parameter (see ) within a SETTINGS frame. The maximum concurrent - streams setting is specific to each endpoint and applies only to the peer that receives - the setting. That is, clients specify the maximum number of concurrent streams the - server can initiate, and servers specify the maximum number of concurrent streams the - client can initiate. - - - Streams that are in the "open" state, or either of the "half closed" states count toward - the maximum number of streams that an endpoint is permitted to open. Streams in any of - these three states count toward the limit advertised in the - SETTINGS_MAX_CONCURRENT_STREAMS setting. Streams in either of the - "reserved" states do not count toward the stream limit. - - - Endpoints MUST NOT exceed the limit set by their peer. An endpoint that receives a - HEADERS frame that causes their advertised concurrent stream limit to be - exceeded MUST treat this as a stream error. An - endpoint that wishes to reduce the value of - SETTINGS_MAX_CONCURRENT_STREAMS to a value that is below the current - number of open streams can either close streams that exceed the new value or allow - streams to complete. - -
-
- -
- - Using streams for multiplexing introduces contention over use of the TCP connection, - resulting in blocked streams. A flow control scheme ensures that streams on the same - connection do not destructively interfere with each other. Flow control is used for both - individual streams and for the connection as a whole. - - - HTTP/2 provides for flow control through use of the WINDOW_UPDATE frame. - - -
- - HTTP/2 stream flow control aims to allow a variety of flow control algorithms to be - used without requiring protocol changes. Flow control in HTTP/2 has the following - characteristics: - - - Flow control is specific to a connection; i.e., it is "hop-by-hop", not - "end-to-end". - - - Flow control is based on window update frames. Receivers advertise how many octets - they are prepared to receive on a stream and for the entire connection. This is a - credit-based scheme. - - - Flow control is directional with overall control provided by the receiver. A - receiver MAY choose to set any window size that it desires for each stream and for - the entire connection. A sender MUST respect flow control limits imposed by a - receiver. Clients, servers and intermediaries all independently advertise their - flow control window as a receiver and abide by the flow control limits set by - their peer when sending. - - - The initial value for the flow control window is 65,535 octets for both new streams - and the overall connection. - - - The frame type determines whether flow control applies to a frame. Of the frames - specified in this document, only DATA frames are subject to flow - control; all other frame types do not consume space in the advertised flow control - window. This ensures that important control frames are not blocked by flow control. - - - Flow control cannot be disabled. - - - HTTP/2 defines only the format and semantics of the WINDOW_UPDATE - frame (). This document does not stipulate how a - receiver decides when to send this frame or the value that it sends, nor does it - specify how a sender chooses to send packets. Implementations are able to select - any algorithm that suits their needs. - - - - - Implementations are also responsible for managing how requests and responses are sent - based on priority; choosing how to avoid head of line blocking for requests; and - managing the creation of new streams. Algorithm choices for these could interact with - any flow control algorithm. - -
- -
- - Flow control is defined to protect endpoints that are operating under resource - constraints. For example, a proxy needs to share memory between many connections, and - also might have a slow upstream connection and a fast downstream one. Flow control - addresses cases where the receiver is unable process data on one stream, yet wants to - continue to process other streams in the same connection. - - - Deployments that do not require this capability can advertise a flow control window of - the maximum size, incrementing the available space when new data is received. This - effectively disables flow control for that receiver. Conversely, a sender is always - subject to the flow control window advertised by the receiver. - - - Deployments with constrained resources (for example, memory) can employ flow control to - limit the amount of memory a peer can consume. Note, however, that this can lead to - suboptimal use of available network resources if flow control is enabled without - knowledge of the bandwidth-delay product (see ). - - - Even with full awareness of the current bandwidth-delay product, implementation of flow - control can be difficult. When using flow control, the receiver MUST read from the TCP - receive buffer in a timely fashion. Failure to do so could lead to a deadlock when - critical frames, such as WINDOW_UPDATE, are not read and acted upon. - -
-
- -
- - A client can assign a priority for a new stream by including prioritization information in - the HEADERS frame that opens the stream. For an existing - stream, the PRIORITY frame can be used to change the - priority. - - - The purpose of prioritization is to allow an endpoint to express how it would prefer its - peer allocate resources when managing concurrent streams. Most importantly, priority can - be used to select streams for transmitting frames when there is limited capacity for - sending. - - - Streams can be prioritized by marking them as dependent on the completion of other streams - (). Each dependency is assigned a relative weight, a number - that is used to determine the relative proportion of available resources that are assigned - to streams dependent on the same stream. - - - - Explicitly setting the priority for a stream is input to a prioritization process. It - does not guarantee any particular processing or transmission order for the stream relative - to any other stream. An endpoint cannot force a peer to process concurrent streams in a - particular order using priority. Expressing priority is therefore only ever a suggestion. - - - Providing prioritization information is optional, so default values are used if no - explicit indicator is provided (). - - -
- - Each stream can be given an explicit dependency on another stream. Including a - dependency expresses a preference to allocate resources to the identified stream rather - than to the dependent stream. - - - A stream that is not dependent on any other stream is given a stream dependency of 0x0. - In other words, the non-existent stream 0 forms the root of the tree. - - - A stream that depends on another stream is a dependent stream. The stream upon which a - stream is dependent is a parent stream. A dependency on a stream that is not currently - in the tree - such as a stream in the "idle" state - results in that stream being given - a default priority. - - - When assigning a dependency on another stream, the stream is added as a new dependency - of the parent stream. Dependent streams that share the same parent are not ordered with - respect to each other. For example, if streams B and C are dependent on stream A, and - if stream D is created with a dependency on stream A, this results in a dependency order - of A followed by B, C, and D in any order. - -
- /|\ - B C B D C -]]> -
- - An exclusive flag allows for the insertion of a new level of dependencies. The - exclusive flag causes the stream to become the sole dependency of its parent stream, - causing other dependencies to become dependent on the exclusive stream. In the - previous example, if stream D is created with an exclusive dependency on stream A, this - results in D becoming the dependency parent of B and C. - -
- D - B C / \ - B C -]]> -
- - Inside the dependency tree, a dependent stream SHOULD only be allocated resources if all - of the streams that it depends on (the chain of parent streams up to 0x0) are either - closed, or it is not possible to make progress on them. - - - A stream cannot depend on itself. An endpoint MUST treat this as a stream error of type PROTOCOL_ERROR. - -
- -
- - All dependent streams are allocated an integer weight between 1 and 256 (inclusive). - - - Streams with the same parent SHOULD be allocated resources proportionally based on their - weight. Thus, if stream B depends on stream A with weight 4, and C depends on stream A - with weight 12, and if no progress can be made on A, stream B ideally receives one third - of the resources allocated to stream C. - -
- -
- - Stream priorities are changed using the PRIORITY frame. Setting a - dependency causes a stream to become dependent on the identified parent stream. - - - Dependent streams move with their parent stream if the parent is reprioritized. Setting - a dependency with the exclusive flag for a reprioritized stream moves all the - dependencies of the new parent stream to become dependent on the reprioritized stream. - - - If a stream is made dependent on one of its own dependencies, the formerly dependent - stream is first moved to be dependent on the reprioritized stream's previous parent. - The moved dependency retains its weight. - -
- - For example, consider an original dependency tree where B and C depend on A, D and E - depend on C, and F depends on D. If A is made dependent on D, then D takes the place - of A. All other dependency relationships stay the same, except for F, which becomes - dependent on A if the reprioritization is exclusive. - - F B C ==> F A OR A - / \ | / \ /|\ - D E E B C B C F - | | | - F E E - (intermediate) (non-exclusive) (exclusive) -]]> -
-
- -
- - When a stream is removed from the dependency tree, its dependencies can be moved to - become dependent on the parent of the closed stream. The weights of new dependencies - are recalculated by distributing the weight of the dependency of the closed stream - proportionally based on the weights of its dependencies. - - - Streams that are removed from the dependency tree cause some prioritization information - to be lost. Resources are shared between streams with the same parent stream, which - means that if a stream in that set closes or becomes blocked, any spare capacity - allocated to a stream is distributed to the immediate neighbors of the stream. However, - if the common dependency is removed from the tree, those streams share resources with - streams at the next highest level. - - - For example, assume streams A and B share a parent, and streams C and D both depend on - stream A. Prior to the removal of stream A, if streams A and D are unable to proceed, - then stream C receives all the resources dedicated to stream A. If stream A is removed - from the tree, the weight of stream A is divided between streams C and D. If stream D - is still unable to proceed, this results in stream C receiving a reduced proportion of - resources. For equal starting weights, C receives one third, rather than one half, of - available resources. - - - It is possible for a stream to become closed while prioritization information that - creates a dependency on that stream is in transit. If a stream identified in a - dependency has no associated priority information, then the dependent stream is instead - assigned a default priority. This potentially creates - suboptimal prioritization, since the stream could be given a priority that is different - to what is intended. - - - To avoid these problems, an endpoint SHOULD retain stream prioritization state for a - period after streams become closed. The longer state is retained, the lower the chance - that streams are assigned incorrect or default priority values. - - - This could create a large state burden for an endpoint, so this state MAY be limited. - An endpoint MAY apply a fixed upper limit on the number of closed streams for which - prioritization state is tracked to limit state exposure. The amount of additional state - an endpoint maintains could be dependent on load; under high load, prioritization state - can be discarded to limit resource commitments. In extreme cases, an endpoint could - even discard prioritization state for active or reserved streams. If a fixed limit is - applied, endpoints SHOULD maintain state for at least as many streams as allowed by - their setting for SETTINGS_MAX_CONCURRENT_STREAMS. - - - An endpoint receiving a PRIORITY frame that changes the priority of a - closed stream SHOULD alter the dependencies of the streams that depend on it, if it has - retained enough state to do so. - -
- -
- - Providing priority information is optional. Streams are assigned a non-exclusive - dependency on stream 0x0 by default. Pushed streams - initially depend on their associated stream. In both cases, streams are assigned a - default weight of 16. - -
-
- -
- - HTTP/2 framing permits two classes of error: - - - An error condition that renders the entire connection unusable is a connection error. - - - An error in an individual stream is a stream error. - - - - - A list of error codes is included in . - - -
- - A connection error is any error which prevents further processing of the framing layer, - or which corrupts any connection state. - - - An endpoint that encounters a connection error SHOULD first send a GOAWAY - frame () with the stream identifier of the last stream that it - successfully received from its peer. The GOAWAY frame includes an error - code that indicates why the connection is terminating. After sending the - GOAWAY frame, the endpoint MUST close the TCP connection. - - - It is possible that the GOAWAY will not be reliably received by the - receiving endpoint (see ). In the event of a connection error, - GOAWAY only provides a best effort attempt to communicate with the peer - about why the connection is being terminated. - - - An endpoint can end a connection at any time. In particular, an endpoint MAY choose to - treat a stream error as a connection error. Endpoints SHOULD send a - GOAWAY frame when ending a connection, providing that circumstances - permit it. - -
- -
- - A stream error is an error related to a specific stream that does not affect processing - of other streams. - - - An endpoint that detects a stream error sends a RST_STREAM frame () that contains the stream identifier of the stream where the error - occurred. The RST_STREAM frame includes an error code that indicates the - type of error. - - - A RST_STREAM is the last frame that an endpoint can send on a stream. - The peer that sends the RST_STREAM frame MUST be prepared to receive any - frames that were sent or enqueued for sending by the remote peer. These frames can be - ignored, except where they modify connection state (such as the state maintained for - header compression, or flow control). - - - Normally, an endpoint SHOULD NOT send more than one RST_STREAM frame for - any stream. However, an endpoint MAY send additional RST_STREAM frames if - it receives frames on a closed stream after more than a round-trip time. This behavior - is permitted to deal with misbehaving implementations. - - - An endpoint MUST NOT send a RST_STREAM in response to an - RST_STREAM frame, to avoid looping. - -
- -
- - If the TCP connection is closed or reset while streams remain in open or half closed - states, then the endpoint MUST assume that those streams were abnormally interrupted and - could be incomplete. - -
-
- -
- - HTTP/2 permits extension of the protocol. Protocol extensions can be used to provide - additional services or alter any aspect of the protocol, within the limitations described - in this section. Extensions are effective only within the scope of a single HTTP/2 - connection. - - - Extensions are permitted to use new frame types, new - settings, or new error - codes. Registries are established for managing these extension points: frame types, settings and - error codes. - - - Implementations MUST ignore unknown or unsupported values in all extensible protocol - elements. Implementations MUST discard frames that have unknown or unsupported types. - This means that any of these extension points can be safely used by extensions without - prior arrangement or negotiation. However, extension frames that appear in the middle of - a header block are not permitted; these MUST be treated - as a connection error of type - PROTOCOL_ERROR. - - - However, extensions that could change the semantics of existing protocol components MUST - be negotiated before being used. For example, an extension that changes the layout of the - HEADERS frame cannot be used until the peer has given a positive signal - that this is acceptable. In this case, it could also be necessary to coordinate when the - revised layout comes into effect. Note that treating any frame other than - DATA frames as flow controlled is such a change in semantics, and can only - be done through negotiation. - - - This document doesn't mandate a specific method for negotiating the use of an extension, - but notes that a setting could be used for that - purpose. If both peers set a value that indicates willingness to use the extension, then - the extension can be used. If a setting is used for extension negotiation, the initial - value MUST be defined so that the extension is initially disabled. - -
-
- -
- - This specification defines a number of frame types, each identified by a unique 8-bit type - code. Each frame type serves a distinct purpose either in the establishment and management - of the connection as a whole, or of individual streams. - - - The transmission of specific frame types can alter the state of a connection. If endpoints - fail to maintain a synchronized view of the connection state, successful communication - within the connection will no longer be possible. Therefore, it is important that endpoints - have a shared comprehension of how the state is affected by the use any given frame. - - -
- - DATA frames (type=0x0) convey arbitrary, variable-length sequences of octets associated - with a stream. One or more DATA frames are used, for instance, to carry HTTP request or - response payloads. - - - DATA frames MAY also contain arbitrary padding. Padding can be added to DATA frames to - obscure the size of messages. - -
- -
- - The DATA frame contains the following fields: - - - An 8-bit field containing the length of the frame padding in units of octets. This - field is optional and is only present if the PADDED flag is set. - - - Application data. The amount of data is the remainder of the frame payload after - subtracting the length of the other fields that are present. - - - Padding octets that contain no application semantic value. Padding octets MUST be set - to zero when sending and ignored when receiving. - - - - - - The DATA frame defines the following flags: - - - Bit 1 being set indicates that this frame is the last that the endpoint will send for - the identified stream. Setting this flag causes the stream to enter one of the "half closed" states or the "closed" state. - - - Bit 4 being set indicates that the Pad Length field and any padding that it describes - is present. - - - - - DATA frames MUST be associated with a stream. If a DATA frame is received whose stream - identifier field is 0x0, the recipient MUST respond with a connection error of type - PROTOCOL_ERROR. - - - DATA frames are subject to flow control and can only be sent when a stream is in the - "open" or "half closed (remote)" states. The entire DATA frame payload is included in flow - control, including Pad Length and Padding fields if present. If a DATA frame is received - whose stream is not in "open" or "half closed (local)" state, the recipient MUST respond - with a stream error of type - STREAM_CLOSED. - - - The total number of padding octets is determined by the value of the Pad Length field. If - the length of the padding is greater than the length of the frame payload, the recipient - MUST treat this as a connection error of - type PROTOCOL_ERROR. - - - A frame can be increased in size by one octet by including a Pad Length field with a - value of zero. - - - - - Padding is a security feature; see . - -
- -
- - The HEADERS frame (type=0x1) is used to open a stream, - and additionally carries a header block fragment. HEADERS frames can be sent on a stream - in the "open" or "half closed (remote)" states. - -
- -
- - The HEADERS frame payload has the following fields: - - - An 8-bit field containing the length of the frame padding in units of octets. This - field is only present if the PADDED flag is set. - - - A single bit flag indicates that the stream dependency is exclusive, see . This field is only present if the PRIORITY flag is set. - - - A 31-bit stream identifier for the stream that this stream depends on, see . This field is only present if the PRIORITY flag is set. - - - An 8-bit weight for the stream, see . Add one to the - value to obtain a weight between 1 and 256. This field is only present if the - PRIORITY flag is set. - - - A header block fragment. - - - Padding octets that contain no application semantic value. Padding octets MUST be set - to zero when sending and ignored when receiving. - - - - - - The HEADERS frame defines the following flags: - - - - Bit 1 being set indicates that the header block is - the last that the endpoint will send for the identified stream. Setting this flag - causes the stream to enter one of "half closed" - states. - - - A HEADERS frame carries the END_STREAM flag that signals the end of a stream. - However, a HEADERS frame with the END_STREAM flag set can be followed by - CONTINUATION frames on the same stream. Logically, the - CONTINUATION frames are part of the HEADERS frame. - - - - - Bit 3 being set indicates that this frame contains an entire header block and is not followed by any - CONTINUATION frames. - - - A HEADERS frame without the END_HEADERS flag set MUST be followed by a - CONTINUATION frame for the same stream. A receiver MUST treat the - receipt of any other type of frame or a frame on a different stream as a connection error of type - PROTOCOL_ERROR. - - - - - Bit 4 being set indicates that the Pad Length field and any padding that it - describes is present. - - - - - Bit 6 being set indicates that the Exclusive Flag (E), Stream Dependency, and Weight - fields are present; see . - - - - - - - The payload of a HEADERS frame contains a header block - fragment. A header block that does not fit within a HEADERS frame is continued in - a CONTINUATION frame. - - - - HEADERS frames MUST be associated with a stream. If a HEADERS frame is received whose - stream identifier field is 0x0, the recipient MUST respond with a connection error of type - PROTOCOL_ERROR. - - - - The HEADERS frame changes the connection state as described in . - - - - The HEADERS frame includes optional padding. Padding fields and flags are identical to - those defined for DATA frames. - - - Prioritization information in a HEADERS frame is logically equivalent to a separate - PRIORITY frame, but inclusion in HEADERS avoids the potential for churn in - stream prioritization when new streams are created. Priorization fields in HEADERS frames - subsequent to the first on a stream reprioritize the - stream. - -
- -
- - The PRIORITY frame (type=0x2) specifies the sender-advised - priority of a stream. It can be sent at any time for an existing stream, including - closed streams. This enables reprioritization of existing streams. - -
- -
- - The payload of a PRIORITY frame contains the following fields: - - - A single bit flag indicates that the stream dependency is exclusive, see . - - - A 31-bit stream identifier for the stream that this stream depends on, see . - - - An 8-bit weight for the identified stream dependency, see . Add one to the value to obtain a weight between 1 and 256. - - - - - - The PRIORITY frame does not define any flags. - - - - The PRIORITY frame is associated with an existing stream. If a PRIORITY frame is received - with a stream identifier of 0x0, the recipient MUST respond with a connection error of type - PROTOCOL_ERROR. - - - The PRIORITY frame can be sent on a stream in any of the "reserved (remote)", "open", - "half closed (local)", "half closed (remote)", or "closed" states, though it cannot be - sent between consecutive frames that comprise a single header - block. Note that this frame could arrive after processing or frame sending has - completed, which would cause it to have no effect on the current stream. For a stream - that is in the "half closed (remote)" or "closed" - state, this frame can only affect - processing of the current stream and not frame transmission. - - - The PRIORITY frame is the only frame that can be sent for a stream in the "closed" state. - This allows for the reprioritization of a group of dependent streams by altering the - priority of a parent stream, which might be closed. However, a PRIORITY frame sent on a - closed stream risks being ignored due to the peer having discarded priority state - information for that stream. - -
- -
- - The RST_STREAM frame (type=0x3) allows for abnormal termination of a stream. When sent by - the initiator of a stream, it indicates that they wish to cancel the stream or that an - error condition has occurred. When sent by the receiver of a stream, it indicates that - either the receiver is rejecting the stream, requesting that the stream be cancelled, or - that an error condition has occurred. - -
- -
- - - The RST_STREAM frame contains a single unsigned, 32-bit integer identifying the error code. The error code indicates why the stream is being - terminated. - - - - The RST_STREAM frame does not define any flags. - - - - The RST_STREAM frame fully terminates the referenced stream and causes it to enter the - closed state. After receiving a RST_STREAM on a stream, the receiver MUST NOT send - additional frames for that stream, with the exception of PRIORITY. However, - after sending the RST_STREAM, the sending endpoint MUST be prepared to receive and process - additional frames sent on the stream that might have been sent by the peer prior to the - arrival of the RST_STREAM. - - - - RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame is received - with a stream identifier of 0x0, the recipient MUST treat this as a connection error of type - PROTOCOL_ERROR. - - - - RST_STREAM frames MUST NOT be sent for a stream in the "idle" state. If a RST_STREAM - frame identifying an idle stream is received, the recipient MUST treat this as a connection error of type - PROTOCOL_ERROR. - - -
- -
- - The SETTINGS frame (type=0x4) conveys configuration parameters that affect how endpoints - communicate, such as preferences and constraints on peer behavior. The SETTINGS frame is - also used to acknowledge the receipt of those parameters. Individually, a SETTINGS - parameter can also be referred to as a "setting". - - - SETTINGS parameters are not negotiated; they describe characteristics of the sending peer, - which are used by the receiving peer. Different values for the same parameter can be - advertised by each peer. For example, a client might set a high initial flow control - window, whereas a server might set a lower value to conserve resources. - - - - A SETTINGS frame MUST be sent by both endpoints at the start of a connection, and MAY be - sent at any other time by either endpoint over the lifetime of the connection. - Implementations MUST support all of the parameters defined by this specification. - - - - Each parameter in a SETTINGS frame replaces any existing value for that parameter. - Parameters are processed in the order in which they appear, and a receiver of a SETTINGS - frame does not need to maintain any state other than the current value of its - parameters. Therefore, the value of a SETTINGS parameter is the last value that is seen by - a receiver. - - - SETTINGS parameters are acknowledged by the receiving peer. To enable this, the SETTINGS - frame defines the following flag: - - - Bit 1 being set indicates that this frame acknowledges receipt and application of the - peer's SETTINGS frame. When this bit is set, the payload of the SETTINGS frame MUST - be empty. Receipt of a SETTINGS frame with the ACK flag set and a length field value - other than 0 MUST be treated as a connection - error of type FRAME_SIZE_ERROR. For more info, see Settings Synchronization. - - - - - SETTINGS frames always apply to a connection, never a single stream. The stream - identifier for a SETTINGS frame MUST be zero (0x0). If an endpoint receives a SETTINGS - frame whose stream identifier field is anything other than 0x0, the endpoint MUST respond - with a connection error of type - PROTOCOL_ERROR. - - - The SETTINGS frame affects connection state. A badly formed or incomplete SETTINGS frame - MUST be treated as a connection error of type - PROTOCOL_ERROR. - - -
- - The payload of a SETTINGS frame consists of zero or more parameters, each consisting of - an unsigned 16-bit setting identifier and an unsigned 32-bit value. - - -
- -
-
- -
- - The following parameters are defined: - - - - Allows the sender to inform the remote endpoint of the maximum size of the header - compression table used to decode header blocks, in octets. The encoder can select - any size equal to or less than this value by using signaling specific to the - header compression format inside a header block. The initial value is 4,096 - octets. - - - - - This setting can be use to disable server - push. An endpoint MUST NOT send a PUSH_PROMISE frame if it - receives this parameter set to a value of 0. An endpoint that has both set this - parameter to 0 and had it acknowledged MUST treat the receipt of a - PUSH_PROMISE frame as a connection error of type - PROTOCOL_ERROR. - - - The initial value is 1, which indicates that server push is permitted. Any value - other than 0 or 1 MUST be treated as a connection error of type - PROTOCOL_ERROR. - - - - - Indicates the maximum number of concurrent streams that the sender will allow. - This limit is directional: it applies to the number of streams that the sender - permits the receiver to create. Initially there is no limit to this value. It is - recommended that this value be no smaller than 100, so as to not unnecessarily - limit parallelism. - - - A value of 0 for SETTINGS_MAX_CONCURRENT_STREAMS SHOULD NOT be treated as special - by endpoints. A zero value does prevent the creation of new streams, however this - can also happen for any limit that is exhausted with active streams. Servers - SHOULD only set a zero value for short durations; if a server does not wish to - accept requests, closing the connection could be preferable. - - - - - Indicates the sender's initial window size (in octets) for stream level flow - control. The initial value is 216-1 (65,535) octets. - - - This setting affects the window size of all streams, including existing streams, - see . - - - Values above the maximum flow control window size of 231-1 MUST - be treated as a connection error of - type FLOW_CONTROL_ERROR. - - - - - Indicates the size of the largest frame payload that the sender is willing to - receive, in octets. - - - The initial value is 214 (16,384) octets. The value advertised by - an endpoint MUST be between this initial value and the maximum allowed frame size - (224-1 or 16,777,215 octets), inclusive. Values outside this range - MUST be treated as a connection error - of type PROTOCOL_ERROR. - - - - - This advisory setting informs a peer of the maximum size of header list that the - sender is prepared to accept, in octets. The value is based on the uncompressed - size of header fields, including the length of the name and value in octets plus - an overhead of 32 octets for each header field. - - - For any given request, a lower limit than what is advertised MAY be enforced. The - initial value of this setting is unlimited. - - - - - - An endpoint that receives a SETTINGS frame with any unknown or unsupported identifier - MUST ignore that setting. - -
- -
- - Most values in SETTINGS benefit from or require an understanding of when the peer has - received and applied the changed parameter values. In order to provide - such synchronization timepoints, the recipient of a SETTINGS frame in which the ACK flag - is not set MUST apply the updated parameters as soon as possible upon receipt. - - - The values in the SETTINGS frame MUST be processed in the order they appear, with no - other frame processing between values. Unsupported parameters MUST be ignored. Once - all values have been processed, the recipient MUST immediately emit a SETTINGS frame - with the ACK flag set. Upon receiving a SETTINGS frame with the ACK flag set, the sender - of the altered parameters can rely on the setting having been applied. - - - If the sender of a SETTINGS frame does not receive an acknowledgement within a - reasonable amount of time, it MAY issue a connection error of type - SETTINGS_TIMEOUT. - -
-
- -
- - The PUSH_PROMISE frame (type=0x5) is used to notify the peer endpoint in advance of - streams the sender intends to initiate. The PUSH_PROMISE frame includes the unsigned - 31-bit identifier of the stream the endpoint plans to create along with a set of headers - that provide additional context for the stream. contains a - thorough description of the use of PUSH_PROMISE frames. - - -
- -
- - The PUSH_PROMISE frame payload has the following fields: - - - An 8-bit field containing the length of the frame padding in units of octets. This - field is only present if the PADDED flag is set. - - - A single reserved bit. - - - An unsigned 31-bit integer that identifies the stream that is reserved by the - PUSH_PROMISE. The promised stream identifier MUST be a valid choice for the next - stream sent by the sender (see new stream - identifier). - - - A header block fragment containing request header - fields. - - - Padding octets. - - - - - - The PUSH_PROMISE frame defines the following flags: - - - - Bit 3 being set indicates that this frame contains an entire header block and is not followed by any - CONTINUATION frames. - - - A PUSH_PROMISE frame without the END_HEADERS flag set MUST be followed by a - CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any - other type of frame or a frame on a different stream as a connection error of type - PROTOCOL_ERROR. - - - - - Bit 4 being set indicates that the Pad Length field and any padding that it - describes is present. - - - - - - - PUSH_PROMISE frames MUST be associated with an existing, peer-initiated stream. The stream - identifier of a PUSH_PROMISE frame indicates the stream it is associated with. If the - stream identifier field specifies the value 0x0, a recipient MUST respond with a connection error of type - PROTOCOL_ERROR. - - - - Promised streams are not required to be used in the order they are promised. The - PUSH_PROMISE only reserves stream identifiers for later use. - - - - PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH setting of the - peer endpoint is set to 0. An endpoint that has set this setting and has received - acknowledgement MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type - PROTOCOL_ERROR. - - - Recipients of PUSH_PROMISE frames can choose to reject promised streams by returning a - RST_STREAM referencing the promised stream identifier back to the sender of - the PUSH_PROMISE. - - - - A PUSH_PROMISE frame modifies the connection state in two ways. The inclusion of a header block potentially modifies the state maintained for - header compression. PUSH_PROMISE also reserves a stream for later use, causing the - promised stream to enter the "reserved" state. A sender MUST NOT send a PUSH_PROMISE on a - stream unless that stream is either "open" or "half closed (remote)"; the sender MUST - ensure that the promised stream is a valid choice for a new stream identifier (that is, the promised stream MUST - be in the "idle" state). - - - Since PUSH_PROMISE reserves a stream, ignoring a PUSH_PROMISE frame causes the stream - state to become indeterminate. A receiver MUST treat the receipt of a PUSH_PROMISE on a - stream that is neither "open" nor "half closed (local)" as a connection error of type - PROTOCOL_ERROR. However, an endpoint that has sent - RST_STREAM on the associated stream MUST handle PUSH_PROMISE frames that - might have been created before the RST_STREAM frame is received and - processed. - - - A receiver MUST treat the receipt of a PUSH_PROMISE that promises an illegal stream identifier (that is, an identifier for a - stream that is not currently in the "idle" state) as a connection error of type - PROTOCOL_ERROR. - - - - The PUSH_PROMISE frame includes optional padding. Padding fields and flags are identical - to those defined for DATA frames. - -
- -
- - The PING frame (type=0x6) is a mechanism for measuring a minimal round trip time from the - sender, as well as determining whether an idle connection is still functional. PING - frames can be sent from any endpoint. - -
- -
- - - In addition to the frame header, PING frames MUST contain 8 octets of data in the payload. - A sender can include any value it chooses and use those bytes in any fashion. - - - Receivers of a PING frame that does not include an ACK flag MUST send a PING frame with - the ACK flag set in response, with an identical payload. PING responses SHOULD be given - higher priority than any other frame. - - - - The PING frame defines the following flags: - - - Bit 1 being set indicates that this PING frame is a PING response. An endpoint MUST - set this flag in PING responses. An endpoint MUST NOT respond to PING frames - containing this flag. - - - - - PING frames are not associated with any individual stream. If a PING frame is received - with a stream identifier field value other than 0x0, the recipient MUST respond with a - connection error of type - PROTOCOL_ERROR. - - - Receipt of a PING frame with a length field value other than 8 MUST be treated as a connection error of type - FRAME_SIZE_ERROR. - - -
- -
- - The GOAWAY frame (type=0x7) informs the remote peer to stop creating streams on this - connection. GOAWAY can be sent by either the client or the server. Once sent, the sender - will ignore frames sent on any new streams with identifiers higher than the included last - stream identifier. Receivers of a GOAWAY frame MUST NOT open additional streams on the - connection, although a new connection can be established for new streams. - - - The purpose of this frame is to allow an endpoint to gracefully stop accepting new - streams, while still finishing processing of previously established streams. This enables - administrative actions, like server maintainance. - - - There is an inherent race condition between an endpoint starting new streams and the - remote sending a GOAWAY frame. To deal with this case, the GOAWAY contains the stream - identifier of the last peer-initiated stream which was or might be processed on the - sending endpoint in this connection. For instance, if the server sends a GOAWAY frame, - the identified stream is the highest numbered stream initiated by the client. - - - If the receiver of the GOAWAY has sent data on streams with a higher stream identifier - than what is indicated in the GOAWAY frame, those streams are not or will not be - processed. The receiver of the GOAWAY frame can treat the streams as though they had - never been created at all, thereby allowing those streams to be retried later on a new - connection. - - - Endpoints SHOULD always send a GOAWAY frame before closing a connection so that the remote - can know whether a stream has been partially processed or not. For example, if an HTTP - client sends a POST at the same time that a server closes a connection, the client cannot - know if the server started to process that POST request if the server does not send a - GOAWAY frame to indicate what streams it might have acted on. - - - An endpoint might choose to close a connection without sending GOAWAY for misbehaving - peers. - - -
- -
- - The GOAWAY frame does not define any flags. - - - The GOAWAY frame applies to the connection, not a specific stream. An endpoint MUST treat - a GOAWAY frame with a stream identifier other than 0x0 as a connection error of type - PROTOCOL_ERROR. - - - The last stream identifier in the GOAWAY frame contains the highest numbered stream - identifier for which the sender of the GOAWAY frame might have taken some action on, or - might yet take action on. All streams up to and including the identified stream might - have been processed in some way. The last stream identifier can be set to 0 if no streams - were processed. - - - In this context, "processed" means that some data from the stream was passed to some - higher layer of software that might have taken some action as a result. - - - If a connection terminates without a GOAWAY frame, the last stream identifier is - effectively the highest possible stream identifier. - - - On streams with lower or equal numbered identifiers that were not closed completely prior - to the connection being closed, re-attempting requests, transactions, or any protocol - activity is not possible, with the exception of idempotent actions like HTTP GET, PUT, or - DELETE. Any protocol activity that uses higher numbered streams can be safely retried - using a new connection. - - - Activity on streams numbered lower or equal to the last stream identifier might still - complete successfully. The sender of a GOAWAY frame might gracefully shut down a - connection by sending a GOAWAY frame, maintaining the connection in an open state until - all in-progress streams complete. - - - An endpoint MAY send multiple GOAWAY frames if circumstances change. For instance, an - endpoint that sends GOAWAY with NO_ERROR during graceful shutdown could - subsequently encounter an condition that requires immediate termination of the connection. - The last stream identifier from the last GOAWAY frame received indicates which streams - could have been acted upon. Endpoints MUST NOT increase the value they send in the last - stream identifier, since the peers might already have retried unprocessed requests on - another connection. - - - A client that is unable to retry requests loses all requests that are in flight when the - server closes the connection. This is especially true for intermediaries that might - not be serving clients using HTTP/2. A server that is attempting to gracefully shut down - a connection SHOULD send an initial GOAWAY frame with the last stream identifier set to - 231-1 and a NO_ERROR code. This signals to the client that - a shutdown is imminent and that no further requests can be initiated. After waiting at - least one round trip time, the server can send another GOAWAY frame with an updated last - stream identifier. This ensures that a connection can be cleanly shut down without losing - requests. - - - - After sending a GOAWAY frame, the sender can discard frames for streams with identifiers - higher than the identified last stream. However, any frames that alter connection state - cannot be completely ignored. For instance, HEADERS, - PUSH_PROMISE and CONTINUATION frames MUST be minimally - processed to ensure the state maintained for header compression is consistent (see ); similarly DATA frames MUST be counted toward the connection flow - control window. Failure to process these frames can cause flow control or header - compression state to become unsynchronized. - - - - The GOAWAY frame also contains a 32-bit error code that - contains the reason for closing the connection. - - - Endpoints MAY append opaque data to the payload of any GOAWAY frame. Additional debug - data is intended for diagnostic purposes only and carries no semantic value. Debug - information could contain security- or privacy-sensitive data. Logged or otherwise - persistently stored debug data MUST have adequate safeguards to prevent unauthorized - access. - -
- -
- - The WINDOW_UPDATE frame (type=0x8) is used to implement flow control; see for an overview. - - - Flow control operates at two levels: on each individual stream and on the entire - connection. - - - Both types of flow control are hop-by-hop; that is, only between the two endpoints. - Intermediaries do not forward WINDOW_UPDATE frames between dependent connections. - However, throttling of data transfer by any receiver can indirectly cause the propagation - of flow control information toward the original sender. - - - Flow control only applies to frames that are identified as being subject to flow control. - Of the frame types defined in this document, this includes only DATA frames. - Frames that are exempt from flow control MUST be accepted and processed, unless the - receiver is unable to assign resources to handling the frame. A receiver MAY respond with - a stream error or connection error of type - FLOW_CONTROL_ERROR if it is unable to accept a frame. - -
- -
- - The payload of a WINDOW_UPDATE frame is one reserved bit, plus an unsigned 31-bit integer - indicating the number of octets that the sender can transmit in addition to the existing - flow control window. The legal range for the increment to the flow control window is 1 to - 231-1 (0x7fffffff) octets. - - - The WINDOW_UPDATE frame does not define any flags. - - - The WINDOW_UPDATE frame can be specific to a stream or to the entire connection. In the - former case, the frame's stream identifier indicates the affected stream; in the latter, - the value "0" indicates that the entire connection is the subject of the frame. - - - A receiver MUST treat the receipt of a WINDOW_UPDATE frame with an flow control window - increment of 0 as a stream error of type - PROTOCOL_ERROR; errors on the connection flow control window MUST be - treated as a connection error. - - - WINDOW_UPDATE can be sent by a peer that has sent a frame bearing the END_STREAM flag. - This means that a receiver could receive a WINDOW_UPDATE frame on a "half closed (remote)" - or "closed" stream. A receiver MUST NOT treat this as an error, see . - - - A receiver that receives a flow controlled frame MUST always account for its contribution - against the connection flow control window, unless the receiver treats this as a connection error. This is necessary even if the - frame is in error. Since the sender counts the frame toward the flow control window, if - the receiver does not, the flow control window at sender and receiver can become - different. - - -
- - Flow control in HTTP/2 is implemented using a window kept by each sender on every - stream. The flow control window is a simple integer value that indicates how many octets - of data the sender is permitted to transmit; as such, its size is a measure of the - buffering capacity of the receiver. - - - Two flow control windows are applicable: the stream flow control window and the - connection flow control window. The sender MUST NOT send a flow controlled frame with a - length that exceeds the space available in either of the flow control windows advertised - by the receiver. Frames with zero length with the END_STREAM flag set (that is, an - empty DATA frame) MAY be sent if there is no available space in either - flow control window. - - - For flow control calculations, the 9 octet frame header is not counted. - - - After sending a flow controlled frame, the sender reduces the space available in both - windows by the length of the transmitted frame. - - - The receiver of a frame sends a WINDOW_UPDATE frame as it consumes data and frees up - space in flow control windows. Separate WINDOW_UPDATE frames are sent for the stream - and connection level flow control windows. - - - A sender that receives a WINDOW_UPDATE frame updates the corresponding window by the - amount specified in the frame. - - - A sender MUST NOT allow a flow control window to exceed 231-1 octets. - If a sender receives a WINDOW_UPDATE that causes a flow control window to exceed this - maximum it MUST terminate either the stream or the connection, as appropriate. For - streams, the sender sends a RST_STREAM with the error code of - FLOW_CONTROL_ERROR code; for the connection, a GOAWAY - frame with a FLOW_CONTROL_ERROR code. - - - Flow controlled frames from the sender and WINDOW_UPDATE frames from the receiver are - completely asynchronous with respect to each other. This property allows a receiver to - aggressively update the window size kept by the sender to prevent streams from stalling. - -
- -
- - When an HTTP/2 connection is first established, new streams are created with an initial - flow control window size of 65,535 octets. The connection flow control window is 65,535 - octets. Both endpoints can adjust the initial window size for new streams by including - a value for SETTINGS_INITIAL_WINDOW_SIZE in the SETTINGS - frame that forms part of the connection preface. The connection flow control window can - only be changed using WINDOW_UPDATE frames. - - - Prior to receiving a SETTINGS frame that sets a value for - SETTINGS_INITIAL_WINDOW_SIZE, an endpoint can only use the default - initial window size when sending flow controlled frames. Similarly, the connection flow - control window is set to the default initial window size until a WINDOW_UPDATE frame is - received. - - - A SETTINGS frame can alter the initial flow control window size for all - current streams. When the value of SETTINGS_INITIAL_WINDOW_SIZE changes, - a receiver MUST adjust the size of all stream flow control windows that it maintains by - the difference between the new value and the old value. - - - A change to SETTINGS_INITIAL_WINDOW_SIZE can cause the available space in - a flow control window to become negative. A sender MUST track the negative flow control - window, and MUST NOT send new flow controlled frames until it receives WINDOW_UPDATE - frames that cause the flow control window to become positive. - - - For example, if the client sends 60KB immediately on connection establishment, and the - server sets the initial window size to be 16KB, the client will recalculate the - available flow control window to be -44KB on receipt of the SETTINGS - frame. The client retains a negative flow control window until WINDOW_UPDATE frames - restore the window to being positive, after which the client can resume sending. - - - A SETTINGS frame cannot alter the connection flow control window. - - - An endpoint MUST treat a change to SETTINGS_INITIAL_WINDOW_SIZE that - causes any flow control window to exceed the maximum size as a connection error of type - FLOW_CONTROL_ERROR. - -
- -
- - A receiver that wishes to use a smaller flow control window than the current size can - send a new SETTINGS frame. However, the receiver MUST be prepared to - receive data that exceeds this window size, since the sender might send data that - exceeds the lower limit prior to processing the SETTINGS frame. - - - After sending a SETTINGS frame that reduces the initial flow control window size, a - receiver has two options for handling streams that exceed flow control limits: - - - The receiver can immediately send RST_STREAM with - FLOW_CONTROL_ERROR error code for the affected streams. - - - The receiver can accept the streams and tolerate the resulting head of line - blocking, sending WINDOW_UPDATE frames as it consumes data. - - - -
-
- -
- - The CONTINUATION frame (type=0x9) is used to continue a sequence of header block fragments. Any number of CONTINUATION frames can - be sent on an existing stream, as long as the preceding frame is on the same stream and is - a HEADERS, PUSH_PROMISE or CONTINUATION frame without the - END_HEADERS flag set. - - -
- -
- - The CONTINUATION frame payload contains a header block - fragment. - - - - The CONTINUATION frame defines the following flag: - - - - Bit 3 being set indicates that this frame ends a header - block. - - - If the END_HEADERS bit is not set, this frame MUST be followed by another - CONTINUATION frame. A receiver MUST treat the receipt of any other type of frame or - a frame on a different stream as a connection - error of type PROTOCOL_ERROR. - - - - - - - The CONTINUATION frame changes the connection state as defined in . - - - - CONTINUATION frames MUST be associated with a stream. If a CONTINUATION frame is received - whose stream identifier field is 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. - - - - A CONTINUATION frame MUST be preceded by a HEADERS, - PUSH_PROMISE or CONTINUATION frame without the END_HEADERS flag set. A - recipient that observes violation of this rule MUST respond with a connection error of type - PROTOCOL_ERROR. - -
-
- -
- - Error codes are 32-bit fields that are used in RST_STREAM and - GOAWAY frames to convey the reasons for the stream or connection error. - - - - Error codes share a common code space. Some error codes apply only to either streams or the - entire connection and have no defined semantics in the other context. - - - - The following error codes are defined: - - - The associated condition is not as a result of an error. For example, a - GOAWAY might include this code to indicate graceful shutdown of a - connection. - - - The endpoint detected an unspecific protocol error. This error is for use when a more - specific error code is not available. - - - The endpoint encountered an unexpected internal error. - - - The endpoint detected that its peer violated the flow control protocol. - - - The endpoint sent a SETTINGS frame, but did not receive a response in a - timely manner. See Settings Synchronization. - - - The endpoint received a frame after a stream was half closed. - - - The endpoint received a frame with an invalid size. - - - The endpoint refuses the stream prior to performing any application processing, see - for details. - - - Used by the endpoint to indicate that the stream is no longer needed. - - - The endpoint is unable to maintain the header compression context for the connection. - - - The connection established in response to a CONNECT - request was reset or abnormally closed. - - - The endpoint detected that its peer is exhibiting a behavior that might be generating - excessive load. - - - The underlying transport has properties that do not meet minimum security - requirements (see ). - - - - - Unknown or unsupported error codes MUST NOT trigger any special behavior. These MAY be - treated by an implementation as being equivalent to INTERNAL_ERROR. - -
- -
- - HTTP/2 is intended to be as compatible as possible with current uses of HTTP. This means - that, from the application perspective, the features of the protocol are largely - unchanged. To achieve this, all request and response semantics are preserved, although the - syntax of conveying those semantics has changed. - - - Thus, the specification and requirements of HTTP/1.1 Semantics and Content , Conditional Requests , Range Requests , Caching and Authentication are applicable to HTTP/2. Selected portions of HTTP/1.1 Message Syntax - and Routing , such as the HTTP and HTTPS URI schemes, are also - applicable in HTTP/2, but the expression of those semantics for this protocol are defined - in the sections below. - - -
- - A client sends an HTTP request on a new stream, using a previously unused stream identifier. A server sends an HTTP response on - the same stream as the request. - - - An HTTP message (request or response) consists of: - - - for a response only, zero or more HEADERS frames (each followed by zero - or more CONTINUATION frames) containing the message headers of - informational (1xx) HTTP responses (see and ), - and - - - one HEADERS frame (followed by zero or more CONTINUATION - frames) containing the message headers (see ), and - - - zero or more DATA frames containing the message payload (see ), and - - - optionally, one HEADERS frame, followed by zero or more - CONTINUATION frames containing the trailer-part, if present (see ). - - - The last frame in the sequence bears an END_STREAM flag, noting that a - HEADERS frame bearing the END_STREAM flag can be followed by - CONTINUATION frames that carry any remaining portions of the header block. - - - Other frames (from any stream) MUST NOT occur between either HEADERS frame - and any CONTINUATION frames that might follow. - - - - Trailing header fields are carried in a header block that also terminates the stream. - That is, a sequence starting with a HEADERS frame, followed by zero or more - CONTINUATION frames, where the HEADERS frame bears an - END_STREAM flag. Header blocks after the first that do not terminate the stream are not - part of an HTTP request or response. - - - A HEADERS frame (and associated CONTINUATION frames) can - only appear at the start or end of a stream. An endpoint that receives a - HEADERS frame without the END_STREAM flag set after receiving a final - (non-informational) status code MUST treat the corresponding request or response as malformed. - - - - An HTTP request/response exchange fully consumes a single stream. A request starts with - the HEADERS frame that puts the stream into an "open" state. The request - ends with a frame bearing END_STREAM, which causes the stream to become "half closed - (local)" for the client and "half closed (remote)" for the server. A response starts with - a HEADERS frame and ends with a frame bearing END_STREAM, which places the - stream in the "closed" state. - - - -
- - HTTP/2 removes support for the 101 (Switching Protocols) informational status code - (). - - - The semantics of 101 (Switching Protocols) aren't applicable to a multiplexed protocol. - Alternative protocols are able to use the same mechanisms that HTTP/2 uses to negotiate - their use (see ). - -
- -
- - HTTP header fields carry information as a series of key-value pairs. For a listing of - registered HTTP headers, see the Message Header Field Registry maintained at . - - -
- - While HTTP/1.x used the message start-line (see ) to convey the target URI and method of the request, and the - status code for the response, HTTP/2 uses special pseudo-header fields beginning with - ':' character (ASCII 0x3a) for this purpose. - - - Pseudo-header fields are not HTTP header fields. Endpoints MUST NOT generate - pseudo-header fields other than those defined in this document. - - - Pseudo-header fields are only valid in the context in which they are defined. - Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header - fields defined for responses MUST NOT appear in requests. Pseudo-header fields MUST - NOT appear in trailers. Endpoints MUST treat a request or response that contains - undefined or invalid pseudo-header fields as malformed. - - - Just as in HTTP/1.x, header field names are strings of ASCII characters that are - compared in a case-insensitive fashion. However, header field names MUST be converted - to lowercase prior to their encoding in HTTP/2. A request or response containing - uppercase header field names MUST be treated as malformed. - - - All pseudo-header fields MUST appear in the header block before regular header fields. - Any request or response that contains a pseudo-header field that appears in a header - block after a regular header field MUST be treated as malformed. - -
- -
- - HTTP/2 does not use the Connection header field to - indicate connection-specific header fields; in this protocol, connection-specific - metadata is conveyed by other means. An endpoint MUST NOT generate a HTTP/2 message - containing connection-specific header fields; any message containing - connection-specific header fields MUST be treated as malformed. - - - This means that an intermediary transforming an HTTP/1.x message to HTTP/2 will need - to remove any header fields nominated by the Connection header field, along with the - Connection header field itself. Such intermediaries SHOULD also remove other - connection-specific header fields, such as Keep-Alive, Proxy-Connection, - Transfer-Encoding and Upgrade, even if they are not nominated by Connection. - - - One exception to this is the TE header field, which MAY be present in an HTTP/2 - request, but when it is MUST NOT contain any value other than "trailers". - - - - - HTTP/2 purposefully does not support upgrade to another protocol. The handshake - methods described in are believed sufficient to - negotiate the use of alternative protocols. - - - -
- -
- - The following pseudo-header fields are defined for HTTP/2 requests: - - - - The :method pseudo-header field includes the HTTP - method (). - - - - - The :scheme pseudo-header field includes the scheme - portion of the target URI (). - - - :scheme is not restricted to http and https schemed URIs. A - proxy or gateway can translate requests for non-HTTP schemes, enabling the use - of HTTP to interact with non-HTTP services. - - - - - The :authority pseudo-header field includes the - authority portion of the target URI (). The authority MUST NOT include the deprecated userinfo subcomponent for http - or https schemed URIs. - - - To ensure that the HTTP/1.1 request line can be reproduced accurately, this - pseudo-header field MUST be omitted when translating from an HTTP/1.1 request - that has a request target in origin or asterisk form (see ). Clients that generate - HTTP/2 requests directly SHOULD use the :authority pseudo-header - field instead of the Host header field. An - intermediary that converts an HTTP/2 request to HTTP/1.1 MUST create a Host header field if one is not present in a request by - copying the value of the :authority pseudo-header - field. - - - - - The :path pseudo-header field includes the path and - query parts of the target URI (the path-absolute - production from and optionally a '?' character - followed by the query production, see and ). A request in asterisk form includes the value '*' for the - :path pseudo-header field. - - - This pseudo-header field MUST NOT be empty for http - or https URIs; http or - https URIs that do not contain a path component - MUST include a value of '/'. The exception to this rule is an OPTIONS request - for an http or https - URI that does not include a path component; these MUST include a :path pseudo-header field with a value of '*' (see ). - - - - - - All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header fields, unless it is a CONNECT request. An HTTP request that omits mandatory - pseudo-header fields is malformed. - - - HTTP/2 does not define a way to carry the version identifier that is included in the - HTTP/1.1 request line. - -
- -
- - For HTTP/2 responses, a single :status pseudo-header - field is defined that carries the HTTP status code field (see ). This pseudo-header field MUST be included in all - responses, otherwise the response is malformed. - - - HTTP/2 does not define a way to carry the version or reason phrase that is included in - an HTTP/1.1 status line. - -
- -
- - The Cookie header field can carry a significant amount of - redundant data. - - - The Cookie header field uses a semi-colon (";") to delimit cookie-pairs (or "crumbs"). - This header field doesn't follow the list construction rules in HTTP (see ), which prevents cookie-pairs from - being separated into different name-value pairs. This can significantly reduce - compression efficiency as individual cookie-pairs are updated. - - - To allow for better compression efficiency, the Cookie header field MAY be split into - separate header fields, each with one or more cookie-pairs. If there are multiple - Cookie header fields after decompression, these MUST be concatenated into a single - octet string using the two octet delimiter of 0x3B, 0x20 (the ASCII string "; ") - before being passed into a non-HTTP/2 context, such as an HTTP/1.1 connection, or a - generic HTTP server application. - -
- - Therefore, the following two lists of Cookie header fields are semantically - equivalent. - - -
-
- -
- - A malformed request or response is one that is an otherwise valid sequence of HTTP/2 - frames, but is otherwise invalid due to the presence of extraneous frames, prohibited - header fields, the absence of mandatory header fields, or the inclusion of uppercase - header field names. - - - A request or response that includes an entity body can include a content-length header field. A request or response is also - malformed if the value of a content-length header field - does not equal the sum of the DATA frame payload lengths that form the - body. A response that is defined to have no payload, as described in , can have a non-zero - content-length header field, even though no content is - included in DATA frames. - - - Intermediaries that process HTTP requests or responses (i.e., any intermediary not - acting as a tunnel) MUST NOT forward a malformed request or response. Malformed - requests or responses that are detected MUST be treated as a stream error of type PROTOCOL_ERROR. - - - For malformed requests, a server MAY send an HTTP response prior to closing or - resetting the stream. Clients MUST NOT accept a malformed response. Note that these - requirements are intended to protect against several types of common attacks against - HTTP; they are deliberately strict, because being permissive can expose - implementations to these vulnerabilities. - -
-
- -
- - This section shows HTTP/1.1 requests and responses, with illustrations of equivalent - HTTP/2 requests and responses. - - - An HTTP GET request includes request header fields and no body and is therefore - transmitted as a single HEADERS frame, followed by zero or more - CONTINUATION frames containing the serialized block of request header - fields. The HEADERS frame in the following has both the END_HEADERS and - END_STREAM flags set; no CONTINUATION frames are sent: - - -
- + END_STREAM - Accept: image/jpeg + END_HEADERS - :method = GET - :scheme = https - :path = /resource - host = example.org - accept = image/jpeg -]]> -
- - - Similarly, a response that includes only response header fields is transmitted as a - HEADERS frame (again, followed by zero or more - CONTINUATION frames) containing the serialized block of response header - fields. - - -
- + END_STREAM - Expires: Thu, 23 Jan ... + END_HEADERS - :status = 304 - etag = "xyzzy" - expires = Thu, 23 Jan ... -]]> -
- - - An HTTP POST request that includes request header fields and payload data is transmitted - as one HEADERS frame, followed by zero or more - CONTINUATION frames containing the request header fields, followed by one - or more DATA frames, with the last CONTINUATION (or - HEADERS) frame having the END_HEADERS flag set and the final - DATA frame having the END_STREAM flag set: - - -
- - END_STREAM - Content-Type: image/jpeg - END_HEADERS - Content-Length: 123 :method = POST - :path = /resource - {binary data} :scheme = https - - CONTINUATION - + END_HEADERS - content-type = image/jpeg - host = example.org - content-length = 123 - - DATA - + END_STREAM - {binary data} -]]> - - Note that data contributing to any given header field could be spread between header - block fragments. The allocation of header fields to frames in this example is - illustrative only. - -
- - - A response that includes header fields and payload data is transmitted as a - HEADERS frame, followed by zero or more CONTINUATION - frames, followed by one or more DATA frames, with the last - DATA frame in the sequence having the END_STREAM flag set: - - -
- - END_STREAM - Content-Length: 123 + END_HEADERS - :status = 200 - {binary data} content-type = image/jpeg - content-length = 123 - - DATA - + END_STREAM - {binary data} -]]> -
- - - Trailing header fields are sent as a header block after both the request or response - header block and all the DATA frames have been sent. The - HEADERS frame starting the trailers header block has the END_STREAM flag - set. - - -
- - END_STREAM - Transfer-Encoding: chunked + END_HEADERS - Trailer: Foo :status = 200 - content-length = 123 - 123 content-type = image/jpeg - {binary data} trailer = Foo - 0 - Foo: bar DATA - - END_STREAM - {binary data} - - HEADERS - + END_STREAM - + END_HEADERS - foo = bar -]]> -
- - -
- - An informational response using a 1xx status code other than 101 is transmitted as a - HEADERS frame, followed by zero or more CONTINUATION - frames: - - - END_STREAM - + END_HEADERS - :status = 103 - extension-field = bar -]]> -
-
- -
- - In HTTP/1.1, an HTTP client is unable to retry a non-idempotent request when an error - occurs, because there is no means to determine the nature of the error. It is possible - that some server processing occurred prior to the error, which could result in - undesirable effects if the request were reattempted. - - - HTTP/2 provides two mechanisms for providing a guarantee to a client that a request has - not been processed: - - - The GOAWAY frame indicates the highest stream number that might have - been processed. Requests on streams with higher numbers are therefore guaranteed to - be safe to retry. - - - The REFUSED_STREAM error code can be included in a - RST_STREAM frame to indicate that the stream is being closed prior to - any processing having occurred. Any request that was sent on the reset stream can - be safely retried. - - - - - Requests that have not been processed have not failed; clients MAY automatically retry - them, even those with non-idempotent methods. - - - A server MUST NOT indicate that a stream has not been processed unless it can guarantee - that fact. If frames that are on a stream are passed to the application layer for any - stream, then REFUSED_STREAM MUST NOT be used for that stream, and a - GOAWAY frame MUST include a stream identifier that is greater than or - equal to the given stream identifier. - - - In addition to these mechanisms, the PING frame provides a way for a - client to easily test a connection. Connections that remain idle can become broken as - some middleboxes (for instance, network address translators, or load balancers) silently - discard connection bindings. The PING frame allows a client to safely - test whether a connection is still active without sending a request. - -
-
- -
- - HTTP/2 allows a server to pre-emptively send (or "push") responses (along with - corresponding "promised" requests) to a client in association with a previous - client-initiated request. This can be useful when the server knows the client will need - to have those responses available in order to fully process the response to the original - request. - - - - Pushing additional message exchanges in this fashion is optional, and is negotiated - between individual endpoints. The SETTINGS_ENABLE_PUSH setting can be set - to 0 to indicate that server push is disabled. - - - Promised requests MUST be cacheable (see ), MUST be safe (see ) and MUST NOT include a request body. Clients that receive a - promised request that is not cacheable, unsafe or that includes a request body MUST - reset the stream with a stream error of type - PROTOCOL_ERROR. - - - Pushed responses that are cacheable (see ) can be stored by the client, if it implements a HTTP - cache. Pushed responses are considered successfully validated on the origin server (e.g., - if the "no-cache" cache response directive is present) while the stream identified by the - promised stream ID is still open. - - - Pushed responses that are not cacheable MUST NOT be stored by any HTTP cache. They MAY - be made available to the application separately. - - - An intermediary can receive pushes from the server and choose not to forward them on to - the client. In other words, how to make use of the pushed information is up to that - intermediary. Equally, the intermediary might choose to make additional pushes to the - client, without any action taken by the server. - - - A client cannot push. Thus, servers MUST treat the receipt of a - PUSH_PROMISE frame as a connection - error of type PROTOCOL_ERROR. Clients MUST reject any attempt to - change the SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating - the message as a connection error of type - PROTOCOL_ERROR. - - -
- - Server push is semantically equivalent to a server responding to a request; however, in - this case that request is also sent by the server, as a PUSH_PROMISE - frame. - - - The PUSH_PROMISE frame includes a header block that contains a complete - set of request header fields that the server attributes to the request. It is not - possible to push a response to a request that includes a request body. - - - - Pushed responses are always associated with an explicit request from the client. The - PUSH_PROMISE frames sent by the server are sent on that explicit - request's stream. The PUSH_PROMISE frame also includes a promised stream - identifier, chosen from the stream identifiers available to the server (see ). - - - - The header fields in PUSH_PROMISE and any subsequent - CONTINUATION frames MUST be a valid and complete set of request header fields. The server MUST include a method in - the :method header field that is safe and cacheable. If a - client receives a PUSH_PROMISE that does not include a complete and valid - set of header fields, or the :method header field identifies - a method that is not safe, it MUST respond with a stream error of type PROTOCOL_ERROR. - - - - The server SHOULD send PUSH_PROMISE () - frames prior to sending any frames that reference the promised responses. This avoids a - race where clients issue requests prior to receiving any PUSH_PROMISE - frames. - - - For example, if the server receives a request for a document containing embedded links - to multiple image files, and the server chooses to push those additional images to the - client, sending push promises before the DATA frames that contain the - image links ensures that the client is able to see the promises before discovering - embedded links. Similarly, if the server pushes responses referenced by the header block - (for instance, in Link header fields), sending the push promises before sending the - header block ensures that clients do not request them. - - - - PUSH_PROMISE frames MUST NOT be sent by the client. - - - PUSH_PROMISE frames can be sent by the server in response to any - client-initiated stream, but the stream MUST be in either the "open" or "half closed - (remote)" state with respect to the server. PUSH_PROMISE frames are - interspersed with the frames that comprise a response, though they cannot be - interspersed with HEADERS and CONTINUATION frames that - comprise a single header block. - - - Sending a PUSH_PROMISE frame creates a new stream and puts the stream - into the “reserved (local)” state for the server and the “reserved (remote)” state for - the client. - -
- -
- - After sending the PUSH_PROMISE frame, the server can begin delivering the - pushed response as a response on a server-initiated - stream that uses the promised stream identifier. The server uses this stream to - transmit an HTTP response, using the same sequence of frames as defined in . This stream becomes "half closed" - to the client after the initial HEADERS frame is sent. - - - - Once a client receives a PUSH_PROMISE frame and chooses to accept the - pushed response, the client SHOULD NOT issue any requests for the promised response - until after the promised stream has closed. - - - - If the client determines, for any reason, that it does not wish to receive the pushed - response from the server, or if the server takes too long to begin sending the promised - response, the client can send an RST_STREAM frame, using either the - CANCEL or REFUSED_STREAM codes, and referencing the pushed - stream's identifier. - - - A client can use the SETTINGS_MAX_CONCURRENT_STREAMS setting to limit the - number of responses that can be concurrently pushed by a server. Advertising a - SETTINGS_MAX_CONCURRENT_STREAMS value of zero disables server push by - preventing the server from creating the necessary streams. This does not prohibit a - server from sending PUSH_PROMISE frames; clients need to reset any - promised streams that are not wanted. - - - - Clients receiving a pushed response MUST validate that either the server is - authoritative (see ), or the proxy that provided the pushed - response is configured for the corresponding request. For example, a server that offers - a certificate for only the example.com DNS-ID or Common Name - is not permitted to push a response for https://www.example.org/doc. - - - The response for a PUSH_PROMISE stream begins with a - HEADERS frame, which immediately puts the stream into the “half closed - (remote)” state for the server and “half closed (local)” state for the client, and ends - with a frame bearing END_STREAM, which places the stream in the "closed" state. - - - The client never sends a frame with the END_STREAM flag for a server push. - - - -
- -
- -
- - In HTTP/1.x, the pseudo-method CONNECT () is used to convert an HTTP connection into a tunnel to a remote host. - CONNECT is primarily used with HTTP proxies to establish a TLS session with an origin - server for the purposes of interacting with https resources. - - - In HTTP/2, the CONNECT method is used to establish a tunnel over a single HTTP/2 stream to - a remote host, for similar purposes. The HTTP header field mapping works as defined in - Request Header Fields, with a few - differences. Specifically: - - - The :method header field is set to CONNECT. - - - The :scheme and :path header - fields MUST be omitted. - - - The :authority header field contains the host and port to - connect to (equivalent to the authority-form of the request-target of CONNECT - requests, see ). - - - - - A proxy that supports CONNECT establishes a TCP connection to - the server identified in the :authority header field. Once - this connection is successfully established, the proxy sends a HEADERS - frame containing a 2xx series status code to the client, as defined in . - - - After the initial HEADERS frame sent by each peer, all subsequent - DATA frames correspond to data sent on the TCP connection. The payload of - any DATA frames sent by the client is transmitted by the proxy to the TCP - server; data received from the TCP server is assembled into DATA frames by - the proxy. Frame types other than DATA or stream management frames - (RST_STREAM, WINDOW_UPDATE, and PRIORITY) - MUST NOT be sent on a connected stream, and MUST be treated as a stream error if received. - - - The TCP connection can be closed by either peer. The END_STREAM flag on a - DATA frame is treated as being equivalent to the TCP FIN bit. A client is - expected to send a DATA frame with the END_STREAM flag set after receiving - a frame bearing the END_STREAM flag. A proxy that receives a DATA frame - with the END_STREAM flag set sends the attached data with the FIN bit set on the last TCP - segment. A proxy that receives a TCP segment with the FIN bit set sends a - DATA frame with the END_STREAM flag set. Note that the final TCP segment - or DATA frame could be empty. - - - A TCP connection error is signaled with RST_STREAM. A proxy treats any - error in the TCP connection, which includes receiving a TCP segment with the RST bit set, - as a stream error of type - CONNECT_ERROR. Correspondingly, a proxy MUST send a TCP segment with the - RST bit set if it detects an error with the stream or the HTTP/2 connection. - -
-
- -
- - This section outlines attributes of the HTTP protocol that improve interoperability, reduce - exposure to known security vulnerabilities, or reduce the potential for implementation - variation. - - -
- - HTTP/2 connections are persistent. For best performance, it is expected clients will not - close connections until it is determined that no further communication with a server is - necessary (for example, when a user navigates away from a particular web page), or until - the server closes the connection. - - - Clients SHOULD NOT open more than one HTTP/2 connection to a given host and port pair, - where host is derived from a URI, a selected alternative - service, or a configured proxy. - - - A client can create additional connections as replacements, either to replace connections - that are near to exhausting the available stream - identifier space, to refresh the keying material for a TLS connection, or to - replace connections that have encountered errors. - - - A client MAY open multiple connections to the same IP address and TCP port using different - Server Name Indication values or to provide different TLS - client certificates, but SHOULD avoid creating multiple connections with the same - configuration. - - - Servers are encouraged to maintain open connections for as long as possible, but are - permitted to terminate idle connections if necessary. When either endpoint chooses to - close the transport-layer TCP connection, the terminating endpoint SHOULD first send a - GOAWAY () frame so that both endpoints can reliably - determine whether previously sent frames have been processed and gracefully complete or - terminate any necessary remaining tasks. - - -
- - Connections that are made to an origin servers, either directly or through a tunnel - created using the CONNECT method MAY be reused for - requests with multiple different URI authority components. A connection can be reused - as long as the origin server is authoritative. For - http resources, this depends on the host having resolved to - the same IP address. - - - For https resources, connection reuse additionally depends - on having a certificate that is valid for the host in the URI. An origin server might - offer a certificate with multiple subjectAltName attributes, - or names with wildcards, one of which is valid for the authority in the URI. For - example, a certificate with a subjectAltName of *.example.com might permit the use of the same connection for - requests to URIs starting with https://a.example.com/ and - https://b.example.com/. - - - In some deployments, reusing a connection for multiple origins can result in requests - being directed to the wrong origin server. For example, TLS termination might be - performed by a middlebox that uses the TLS Server Name Indication - (SNI) extension to select an origin server. This means that it is possible - for clients to send confidential information to servers that might not be the intended - target for the request, even though the server is otherwise authoritative. - - - A server that does not wish clients to reuse connections can indicate that it is not - authoritative for a request by sending a 421 (Misdirected Request) status code in response - to the request (see ). - - - A client that is configured to use a proxy over HTTP/2 directs requests to that proxy - through a single connection. That is, all requests sent via a proxy reuse the - connection to the proxy. - -
- -
- - The 421 (Misdirected Request) status code indicates that the request was directed at a - server that is not able to produce a response. This can be sent by a server that is not - configured to produce responses for the combination of scheme and authority that are - included in the request URI. - - - Clients receiving a 421 (Misdirected Request) response from a server MAY retry the - request - whether the request method is idempotent or not - over a different connection. - This is possible if a connection is reused () or if an alternative - service is selected (). - - - This status code MUST NOT be generated by proxies. - - - A 421 response is cacheable by default; i.e., unless otherwise indicated by the method - definition or explicit cache controls (see ). - -
-
- -
- - Implementations of HTTP/2 MUST support TLS 1.2 for HTTP/2 over - TLS. The general TLS usage guidance in SHOULD be followed, with - some additional restrictions that are specific to HTTP/2. - - - - An implementation of HTTP/2 over TLS MUST use TLS 1.2 or higher with the restrictions on - feature set and cipher suite described in this section. Due to implementation - limitations, it might not be possible to fail TLS negotiation. An endpoint MUST - immediately terminate an HTTP/2 connection that does not meet these minimum requirements - with a connection error of type - INADEQUATE_SECURITY. - - -
- - The TLS implementation MUST support the Server Name Indication - (SNI) extension to TLS. HTTP/2 clients MUST indicate the target domain name when - negotiating TLS. - - - The TLS implementation MUST disable compression. TLS compression can lead to the - exposure of information that would not otherwise be revealed . - Generic compression is unnecessary since HTTP/2 provides compression features that are - more aware of context and therefore likely to be more appropriate for use for - performance, security or other reasons. - - - The TLS implementation MUST disable renegotiation. An endpoint MUST treat a TLS - renegotiation as a connection error of type - PROTOCOL_ERROR. Note that disabling renegotiation can result in - long-lived connections becoming unusable due to limits on the number of messages the - underlying cipher suite can encipher. - - - A client MAY use renegotiation to provide confidentiality protection for client - credentials offered in the handshake, but any renegotiation MUST occur prior to sending - the connection preface. A server SHOULD request a client certificate if it sees a - renegotiation request immediately after establishing a connection. - - - This effectively prevents the use of renegotiation in response to a request for a - specific protected resource. A future specification might provide a way to support this - use case. - -
- -
- - The set of TLS cipher suites that are permitted in HTTP/2 is restricted. HTTP/2 MUST - only be used with cipher suites that have ephemeral key exchange, such as the ephemeral Diffie-Hellman (DHE) or the elliptic curve variant (ECDHE). Ephemeral key exchange MUST - have a minimum size of 2048 bits for DHE or security level of 128 bits for ECDHE. - Clients MUST accept DHE sizes of up to 4096 bits. HTTP MUST NOT be used with cipher - suites that use stream or block ciphers. Authenticated Encryption with Additional Data - (AEAD) modes, such as the Galois Counter Model (GCM) mode for - AES are acceptable. - - - The effect of these restrictions is that TLS 1.2 implementations could have - non-intersecting sets of available cipher suites, since these prevent the use of the - cipher suite that TLS 1.2 makes mandatory. To avoid this problem, implementations of - HTTP/2 that use TLS 1.2 MUST support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 with P256 . - - - Clients MAY advertise support of cipher suites that are prohibited by the above - restrictions in order to allow for connection to servers that do not support HTTP/2. - This enables a fallback to protocols without these constraints without the additional - latency imposed by using a separate connection for fallback. - -
-
-
- -
-
- - HTTP/2 relies on the HTTP/1.1 definition of authority for determining whether a server is - authoritative in providing a given response, see . This relies on local name resolution for the "http" - URI scheme, and the authenticated server identity for the "https" scheme (see ). - -
- -
- - In a cross-protocol attack, an attacker causes a client to initiate a transaction in one - protocol toward a server that understands a different protocol. An attacker might be able - to cause the transaction to appear as valid transaction in the second protocol. In - combination with the capabilities of the web context, this can be used to interact with - poorly protected servers in private networks. - - - Completing a TLS handshake with an ALPN identifier for HTTP/2 can be considered sufficient - protection against cross protocol attacks. ALPN provides a positive indication that a - server is willing to proceed with HTTP/2, which prevents attacks on other TLS-based - protocols. - - - The encryption in TLS makes it difficult for attackers to control the data which could be - used in a cross-protocol attack on a cleartext protocol. - - - The cleartext version of HTTP/2 has minimal protection against cross-protocol attacks. - The connection preface contains a string that is - designed to confuse HTTP/1.1 servers, but no special protection is offered for other - protocols. A server that is willing to ignore parts of an HTTP/1.1 request containing an - Upgrade header field in addition to the client connection preface could be exposed to a - cross-protocol attack. - -
- -
- - HTTP/2 header field names and values are encoded as sequences of octets with a length - prefix. This enables HTTP/2 to carry any string of octets as the name or value of a - header field. An intermediary that translates HTTP/2 requests or responses into HTTP/1.1 - directly could permit the creation of corrupted HTTP/1.1 messages. An attacker might - exploit this behavior to cause the intermediary to create HTTP/1.1 messages with illegal - header fields, extra header fields, or even new messages that are entirely falsified. - - - Header field names or values that contain characters not permitted by HTTP/1.1, including - carriage return (ASCII 0xd) or line feed (ASCII 0xa) MUST NOT be translated verbatim by an - intermediary, as stipulated in . - - - Translation from HTTP/1.x to HTTP/2 does not produce the same opportunity to an attacker. - Intermediaries that perform translation to HTTP/2 MUST remove any instances of the obs-fold production from header field values. - -
- -
- - Pushed responses do not have an explicit request from the client; the request - is provided by the server in the PUSH_PROMISE frame. - - - Caching responses that are pushed is possible based on the guidance provided by the origin - server in the Cache-Control header field. However, this can cause issues if a single - server hosts more than one tenant. For example, a server might offer multiple users each - a small portion of its URI space. - - - Where multiple tenants share space on the same server, that server MUST ensure that - tenants are not able to push representations of resources that they do not have authority - over. Failure to enforce this would allow a tenant to provide a representation that would - be served out of cache, overriding the actual representation that the authoritative tenant - provides. - - - Pushed responses for which an origin server is not authoritative (see - ) are never cached or used. - -
- -
- - An HTTP/2 connection can demand a greater commitment of resources to operate than a - HTTP/1.1 connection. The use of header compression and flow control depend on a - commitment of resources for storing a greater amount of state. Settings for these - features ensure that memory commitments for these features are strictly bounded. - - - The number of PUSH_PROMISE frames is not constrained in the same fashion. - A client that accepts server push SHOULD limit the number of streams it allows to be in - the "reserved (remote)" state. Excessive number of server push streams can be treated as - a stream error of type - ENHANCE_YOUR_CALM. - - - Processing capacity cannot be guarded as effectively as state capacity. - - - The SETTINGS frame can be abused to cause a peer to expend additional - processing time. This might be done by pointlessly changing SETTINGS parameters, setting - multiple undefined parameters, or changing the same setting multiple times in the same - frame. WINDOW_UPDATE or PRIORITY frames can be abused to - cause an unnecessary waste of resources. - - - Large numbers of small or empty frames can be abused to cause a peer to expend time - processing frame headers. Note however that some uses are entirely legitimate, such as - the sending of an empty DATA frame to end a stream. - - - Header compression also offers some opportunities to waste processing resources; see for more details on potential abuses. - - - Limits in SETTINGS parameters cannot be reduced instantaneously, which - leaves an endpoint exposed to behavior from a peer that could exceed the new limits. In - particular, immediately after establishing a connection, limits set by a server are not - known to clients and could be exceeded without being an obvious protocol violation. - - - All these features - i.e., SETTINGS changes, small frames, header - compression - have legitimate uses. These features become a burden only when they are - used unnecessarily or to excess. - - - An endpoint that doesn't monitor this behavior exposes itself to a risk of denial of - service attack. Implementations SHOULD track the use of these features and set limits on - their use. An endpoint MAY treat activity that is suspicious as a connection error of type - ENHANCE_YOUR_CALM. - - -
- - A large header block can cause an implementation to - commit a large amount of state. Header fields that are critical for routing can appear - toward the end of a header block, which prevents streaming of header fields to their - ultimate destination. For this an other reasons, such as ensuring cache correctness, - means that an endpoint might need to buffer the entire header block. Since there is no - hard limit to the size of a header block, some endpoints could be forced commit a large - amount of available memory for header fields. - - - An endpoint can use the SETTINGS_MAX_HEADER_LIST_SIZE to advise peers of - limits that might apply on the size of header blocks. This setting is only advisory, so - endpoints MAY choose to send header blocks that exceed this limit and risk having the - request or response being treated as malformed. This setting specific to a connection, - so any request or response could encounter a hop with a lower, unknown limit. An - intermediary can attempt to avoid this problem by passing on values presented by - different peers, but they are not obligated to do so. - - - A server that receives a larger header block than it is willing to handle can send an - HTTP 431 (Request Header Fields Too Large) status code . A - client can discard responses that it cannot process. The header block MUST be processed - to ensure a consistent connection state, unless the connection is closed. - -
-
- -
- - HTTP/2 enables greater use of compression for both header fields () and entity bodies. Compression can allow an attacker to recover - secret data when it is compressed in the same context as data under attacker control. - - - There are demonstrable attacks on compression that exploit the characteristics of the web - (e.g., ). The attacker induces multiple requests containing - varying plaintext, observing the length of the resulting ciphertext in each, which - reveals a shorter length when a guess about the secret is correct. - - - Implementations communicating on a secure channel MUST NOT compress content that includes - both confidential and attacker-controlled data unless separate compression dictionaries - are used for each source of data. Compression MUST NOT be used if the source of data - cannot be reliably determined. Generic stream compression, such as that provided by TLS - MUST NOT be used with HTTP/2 (). - - - Further considerations regarding the compression of header fields are described in . - -
- -
- - Padding within HTTP/2 is not intended as a replacement for general purpose padding, such - as might be provided by TLS. Redundant padding could even be - counterproductive. Correct application can depend on having specific knowledge of the - data that is being padded. - - - To mitigate attacks that rely on compression, disabling or limiting compression might be - preferable to padding as a countermeasure. - - - Padding can be used to obscure the exact size of frame content, and is provided to - mitigate specific attacks within HTTP. For example, attacks where compressed content - includes both attacker-controlled plaintext and secret data (see for example, ). - - - Use of padding can result in less protection than might seem immediately obvious. At - best, padding only makes it more difficult for an attacker to infer length information by - increasing the number of frames an attacker has to observe. Incorrectly implemented - padding schemes can be easily defeated. In particular, randomized padding with a - predictable distribution provides very little protection; similarly, padding payloads to a - fixed size exposes information as payload sizes cross the fixed size boundary, which could - be possible if an attacker can control plaintext. - - - Intermediaries SHOULD retain padding for DATA frames, but MAY drop padding - for HEADERS and PUSH_PROMISE frames. A valid reason for an - intermediary to change the amount of padding of frames is to improve the protections that - padding provides. - -
- -
- - Several characteristics of HTTP/2 provide an observer an opportunity to correlate actions - of a single client or server over time. This includes the value of settings, the manner - in which flow control windows are managed, the way priorities are allocated to streams, - timing of reactions to stimulus, and handling of any optional features. - - - As far as this creates observable differences in behavior, they could be used as a basis - for fingerprinting a specific client, as defined in . - -
-
- -
- - A string for identifying HTTP/2 is entered into the "Application Layer Protocol Negotiation - (ALPN) Protocol IDs" registry established in . - - - This document establishes a registry for frame types, settings, and error codes. These new - registries are entered into a new "Hypertext Transfer Protocol (HTTP) 2 Parameters" section. - - - This document registers the HTTP2-Settings header field for - use in HTTP; and the 421 (Misdirected Request) status code. - - - This document registers the PRI method for use in HTTP, to avoid - collisions with the connection preface. - - -
- - This document creates two registrations for the identification of HTTP/2 in the - "Application Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in . - - - The "h2" string identifies HTTP/2 when used over TLS: - - HTTP/2 over TLS - 0x68 0x32 ("h2") - This document - - - - The "h2c" string identifies HTTP/2 when used over cleartext TCP: - - HTTP/2 over TCP - 0x68 0x32 0x63 ("h2c") - This document - - -
- -
- - This document establishes a registry for HTTP/2 frame type codes. The "HTTP/2 Frame - Type" registry manages an 8-bit space. The "HTTP/2 Frame Type" registry operates under - either of the "IETF Review" or "IESG Approval" policies for - values between 0x00 and 0xef, with values between 0xf0 and 0xff being reserved for - experimental use. - - - New entries in this registry require the following information: - - - A name or label for the frame type. - - - The 8-bit code assigned to the frame type. - - - A reference to a specification that includes a description of the frame layout, - it's semantics and flags that the frame type uses, including any parts of the frame - that are conditionally present based on the value of flags. - - - - - The entries in the following table are registered by this document. - - - Frame Type - Code - Section - DATA0x0 - HEADERS0x1 - PRIORITY0x2 - RST_STREAM0x3 - SETTINGS0x4 - PUSH_PROMISE0x5 - PING0x6 - GOAWAY0x7 - WINDOW_UPDATE0x8 - CONTINUATION0x9 - -
- -
- - This document establishes a registry for HTTP/2 settings. The "HTTP/2 Settings" registry - manages a 16-bit space. The "HTTP/2 Settings" registry operates under the "Expert Review" policy for values in the range from 0x0000 to - 0xefff, with values between and 0xf000 and 0xffff being reserved for experimental use. - - - New registrations are advised to provide the following information: - - - A symbolic name for the setting. Specifying a setting name is optional. - - - The 16-bit code assigned to the setting. - - - An initial value for the setting. - - - An optional reference to a specification that describes the use of the setting. - - - - - An initial set of setting registrations can be found in . - - - Name - Code - Initial Value - Specification - HEADER_TABLE_SIZE - 0x14096 - ENABLE_PUSH - 0x21 - MAX_CONCURRENT_STREAMS - 0x3(infinite) - INITIAL_WINDOW_SIZE - 0x465535 - MAX_FRAME_SIZE - 0x516384 - MAX_HEADER_LIST_SIZE - 0x6(infinite) - - -
- -
- - This document establishes a registry for HTTP/2 error codes. The "HTTP/2 Error Code" - registry manages a 32-bit space. The "HTTP/2 Error Code" registry operates under the - "Expert Review" policy. - - - Registrations for error codes are required to include a description of the error code. An - expert reviewer is advised to examine new registrations for possible duplication with - existing error codes. Use of existing registrations is to be encouraged, but not - mandated. - - - New registrations are advised to provide the following information: - - - A name for the error code. Specifying an error code name is optional. - - - The 32-bit error code value. - - - A brief description of the error code semantics, longer if no detailed specification - is provided. - - - An optional reference for a specification that defines the error code. - - - - - The entries in the following table are registered by this document. - - - Name - Code - Description - Specification - NO_ERROR0x0 - Graceful shutdown - - PROTOCOL_ERROR0x1 - Protocol error detected - - INTERNAL_ERROR0x2 - Implementation fault - - FLOW_CONTROL_ERROR0x3 - Flow control limits exceeded - - SETTINGS_TIMEOUT0x4 - Settings not acknowledged - - STREAM_CLOSED0x5 - Frame received for closed stream - - FRAME_SIZE_ERROR0x6 - Frame size incorrect - - REFUSED_STREAM0x7 - Stream not processed - - CANCEL0x8 - Stream cancelled - - COMPRESSION_ERROR0x9 - Compression state not updated - - CONNECT_ERROR0xa - TCP connection error for CONNECT method - - ENHANCE_YOUR_CALM0xb - Processing capacity exceeded - - INADEQUATE_SECURITY0xc - Negotiated TLS parameters not acceptable - - - -
- -
- - This section registers the HTTP2-Settings header field in the - Permanent Message Header Field Registry. - - - HTTP2-Settings - - - http - - - standard - - - IETF - - - of this document - - - This header field is only used by an HTTP/2 client for Upgrade-based negotiation. - - - -
- -
- - This section registers the PRI method in the HTTP Method - Registry (). - - - PRI - - - No - - - No - - - of this document - - - This method is never used by an actual client. This method will appear to be used - when an HTTP/1.1 server or intermediary attempts to parse an HTTP/2 connection - preface. - - - -
- -
- - This document registers the 421 (Misdirected Request) HTTP Status code in the Hypertext - Transfer Protocol (HTTP) Status Code Registry (). - - - - - 421 - - - Misdirected Request - - - of this document - - - -
- -
- -
- - This document includes substantial input from the following individuals: - - - Adam Langley, Wan-Teh Chang, Jim Morrison, Mark Nottingham, Alyssa Wilk, Costin - Manolache, William Chan, Vitaliy Lvin, Joe Chan, Adam Barth, Ryan Hamilton, Gavin - Peters, Kent Alstad, Kevin Lindsay, Paul Amer, Fan Yang, Jonathan Leighton (SPDY - contributors). - - - Gabriel Montenegro and Willy Tarreau (Upgrade mechanism). - - - William Chan, Salvatore Loreto, Osama Mazahir, Gabriel Montenegro, Jitu Padhye, Roberto - Peon, Rob Trace (Flow control). - - - Mike Bishop (Extensibility). - - - Mark Nottingham, Julian Reschke, James Snell, Jeff Pinner, Mike Bishop, Herve Ruellan - (Substantial editorial contributions). - - - Kari Hurtta, Tatsuhiro Tsujikawa, Greg Wilkins, Poul-Henning Kamp. - - - Alexey Melnikov was an editor of this document during 2013. - - - A substantial proportion of Martin's contribution was supported by Microsoft during his - employment there. - - - -
-
- - - - - - HPACK - Header Compression for HTTP/2 - - - - - - - - - - - - Transmission Control Protocol - - - University of Southern California (USC)/Information Sciences - Institute - - - - - - - - - - - Key words for use in RFCs to Indicate Requirement Levels - - - Harvard University -
sob@harvard.edu
-
- -
- - -
- - - - - HTTP Over TLS - - - - - - - - - - Uniform Resource Identifier (URI): Generic - Syntax - - - - - - - - - - - - The Base16, Base32, and Base64 Data Encodings - - - - - - - - - Guidelines for Writing an IANA Considerations Section in RFCs - - - - - - - - - - - Augmented BNF for Syntax Specifications: ABNF - - - - - - - - - - - The Transport Layer Security (TLS) Protocol Version 1.2 - - - - - - - - - - - Transport Layer Security (TLS) Extensions: Extension Definitions - - - - - - - - - - Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension - - - - - - - - - - - - - TLS Elliptic Curve Cipher Suites with SHA-256/384 and AES Galois - Counter Mode (GCM) - - - - - - - - - - - Digital Signature Standard (DSS) - - NIST - - - - - - - - - Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- - -
- - - - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- - -
- - - Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- -
- - - Hypertext Transfer Protocol (HTTP/1.1): Range Requests - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - World Wide Web Consortium -
ylafon@w3.org
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- -
- - - Hypertext Transfer Protocol (HTTP/1.1): Caching - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - Akamai -
mnot@mnot.net
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- - -
- - - Hypertext Transfer Protocol (HTTP/1.1): Authentication - - Adobe Systems Incorporated -
fielding@gbiv.com
-
- - greenbytes GmbH -
julian.reschke@greenbytes.de
-
- -
- - -
- - - - HTTP State Management Mechanism - - - - - -
- - - - - - TCP Extensions for High Performance - - - - - - - - - - - - Transport Layer Security Protocol Compression Methods - - - - - - - - - Additional HTTP Status Codes - - - - - - - - - - - Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS) - - - - - - - - - - - - - - - AES Galois Counter Mode (GCM) Cipher Suites for TLS - - - - - - - - - - - - HTML5 - - - - - - - - - - - Latest version available at - . - - - - - - - Talking to Yourself for Fun and Profit - - - - - - - - - - - - - - BREACH: Reviving the CRIME Attack - - - - - - - - - - - Registration Procedures for Message Header Fields - - Nine by Nine -
GK-IETF@ninebynine.org
-
- - BEA Systems -
mnot@pobox.com
-
- - HP Labs -
JeffMogul@acm.org
-
- -
- - -
- - - - Recommendations for Secure Use of TLS and DTLS - - - - - - - - - - - - - - - - - - HTTP Alternative Services - - - Akamai - - - Mozilla - - - greenbytes - - - - - - -
- -
- - This section is to be removed by RFC Editor before publication. - - -
- - Renamed Not Authoritative status code to Misdirected Request. - -
- -
- - Pseudo-header fields are now required to appear strictly before regular ones. - - - Restored 1xx series status codes, except 101. - - - Changed frame length field 24-bits. Expanded frame header to 9 octets. Added a setting - to limit the damage. - - - Added a setting to advise peers of header set size limits. - - - Removed segments. - - - Made non-semantic-bearing HEADERS frames illegal in the HTTP mapping. - -
- -
- - Restored extensibility options. - - - Restricting TLS cipher suites to AEAD only. - - - Removing Content-Encoding requirements. - - - Permitting the use of PRIORITY after stream close. - - - Removed ALTSVC frame. - - - Removed BLOCKED frame. - - - Reducing the maximum padding size to 256 octets; removing padding from - CONTINUATION frames. - - - Removed per-frame GZIP compression. - -
- -
- - Added BLOCKED frame (at risk). - - - Simplified priority scheme. - - - Added DATA per-frame GZIP compression. - -
- -
- - Changed "connection header" to "connection preface" to avoid confusion. - - - Added dependency-based stream prioritization. - - - Added "h2c" identifier to distinguish between cleartext and secured HTTP/2. - - - Adding missing padding to PUSH_PROMISE. - - - Integrate ALTSVC frame and supporting text. - - - Dropping requirement on "deflate" Content-Encoding. - - - Improving security considerations around use of compression. - -
- -
- - Adding padding for data frames. - - - Renumbering frame types, error codes, and settings. - - - Adding INADEQUATE_SECURITY error code. - - - Updating TLS usage requirements to 1.2; forbidding TLS compression. - - - Removing extensibility for frames and settings. - - - Changing setting identifier size. - - - Removing the ability to disable flow control. - - - Changing the protocol identification token to "h2". - - - Changing the use of :authority to make it optional and to allow userinfo in non-HTTP - cases. - - - Allowing split on 0x0 for Cookie. - - - Reserved PRI method in HTTP/1.1 to avoid possible future collisions. - -
- -
- - Added cookie crumbling for more efficient header compression. - - - Added header field ordering with the value-concatenation mechanism. - -
- -
- - Marked draft for implementation. - -
- -
- - Adding definition for CONNECT method. - - - Constraining the use of push to safe, cacheable methods with no request body. - - - Changing from :host to :authority to remove any potential confusion. - - - Adding setting for header compression table size. - - - Adding settings acknowledgement. - - - Removing unnecessary and potentially problematic flags from CONTINUATION. - - - Added denial of service considerations. - -
-
- - Marking the draft ready for implementation. - - - Renumbering END_PUSH_PROMISE flag. - - - Editorial clarifications and changes. - -
- -
- - Added CONTINUATION frame for HEADERS and PUSH_PROMISE. - - - PUSH_PROMISE is no longer implicitly prohibited if SETTINGS_MAX_CONCURRENT_STREAMS is - zero. - - - Push expanded to allow all safe methods without a request body. - - - Clarified the use of HTTP header fields in requests and responses. Prohibited HTTP/1.1 - hop-by-hop header fields. - - - Requiring that intermediaries not forward requests with missing or illegal routing - :-headers. - - - Clarified requirements around handling different frames after stream close, stream reset - and GOAWAY. - - - Added more specific prohibitions for sending of different frame types in various stream - states. - - - Making the last received setting value the effective value. - - - Clarified requirements on TLS version, extension and ciphers. - -
- -
- - Committed major restructuring atrocities. - - - Added reference to first header compression draft. - - - Added more formal description of frame lifecycle. - - - Moved END_STREAM (renamed from FINAL) back to HEADERS/DATA. - - - Removed HEADERS+PRIORITY, added optional priority to HEADERS frame. - - - Added PRIORITY frame. - -
- -
- - Added continuations to frames carrying header blocks. - - - Replaced use of "session" with "connection" to avoid confusion with other HTTP stateful - concepts, like cookies. - - - Removed "message". - - - Switched to TLS ALPN from NPN. - - - Editorial changes. - -
- -
- - Added IANA considerations section for frame types, error codes and settings. - - - Removed data frame compression. - - - Added PUSH_PROMISE. - - - Added globally applicable flags to framing. - - - Removed zlib-based header compression mechanism. - - - Updated references. - - - Clarified stream identifier reuse. - - - Removed CREDENTIALS frame and associated mechanisms. - - - Added advice against naive implementation of flow control. - - - Added session header section. - - - Restructured frame header. Removed distinction between data and control frames. - - - Altered flow control properties to include session-level limits. - - - Added note on cacheability of pushed resources and multiple tenant servers. - - - Changed protocol label form based on discussions. - -
- -
- - Changed title throughout. - - - Removed section on Incompatibilities with SPDY draft#2. - - - Changed INTERNAL_ERROR on GOAWAY to have a value of 2 . - - - Replaced abstract and introduction. - - - Added section on starting HTTP/2.0, including upgrade mechanism. - - - Removed unused references. - - - Added flow control principles based on . - -
- -
- - Adopted as base for draft-ietf-httpbis-http2. - - - Updated authors/editors list. - - - Added status note. - -
-
- -
-
- diff --git a/examples/golang.org/x/net/http2/transport.go b/examples/golang.org/x/net/http2/transport.go deleted file mode 100644 index 9d1f2fa..0000000 --- a/examples/golang.org/x/net/http2/transport.go +++ /dev/null @@ -1,2453 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Transport code. - -package http2 - -import ( - "bufio" - "bytes" - "compress/gzip" - "crypto/rand" - "crypto/tls" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "math" - mathrand "math/rand" - "net" - "net/http" - "net/textproto" - "sort" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/http/httpguts" - "golang.org/x/net/http2/hpack" - "golang.org/x/net/idna" -) - -const ( - // transportDefaultConnFlow is how many connection-level flow control - // tokens we give the server at start-up, past the default 64k. - transportDefaultConnFlow = 1 << 30 - - // transportDefaultStreamFlow is how many stream-level flow - // control tokens we announce to the peer, and how many bytes - // we buffer per stream. - transportDefaultStreamFlow = 4 << 20 - - // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send - // a stream-level WINDOW_UPDATE for at a time. - transportDefaultStreamMinRefresh = 4 << 10 - - defaultUserAgent = "Go-http-client/2.0" -) - -// Transport is an HTTP/2 Transport. -// -// A Transport internally caches connections to servers. It is safe -// for concurrent use by multiple goroutines. -type Transport struct { - // DialTLS specifies an optional dial function for creating - // TLS connections for requests. - // - // If DialTLS is nil, tls.Dial is used. - // - // If the returned net.Conn has a ConnectionState method like tls.Conn, - // it will be used to set http.Response.TLS. - DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error) - - // TLSClientConfig specifies the TLS configuration to use with - // tls.Client. If nil, the default configuration is used. - TLSClientConfig *tls.Config - - // ConnPool optionally specifies an alternate connection pool to use. - // If nil, the default is used. - ConnPool ClientConnPool - - // DisableCompression, if true, prevents the Transport from - // requesting compression with an "Accept-Encoding: gzip" - // request header when the Request contains no existing - // Accept-Encoding value. If the Transport requests gzip on - // its own and gets a gzipped response, it's transparently - // decoded in the Response.Body. However, if the user - // explicitly requested gzip it is not automatically - // uncompressed. - DisableCompression bool - - // AllowHTTP, if true, permits HTTP/2 requests using the insecure, - // plain-text "http" scheme. Note that this does not enable h2c support. - AllowHTTP bool - - // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to - // send in the initial settings frame. It is how many bytes - // of response headers are allowed. Unlike the http2 spec, zero here - // means to use a default limit (currently 10MB). If you actually - // want to advertise an ulimited value to the peer, Transport - // interprets the highest possible value here (0xffffffff or 1<<32-1) - // to mean no limit. - MaxHeaderListSize uint32 - - // t1, if non-nil, is the standard library Transport using - // this transport. Its settings are used (but not its - // RoundTrip method, etc). - t1 *http.Transport - - connPoolOnce sync.Once - connPoolOrDef ClientConnPool // non-nil version of ConnPool -} - -func (t *Transport) maxHeaderListSize() uint32 { - if t.MaxHeaderListSize == 0 { - return 10 << 20 - } - if t.MaxHeaderListSize == 0xffffffff { - return 0 - } - return t.MaxHeaderListSize -} - -func (t *Transport) disableCompression() bool { - return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression) -} - -var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6") - -// ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2. -// It requires Go 1.6 or later and returns an error if the net/http package is too old -// or if t1 has already been HTTP/2-enabled. -func ConfigureTransport(t1 *http.Transport) error { - _, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go - return err -} - -func (t *Transport) connPool() ClientConnPool { - t.connPoolOnce.Do(t.initConnPool) - return t.connPoolOrDef -} - -func (t *Transport) initConnPool() { - if t.ConnPool != nil { - t.connPoolOrDef = t.ConnPool - } else { - t.connPoolOrDef = &clientConnPool{t: t} - } -} - -// ClientConn is the state of a single HTTP/2 client connection to an -// HTTP/2 server. -type ClientConn struct { - t *Transport - tconn net.Conn // usually *tls.Conn, except specialized impls - tlsState *tls.ConnectionState // nil only for specialized impls - singleUse bool // whether being used for a single http.Request - - // readLoop goroutine fields: - readerDone chan struct{} // closed on error - readerErr error // set before readerDone is closed - - idleTimeout time.Duration // or 0 for never - idleTimer *time.Timer - - mu sync.Mutex // guards following - cond *sync.Cond // hold mu; broadcast on flow/closed changes - flow flow // our conn-level flow control quota (cs.flow is per stream) - inflow flow // peer's conn-level flow control - closing bool - closed bool - wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back - goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received - goAwayDebug string // goAway frame's debug data, retained as a string - streams map[uint32]*clientStream // client-initiated - nextStreamID uint32 - pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams - pings map[[8]byte]chan struct{} // in flight ping data to notification channel - bw *bufio.Writer - br *bufio.Reader - fr *Framer - lastActive time.Time - // Settings from peer: (also guarded by mu) - maxFrameSize uint32 - maxConcurrentStreams uint32 - peerMaxHeaderListSize uint64 - initialWindowSize uint32 - - hbuf bytes.Buffer // HPACK encoder writes into this - henc *hpack.Encoder - freeBuf [][]byte - - wmu sync.Mutex // held while writing; acquire AFTER mu if holding both - werr error // first write error that has occurred -} - -// clientStream is the state for a single HTTP/2 stream. One of these -// is created for each Transport.RoundTrip call. -type clientStream struct { - cc *ClientConn - req *http.Request - trace *clientTrace // or nil - ID uint32 - resc chan resAndError - bufPipe pipe // buffered pipe with the flow-controlled response payload - startedWrite bool // started request body write; guarded by cc.mu - requestedGzip bool - on100 func() // optional code to run if get a 100 continue response - - flow flow // guarded by cc.mu - inflow flow // guarded by cc.mu - bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read - readErr error // sticky read error; owned by transportResponseBody.Read - stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu - didReset bool // whether we sent a RST_STREAM to the server; guarded by cc.mu - - peerReset chan struct{} // closed on peer reset - resetErr error // populated before peerReset is closed - - done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu - - // owned by clientConnReadLoop: - firstByte bool // got the first response byte - pastHeaders bool // got first MetaHeadersFrame (actual headers) - pastTrailers bool // got optional second MetaHeadersFrame (trailers) - num1xx uint8 // number of 1xx responses seen - - trailer http.Header // accumulated trailers - resTrailer *http.Header // client's Response.Trailer -} - -// awaitRequestCancel waits for the user to cancel a request or for the done -// channel to be signaled. A non-nil error is returned only if the request was -// canceled. -func awaitRequestCancel(req *http.Request, done <-chan struct{}) error { - ctx := reqContext(req) - if req.Cancel == nil && ctx.Done() == nil { - return nil - } - select { - case <-req.Cancel: - return errRequestCanceled - case <-ctx.Done(): - return ctx.Err() - case <-done: - return nil - } -} - -var got1xxFuncForTests func(int, textproto.MIMEHeader) error - -// get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func, -// if any. It returns nil if not set or if the Go version is too old. -func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error { - if fn := got1xxFuncForTests; fn != nil { - return fn - } - return traceGot1xxResponseFunc(cs.trace) -} - -// awaitRequestCancel waits for the user to cancel a request, its context to -// expire, or for the request to be done (any way it might be removed from the -// cc.streams map: peer reset, successful completion, TCP connection breakage, -// etc). If the request is canceled, then cs will be canceled and closed. -func (cs *clientStream) awaitRequestCancel(req *http.Request) { - if err := awaitRequestCancel(req, cs.done); err != nil { - cs.cancelStream() - cs.bufPipe.CloseWithError(err) - } -} - -func (cs *clientStream) cancelStream() { - cc := cs.cc - cc.mu.Lock() - didReset := cs.didReset - cs.didReset = true - cc.mu.Unlock() - - if !didReset { - cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) - cc.forgetStreamID(cs.ID) - } -} - -// checkResetOrDone reports any error sent in a RST_STREAM frame by the -// server, or errStreamClosed if the stream is complete. -func (cs *clientStream) checkResetOrDone() error { - select { - case <-cs.peerReset: - return cs.resetErr - case <-cs.done: - return errStreamClosed - default: - return nil - } -} - -func (cs *clientStream) getStartedWrite() bool { - cc := cs.cc - cc.mu.Lock() - defer cc.mu.Unlock() - return cs.startedWrite -} - -func (cs *clientStream) abortRequestBodyWrite(err error) { - if err == nil { - panic("nil error") - } - cc := cs.cc - cc.mu.Lock() - cs.stopReqBody = err - cc.cond.Broadcast() - cc.mu.Unlock() -} - -type stickyErrWriter struct { - w io.Writer - err *error -} - -func (sew stickyErrWriter) Write(p []byte) (n int, err error) { - if *sew.err != nil { - return 0, *sew.err - } - n, err = sew.w.Write(p) - *sew.err = err - return -} - -// noCachedConnError is the concrete type of ErrNoCachedConn, which -// needs to be detected by net/http regardless of whether it's its -// bundled version (in h2_bundle.go with a rewritten type name) or -// from a user's x/net/http2. As such, as it has a unique method name -// (IsHTTP2NoCachedConnError) that net/http sniffs for via func -// isNoCachedConnError. -type noCachedConnError struct{} - -func (noCachedConnError) IsHTTP2NoCachedConnError() {} -func (noCachedConnError) Error() string { return "http2: no cached connection was available" } - -// isNoCachedConnError reports whether err is of type noCachedConnError -// or its equivalent renamed type in net/http2's h2_bundle.go. Both types -// may coexist in the same running program. -func isNoCachedConnError(err error) bool { - _, ok := err.(interface{ IsHTTP2NoCachedConnError() }) - return ok -} - -var ErrNoCachedConn error = noCachedConnError{} - -// RoundTripOpt are options for the Transport.RoundTripOpt method. -type RoundTripOpt struct { - // OnlyCachedConn controls whether RoundTripOpt may - // create a new TCP connection. If set true and - // no cached connection is available, RoundTripOpt - // will return ErrNoCachedConn. - OnlyCachedConn bool -} - -func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - return t.RoundTripOpt(req, RoundTripOpt{}) -} - -// authorityAddr returns a given authority (a host/IP, or host:port / ip:port) -// and returns a host:port. The port 443 is added if needed. -func authorityAddr(scheme string, authority string) (addr string) { - host, port, err := net.SplitHostPort(authority) - if err != nil { // authority didn't have a port - port = "443" - if scheme == "http" { - port = "80" - } - host = authority - } - if a, err := idna.ToASCII(host); err == nil { - host = a - } - // IPv6 address literal, without a port: - if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { - return host + ":" + port - } - return net.JoinHostPort(host, port) -} - -// RoundTripOpt is like RoundTrip, but takes options. -func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) { - if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) { - return nil, errors.New("http2: unsupported scheme") - } - - addr := authorityAddr(req.URL.Scheme, req.URL.Host) - for retry := 0; ; retry++ { - cc, err := t.connPool().GetClientConn(req, addr) - if err != nil { - t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err) - return nil, err - } - traceGotConn(req, cc) - res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req) - if err != nil && retry <= 6 { - if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil { - // After the first retry, do exponential backoff with 10% jitter. - if retry == 0 { - continue - } - backoff := float64(uint(1) << (uint(retry) - 1)) - backoff += backoff * (0.1 * mathrand.Float64()) - select { - case <-time.After(time.Second * time.Duration(backoff)): - continue - case <-reqContext(req).Done(): - return nil, reqContext(req).Err() - } - } - } - if err != nil { - t.vlogf("RoundTrip failure: %v", err) - return nil, err - } - return res, nil - } -} - -// CloseIdleConnections closes any connections which were previously -// connected from previous requests but are now sitting idle. -// It does not interrupt any connections currently in use. -func (t *Transport) CloseIdleConnections() { - if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok { - cp.closeIdleConnections() - } -} - -var ( - errClientConnClosed = errors.New("http2: client conn is closed") - errClientConnUnusable = errors.New("http2: client conn not usable") - errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY") -) - -// shouldRetryRequest is called by RoundTrip when a request fails to get -// response headers. It is always called with a non-nil error. -// It returns either a request to retry (either the same request, or a -// modified clone), or an error if the request can't be replayed. -func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) { - if !canRetryError(err) { - return nil, err - } - // If the Body is nil (or http.NoBody), it's safe to reuse - // this request and its Body. - if req.Body == nil || reqBodyIsNoBody(req.Body) { - return req, nil - } - - // If the request body can be reset back to its original - // state via the optional req.GetBody, do that. - getBody := reqGetBody(req) // Go 1.8: getBody = req.GetBody - if getBody != nil { - // TODO: consider a req.Body.Close here? or audit that all caller paths do? - body, err := getBody() - if err != nil { - return nil, err - } - newReq := *req - newReq.Body = body - return &newReq, nil - } - - // The Request.Body can't reset back to the beginning, but we - // don't seem to have started to read from it yet, so reuse - // the request directly. The "afterBodyWrite" means the - // bodyWrite process has started, which becomes true before - // the first Read. - if !afterBodyWrite { - return req, nil - } - - return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err) -} - -func canRetryError(err error) bool { - if err == errClientConnUnusable || err == errClientConnGotGoAway { - return true - } - if se, ok := err.(StreamError); ok { - return se.Code == ErrCodeRefusedStream - } - return false -} - -func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host)) - if err != nil { - return nil, err - } - return t.newClientConn(tconn, singleUse) -} - -func (t *Transport) newTLSConfig(host string) *tls.Config { - cfg := new(tls.Config) - if t.TLSClientConfig != nil { - *cfg = *cloneTLSConfig(t.TLSClientConfig) - } - if !strSliceContains(cfg.NextProtos, NextProtoTLS) { - cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) - } - if cfg.ServerName == "" { - cfg.ServerName = host - } - return cfg -} - -func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) { - if t.DialTLS != nil { - return t.DialTLS - } - return t.dialTLSDefault -} - -func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) { - cn, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - if err := cn.Handshake(); err != nil { - return nil, err - } - if !cfg.InsecureSkipVerify { - if err := cn.VerifyHostname(cfg.ServerName); err != nil { - return nil, err - } - } - state := cn.ConnectionState() - if p := state.NegotiatedProtocol; p != NextProtoTLS { - return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS) - } - if !state.NegotiatedProtocolIsMutual { - return nil, errors.New("http2: could not negotiate protocol mutually") - } - return cn, nil -} - -// disableKeepAlives reports whether connections should be closed as -// soon as possible after handling the first request. -func (t *Transport) disableKeepAlives() bool { - return t.t1 != nil && t.t1.DisableKeepAlives -} - -func (t *Transport) expectContinueTimeout() time.Duration { - if t.t1 == nil { - return 0 - } - return transportExpectContinueTimeout(t.t1) -} - -func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { - return t.newClientConn(c, false) -} - -func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) { - cc := &ClientConn{ - t: t, - tconn: c, - readerDone: make(chan struct{}), - nextStreamID: 1, - maxFrameSize: 16 << 10, // spec default - initialWindowSize: 65535, // spec default - maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough. - peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead. - streams: make(map[uint32]*clientStream), - singleUse: singleUse, - wantSettingsAck: true, - pings: make(map[[8]byte]chan struct{}), - } - if d := t.idleConnTimeout(); d != 0 { - cc.idleTimeout = d - cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout) - } - if VerboseLogs { - t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr()) - } - - cc.cond = sync.NewCond(&cc.mu) - cc.flow.add(int32(initialWindowSize)) - - // TODO: adjust this writer size to account for frame size + - // MTU + crypto/tls record padding. - cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr}) - cc.br = bufio.NewReader(c) - cc.fr = NewFramer(cc.bw, cc.br) - cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) - cc.fr.MaxHeaderListSize = t.maxHeaderListSize() - - // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on - // henc in response to SETTINGS frames? - cc.henc = hpack.NewEncoder(&cc.hbuf) - - if t.AllowHTTP { - cc.nextStreamID = 3 - } - - if cs, ok := c.(connectionStater); ok { - state := cs.ConnectionState() - cc.tlsState = &state - } - - initialSettings := []Setting{ - {ID: SettingEnablePush, Val: 0}, - {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow}, - } - if max := t.maxHeaderListSize(); max != 0 { - initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max}) - } - - cc.bw.Write(clientPreface) - cc.fr.WriteSettings(initialSettings...) - cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow) - cc.inflow.add(transportDefaultConnFlow + initialWindowSize) - cc.bw.Flush() - if cc.werr != nil { - return nil, cc.werr - } - - go cc.readLoop() - return cc, nil -} - -func (cc *ClientConn) setGoAway(f *GoAwayFrame) { - cc.mu.Lock() - defer cc.mu.Unlock() - - old := cc.goAway - cc.goAway = f - - // Merge the previous and current GoAway error frames. - if cc.goAwayDebug == "" { - cc.goAwayDebug = string(f.DebugData()) - } - if old != nil && old.ErrCode != ErrCodeNo { - cc.goAway.ErrCode = old.ErrCode - } - last := f.LastStreamID - for streamID, cs := range cc.streams { - if streamID > last { - select { - case cs.resc <- resAndError{err: errClientConnGotGoAway}: - default: - } - } - } -} - -// CanTakeNewRequest reports whether the connection can take a new request, -// meaning it has not been closed or received or sent a GOAWAY. -func (cc *ClientConn) CanTakeNewRequest() bool { - cc.mu.Lock() - defer cc.mu.Unlock() - return cc.canTakeNewRequestLocked() -} - -// clientConnIdleState describes the suitability of a client -// connection to initiate a new RoundTrip request. -type clientConnIdleState struct { - canTakeNewRequest bool - freshConn bool // whether it's unused by any previous request -} - -func (cc *ClientConn) idleState() clientConnIdleState { - cc.mu.Lock() - defer cc.mu.Unlock() - return cc.idleStateLocked() -} - -func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { - if cc.singleUse && cc.nextStreamID > 1 { - return - } - st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && - int64(cc.nextStreamID)+int64(cc.pendingRequests) < math.MaxInt32 - st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest - return -} - -func (cc *ClientConn) canTakeNewRequestLocked() bool { - st := cc.idleStateLocked() - return st.canTakeNewRequest -} - -// onIdleTimeout is called from a time.AfterFunc goroutine. It will -// only be called when we're idle, but because we're coming from a new -// goroutine, there could be a new request coming in at the same time, -// so this simply calls the synchronized closeIfIdle to shut down this -// connection. The timer could just call closeIfIdle, but this is more -// clear. -func (cc *ClientConn) onIdleTimeout() { - cc.closeIfIdle() -} - -func (cc *ClientConn) closeIfIdle() { - cc.mu.Lock() - if len(cc.streams) > 0 { - cc.mu.Unlock() - return - } - cc.closed = true - nextID := cc.nextStreamID - // TODO: do clients send GOAWAY too? maybe? Just Close: - cc.mu.Unlock() - - if VerboseLogs { - cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2) - } - cc.tconn.Close() -} - -var shutdownEnterWaitStateHook = func() {} - -// Shutdown gracefully close the client connection, waiting for running streams to complete. -// Public implementation is in go17.go and not_go17.go -func (cc *ClientConn) shutdown(ctx contextContext) error { - if err := cc.sendGoAway(); err != nil { - return err - } - // Wait for all in-flight streams to complete or connection to close - done := make(chan error, 1) - cancelled := false // guarded by cc.mu - go func() { - cc.mu.Lock() - defer cc.mu.Unlock() - for { - if len(cc.streams) == 0 || cc.closed { - cc.closed = true - done <- cc.tconn.Close() - break - } - if cancelled { - break - } - cc.cond.Wait() - } - }() - shutdownEnterWaitStateHook() - select { - case err := <-done: - return err - case <-ctx.Done(): - cc.mu.Lock() - // Free the goroutine above - cancelled = true - cc.cond.Broadcast() - cc.mu.Unlock() - return ctx.Err() - } -} - -func (cc *ClientConn) sendGoAway() error { - cc.mu.Lock() - defer cc.mu.Unlock() - cc.wmu.Lock() - defer cc.wmu.Unlock() - if cc.closing { - // GOAWAY sent already - return nil - } - // Send a graceful shutdown frame to server - maxStreamID := cc.nextStreamID - if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil { - return err - } - if err := cc.bw.Flush(); err != nil { - return err - } - // Prevent new requests - cc.closing = true - return nil -} - -// Close closes the client connection immediately. -// -// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. -func (cc *ClientConn) Close() error { - cc.mu.Lock() - defer cc.cond.Broadcast() - defer cc.mu.Unlock() - err := errors.New("http2: client connection force closed via ClientConn.Close") - for id, cs := range cc.streams { - select { - case cs.resc <- resAndError{err: err}: - default: - } - cs.bufPipe.CloseWithError(err) - delete(cc.streams, id) - } - cc.closed = true - return cc.tconn.Close() -} - -const maxAllocFrameSize = 512 << 10 - -// frameBuffer returns a scratch buffer suitable for writing DATA frames. -// They're capped at the min of the peer's max frame size or 512KB -// (kinda arbitrarily), but definitely capped so we don't allocate 4GB -// bufers. -func (cc *ClientConn) frameScratchBuffer() []byte { - cc.mu.Lock() - size := cc.maxFrameSize - if size > maxAllocFrameSize { - size = maxAllocFrameSize - } - for i, buf := range cc.freeBuf { - if len(buf) >= int(size) { - cc.freeBuf[i] = nil - cc.mu.Unlock() - return buf[:size] - } - } - cc.mu.Unlock() - return make([]byte, size) -} - -func (cc *ClientConn) putFrameScratchBuffer(buf []byte) { - cc.mu.Lock() - defer cc.mu.Unlock() - const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate. - if len(cc.freeBuf) < maxBufs { - cc.freeBuf = append(cc.freeBuf, buf) - return - } - for i, old := range cc.freeBuf { - if old == nil { - cc.freeBuf[i] = buf - return - } - } - // forget about it. -} - -// errRequestCanceled is a copy of net/http's errRequestCanceled because it's not -// exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests. -var errRequestCanceled = errors.New("net/http: request canceled") - -func commaSeparatedTrailers(req *http.Request) (string, error) { - keys := make([]string, 0, len(req.Trailer)) - for k := range req.Trailer { - k = http.CanonicalHeaderKey(k) - switch k { - case "Transfer-Encoding", "Trailer", "Content-Length": - return "", &badStringError{"invalid Trailer key", k} - } - keys = append(keys, k) - } - if len(keys) > 0 { - sort.Strings(keys) - return strings.Join(keys, ","), nil - } - return "", nil -} - -func (cc *ClientConn) responseHeaderTimeout() time.Duration { - if cc.t.t1 != nil { - return cc.t.t1.ResponseHeaderTimeout - } - // No way to do this (yet?) with just an http2.Transport. Probably - // no need. Request.Cancel this is the new way. We only need to support - // this for compatibility with the old http.Transport fields when - // we're doing transparent http2. - return 0 -} - -// checkConnHeaders checks whether req has any invalid connection-level headers. -// per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields. -// Certain headers are special-cased as okay but not transmitted later. -func checkConnHeaders(req *http.Request) error { - if v := req.Header.Get("Upgrade"); v != "" { - return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"]) - } - if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") { - return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv) - } - if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) { - return fmt.Errorf("http2: invalid Connection request header: %q", vv) - } - return nil -} - -// actualContentLength returns a sanitized version of -// req.ContentLength, where 0 actually means zero (not unknown) and -1 -// means unknown. -func actualContentLength(req *http.Request) int64 { - if req.Body == nil || reqBodyIsNoBody(req.Body) { - return 0 - } - if req.ContentLength != 0 { - return req.ContentLength - } - return -1 -} - -func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { - resp, _, err := cc.roundTrip(req) - return resp, err -} - -func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) { - if err := checkConnHeaders(req); err != nil { - return nil, false, err - } - if cc.idleTimer != nil { - cc.idleTimer.Stop() - } - - trailers, err := commaSeparatedTrailers(req) - if err != nil { - return nil, false, err - } - hasTrailers := trailers != "" - - cc.mu.Lock() - if err := cc.awaitOpenSlotForRequest(req); err != nil { - cc.mu.Unlock() - return nil, false, err - } - - body := req.Body - contentLen := actualContentLength(req) - hasBody := contentLen != 0 - - // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere? - var requestedGzip bool - if !cc.t.disableCompression() && - req.Header.Get("Accept-Encoding") == "" && - req.Header.Get("Range") == "" && - req.Method != "HEAD" { - // Request gzip only, not deflate. Deflate is ambiguous and - // not as universally supported anyway. - // See: http://www.gzip.org/zlib/zlib_faq.html#faq38 - // - // Note that we don't request this for HEAD requests, - // due to a bug in nginx: - // http://trac.nginx.org/nginx/ticket/358 - // https://golang.org/issue/5522 - // - // We don't request gzip if the request is for a range, since - // auto-decoding a portion of a gzipped document will just fail - // anyway. See https://golang.org/issue/8923 - requestedGzip = true - } - - // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is - // sent by writeRequestBody below, along with any Trailers, - // again in form HEADERS{1}, CONTINUATION{0,}) - hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen) - if err != nil { - cc.mu.Unlock() - return nil, false, err - } - - cs := cc.newStream() - cs.req = req - cs.trace = requestTrace(req) - cs.requestedGzip = requestedGzip - bodyWriter := cc.t.getBodyWriterState(cs, body) - cs.on100 = bodyWriter.on100 - - cc.wmu.Lock() - endStream := !hasBody && !hasTrailers - werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs) - cc.wmu.Unlock() - traceWroteHeaders(cs.trace) - cc.mu.Unlock() - - if werr != nil { - if hasBody { - req.Body.Close() // per RoundTripper contract - bodyWriter.cancel() - } - cc.forgetStreamID(cs.ID) - // Don't bother sending a RST_STREAM (our write already failed; - // no need to keep writing) - traceWroteRequest(cs.trace, werr) - return nil, false, werr - } - - var respHeaderTimer <-chan time.Time - if hasBody { - bodyWriter.scheduleBodyWrite() - } else { - traceWroteRequest(cs.trace, nil) - if d := cc.responseHeaderTimeout(); d != 0 { - timer := time.NewTimer(d) - defer timer.Stop() - respHeaderTimer = timer.C - } - } - - readLoopResCh := cs.resc - bodyWritten := false - ctx := reqContext(req) - - handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) { - res := re.res - if re.err != nil || res.StatusCode > 299 { - // On error or status code 3xx, 4xx, 5xx, etc abort any - // ongoing write, assuming that the server doesn't care - // about our request body. If the server replied with 1xx or - // 2xx, however, then assume the server DOES potentially - // want our body (e.g. full-duplex streaming: - // golang.org/issue/13444). If it turns out the server - // doesn't, they'll RST_STREAM us soon enough. This is a - // heuristic to avoid adding knobs to Transport. Hopefully - // we can keep it. - bodyWriter.cancel() - cs.abortRequestBodyWrite(errStopReqBodyWrite) - } - if re.err != nil { - cc.forgetStreamID(cs.ID) - return nil, cs.getStartedWrite(), re.err - } - res.Request = req - res.TLS = cc.tlsState - return res, false, nil - } - - for { - select { - case re := <-readLoopResCh: - return handleReadLoopResponse(re) - case <-respHeaderTimer: - if !hasBody || bodyWritten { - cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) - } else { - bodyWriter.cancel() - cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) - } - cc.forgetStreamID(cs.ID) - return nil, cs.getStartedWrite(), errTimeout - case <-ctx.Done(): - if !hasBody || bodyWritten { - cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) - } else { - bodyWriter.cancel() - cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) - } - cc.forgetStreamID(cs.ID) - return nil, cs.getStartedWrite(), ctx.Err() - case <-req.Cancel: - if !hasBody || bodyWritten { - cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) - } else { - bodyWriter.cancel() - cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel) - } - cc.forgetStreamID(cs.ID) - return nil, cs.getStartedWrite(), errRequestCanceled - case <-cs.peerReset: - // processResetStream already removed the - // stream from the streams map; no need for - // forgetStreamID. - return nil, cs.getStartedWrite(), cs.resetErr - case err := <-bodyWriter.resc: - // Prefer the read loop's response, if available. Issue 16102. - select { - case re := <-readLoopResCh: - return handleReadLoopResponse(re) - default: - } - if err != nil { - return nil, cs.getStartedWrite(), err - } - bodyWritten = true - if d := cc.responseHeaderTimeout(); d != 0 { - timer := time.NewTimer(d) - defer timer.Stop() - respHeaderTimer = timer.C - } - } - } -} - -// awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams. -// Must hold cc.mu. -func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error { - var waitingForConn chan struct{} - var waitingForConnErr error // guarded by cc.mu - for { - cc.lastActive = time.Now() - if cc.closed || !cc.canTakeNewRequestLocked() { - if waitingForConn != nil { - close(waitingForConn) - } - return errClientConnUnusable - } - if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) { - if waitingForConn != nil { - close(waitingForConn) - } - return nil - } - // Unfortunately, we cannot wait on a condition variable and channel at - // the same time, so instead, we spin up a goroutine to check if the - // request is canceled while we wait for a slot to open in the connection. - if waitingForConn == nil { - waitingForConn = make(chan struct{}) - go func() { - if err := awaitRequestCancel(req, waitingForConn); err != nil { - cc.mu.Lock() - waitingForConnErr = err - cc.cond.Broadcast() - cc.mu.Unlock() - } - }() - } - cc.pendingRequests++ - cc.cond.Wait() - cc.pendingRequests-- - if waitingForConnErr != nil { - return waitingForConnErr - } - } -} - -// requires cc.wmu be held -func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error { - first := true // first frame written (HEADERS is first, then CONTINUATION) - for len(hdrs) > 0 && cc.werr == nil { - chunk := hdrs - if len(chunk) > maxFrameSize { - chunk = chunk[:maxFrameSize] - } - hdrs = hdrs[len(chunk):] - endHeaders := len(hdrs) == 0 - if first { - cc.fr.WriteHeaders(HeadersFrameParam{ - StreamID: streamID, - BlockFragment: chunk, - EndStream: endStream, - EndHeaders: endHeaders, - }) - first = false - } else { - cc.fr.WriteContinuation(streamID, endHeaders, chunk) - } - } - // TODO(bradfitz): this Flush could potentially block (as - // could the WriteHeaders call(s) above), which means they - // wouldn't respond to Request.Cancel being readable. That's - // rare, but this should probably be in a goroutine. - cc.bw.Flush() - return cc.werr -} - -// internal error values; they don't escape to callers -var ( - // abort request body write; don't send cancel - errStopReqBodyWrite = errors.New("http2: aborting request body write") - - // abort request body write, but send stream reset of cancel. - errStopReqBodyWriteAndCancel = errors.New("http2: canceling request") -) - -func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) { - cc := cs.cc - sentEnd := false // whether we sent the final DATA frame w/ END_STREAM - buf := cc.frameScratchBuffer() - defer cc.putFrameScratchBuffer(buf) - - defer func() { - traceWroteRequest(cs.trace, err) - // TODO: write h12Compare test showing whether - // Request.Body is closed by the Transport, - // and in multiple cases: server replies <=299 and >299 - // while still writing request body - cerr := bodyCloser.Close() - if err == nil { - err = cerr - } - }() - - req := cs.req - hasTrailers := req.Trailer != nil - - var sawEOF bool - for !sawEOF { - n, err := body.Read(buf) - if err == io.EOF { - sawEOF = true - err = nil - } else if err != nil { - return err - } - - remain := buf[:n] - for len(remain) > 0 && err == nil { - var allowed int32 - allowed, err = cs.awaitFlowControl(len(remain)) - switch { - case err == errStopReqBodyWrite: - return err - case err == errStopReqBodyWriteAndCancel: - cc.writeStreamReset(cs.ID, ErrCodeCancel, nil) - return err - case err != nil: - return err - } - cc.wmu.Lock() - data := remain[:allowed] - remain = remain[allowed:] - sentEnd = sawEOF && len(remain) == 0 && !hasTrailers - err = cc.fr.WriteData(cs.ID, sentEnd, data) - if err == nil { - // TODO(bradfitz): this flush is for latency, not bandwidth. - // Most requests won't need this. Make this opt-in or - // opt-out? Use some heuristic on the body type? Nagel-like - // timers? Based on 'n'? Only last chunk of this for loop, - // unless flow control tokens are low? For now, always. - // If we change this, see comment below. - err = cc.bw.Flush() - } - cc.wmu.Unlock() - } - if err != nil { - return err - } - } - - if sentEnd { - // Already sent END_STREAM (which implies we have no - // trailers) and flushed, because currently all - // WriteData frames above get a flush. So we're done. - return nil - } - - var trls []byte - if hasTrailers { - cc.mu.Lock() - trls, err = cc.encodeTrailers(req) - cc.mu.Unlock() - if err != nil { - cc.writeStreamReset(cs.ID, ErrCodeInternal, err) - cc.forgetStreamID(cs.ID) - return err - } - } - - cc.mu.Lock() - maxFrameSize := int(cc.maxFrameSize) - cc.mu.Unlock() - - cc.wmu.Lock() - defer cc.wmu.Unlock() - - // Two ways to send END_STREAM: either with trailers, or - // with an empty DATA frame. - if len(trls) > 0 { - err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls) - } else { - err = cc.fr.WriteData(cs.ID, true, nil) - } - if ferr := cc.bw.Flush(); ferr != nil && err == nil { - err = ferr - } - return err -} - -// awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow -// control tokens from the server. -// It returns either the non-zero number of tokens taken or an error -// if the stream is dead. -func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) { - cc := cs.cc - cc.mu.Lock() - defer cc.mu.Unlock() - for { - if cc.closed { - return 0, errClientConnClosed - } - if cs.stopReqBody != nil { - return 0, cs.stopReqBody - } - if err := cs.checkResetOrDone(); err != nil { - return 0, err - } - if a := cs.flow.available(); a > 0 { - take := a - if int(take) > maxBytes { - - take = int32(maxBytes) // can't truncate int; take is int32 - } - if take > int32(cc.maxFrameSize) { - take = int32(cc.maxFrameSize) - } - cs.flow.take(take) - return take, nil - } - cc.cond.Wait() - } -} - -type badStringError struct { - what string - str string -} - -func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } - -// requires cc.mu be held. -func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { - cc.hbuf.Reset() - - host := req.Host - if host == "" { - host = req.URL.Host - } - host, err := httpguts.PunycodeHostPort(host) - if err != nil { - return nil, err - } - - var path string - if req.Method != "CONNECT" { - path = req.URL.RequestURI() - if !validPseudoPath(path) { - orig := path - path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host) - if !validPseudoPath(path) { - if req.URL.Opaque != "" { - return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque) - } else { - return nil, fmt.Errorf("invalid request :path %q", orig) - } - } - } - } - - // Check for any invalid headers and return an error before we - // potentially pollute our hpack state. (We want to be able to - // continue to reuse the hpack encoder for future requests) - for k, vv := range req.Header { - if !httpguts.ValidHeaderFieldName(k) { - return nil, fmt.Errorf("invalid HTTP header name %q", k) - } - for _, v := range vv { - if !httpguts.ValidHeaderFieldValue(v) { - return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k) - } - } - } - - enumerateHeaders := func(f func(name, value string)) { - // 8.1.2.3 Request Pseudo-Header Fields - // The :path pseudo-header field includes the path and query parts of the - // target URI (the path-absolute production and optionally a '?' character - // followed by the query production (see Sections 3.3 and 3.4 of - // [RFC3986]). - f(":authority", host) - f(":method", req.Method) - if req.Method != "CONNECT" { - f(":path", path) - f(":scheme", req.URL.Scheme) - } - if trailers != "" { - f("trailer", trailers) - } - - var didUA bool - for k, vv := range req.Header { - if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") { - // Host is :authority, already sent. - // Content-Length is automatic, set below. - continue - } else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") || - strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") || - strings.EqualFold(k, "keep-alive") { - // Per 8.1.2.2 Connection-Specific Header - // Fields, don't send connection-specific - // fields. We have already checked if any - // are error-worthy so just ignore the rest. - continue - } else if strings.EqualFold(k, "user-agent") { - // Match Go's http1 behavior: at most one - // User-Agent. If set to nil or empty string, - // then omit it. Otherwise if not mentioned, - // include the default (below). - didUA = true - if len(vv) < 1 { - continue - } - vv = vv[:1] - if vv[0] == "" { - continue - } - - } - - for _, v := range vv { - f(k, v) - } - } - if shouldSendReqContentLength(req.Method, contentLength) { - f("content-length", strconv.FormatInt(contentLength, 10)) - } - if addGzipHeader { - f("accept-encoding", "gzip") - } - if !didUA { - f("user-agent", defaultUserAgent) - } - } - - // Do a first pass over the headers counting bytes to ensure - // we don't exceed cc.peerMaxHeaderListSize. This is done as a - // separate pass before encoding the headers to prevent - // modifying the hpack state. - hlSize := uint64(0) - enumerateHeaders(func(name, value string) { - hf := hpack.HeaderField{Name: name, Value: value} - hlSize += uint64(hf.Size()) - }) - - if hlSize > cc.peerMaxHeaderListSize { - return nil, errRequestHeaderListSize - } - - trace := requestTrace(req) - traceHeaders := traceHasWroteHeaderField(trace) - - // Header list size is ok. Write the headers. - enumerateHeaders(func(name, value string) { - name = strings.ToLower(name) - cc.writeHeader(name, value) - if traceHeaders { - traceWroteHeaderField(trace, name, value) - } - }) - - return cc.hbuf.Bytes(), nil -} - -// shouldSendReqContentLength reports whether the http2.Transport should send -// a "content-length" request header. This logic is basically a copy of the net/http -// transferWriter.shouldSendContentLength. -// The contentLength is the corrected contentLength (so 0 means actually 0, not unknown). -// -1 means unknown. -func shouldSendReqContentLength(method string, contentLength int64) bool { - if contentLength > 0 { - return true - } - if contentLength < 0 { - return false - } - // For zero bodies, whether we send a content-length depends on the method. - // It also kinda doesn't matter for http2 either way, with END_STREAM. - switch method { - case "POST", "PUT", "PATCH": - return true - default: - return false - } -} - -// requires cc.mu be held. -func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) { - cc.hbuf.Reset() - - hlSize := uint64(0) - for k, vv := range req.Trailer { - for _, v := range vv { - hf := hpack.HeaderField{Name: k, Value: v} - hlSize += uint64(hf.Size()) - } - } - if hlSize > cc.peerMaxHeaderListSize { - return nil, errRequestHeaderListSize - } - - for k, vv := range req.Trailer { - // Transfer-Encoding, etc.. have already been filtered at the - // start of RoundTrip - lowKey := strings.ToLower(k) - for _, v := range vv { - cc.writeHeader(lowKey, v) - } - } - return cc.hbuf.Bytes(), nil -} - -func (cc *ClientConn) writeHeader(name, value string) { - if VerboseLogs { - log.Printf("http2: Transport encoding header %q = %q", name, value) - } - cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) -} - -type resAndError struct { - res *http.Response - err error -} - -// requires cc.mu be held. -func (cc *ClientConn) newStream() *clientStream { - cs := &clientStream{ - cc: cc, - ID: cc.nextStreamID, - resc: make(chan resAndError, 1), - peerReset: make(chan struct{}), - done: make(chan struct{}), - } - cs.flow.add(int32(cc.initialWindowSize)) - cs.flow.setConnFlow(&cc.flow) - cs.inflow.add(transportDefaultStreamFlow) - cs.inflow.setConnFlow(&cc.inflow) - cc.nextStreamID += 2 - cc.streams[cs.ID] = cs - return cs -} - -func (cc *ClientConn) forgetStreamID(id uint32) { - cc.streamByID(id, true) -} - -func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { - cc.mu.Lock() - defer cc.mu.Unlock() - cs := cc.streams[id] - if andRemove && cs != nil && !cc.closed { - cc.lastActive = time.Now() - delete(cc.streams, id) - if len(cc.streams) == 0 && cc.idleTimer != nil { - cc.idleTimer.Reset(cc.idleTimeout) - } - close(cs.done) - // Wake up checkResetOrDone via clientStream.awaitFlowControl and - // wake up RoundTrip if there is a pending request. - cc.cond.Broadcast() - } - return cs -} - -// clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. -type clientConnReadLoop struct { - cc *ClientConn - closeWhenIdle bool -} - -// readLoop runs in its own goroutine and reads and dispatches frames. -func (cc *ClientConn) readLoop() { - rl := &clientConnReadLoop{cc: cc} - defer rl.cleanup() - cc.readerErr = rl.run() - if ce, ok := cc.readerErr.(ConnectionError); ok { - cc.wmu.Lock() - cc.fr.WriteGoAway(0, ErrCode(ce), nil) - cc.wmu.Unlock() - } -} - -// GoAwayError is returned by the Transport when the server closes the -// TCP connection after sending a GOAWAY frame. -type GoAwayError struct { - LastStreamID uint32 - ErrCode ErrCode - DebugData string -} - -func (e GoAwayError) Error() string { - return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q", - e.LastStreamID, e.ErrCode, e.DebugData) -} - -func isEOFOrNetReadError(err error) bool { - if err == io.EOF { - return true - } - ne, ok := err.(*net.OpError) - return ok && ne.Op == "read" -} - -func (rl *clientConnReadLoop) cleanup() { - cc := rl.cc - defer cc.tconn.Close() - defer cc.t.connPool().MarkDead(cc) - defer close(cc.readerDone) - - if cc.idleTimer != nil { - cc.idleTimer.Stop() - } - - // Close any response bodies if the server closes prematurely. - // TODO: also do this if we've written the headers but not - // gotten a response yet. - err := cc.readerErr - cc.mu.Lock() - if cc.goAway != nil && isEOFOrNetReadError(err) { - err = GoAwayError{ - LastStreamID: cc.goAway.LastStreamID, - ErrCode: cc.goAway.ErrCode, - DebugData: cc.goAwayDebug, - } - } else if err == io.EOF { - err = io.ErrUnexpectedEOF - } - for _, cs := range cc.streams { - cs.bufPipe.CloseWithError(err) // no-op if already closed - select { - case cs.resc <- resAndError{err: err}: - default: - } - close(cs.done) - } - cc.closed = true - cc.cond.Broadcast() - cc.mu.Unlock() -} - -func (rl *clientConnReadLoop) run() error { - cc := rl.cc - rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse - gotReply := false // ever saw a HEADERS reply - gotSettings := false - for { - f, err := cc.fr.ReadFrame() - if err != nil { - cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err) - } - if se, ok := err.(StreamError); ok { - if cs := cc.streamByID(se.StreamID, false); cs != nil { - cs.cc.writeStreamReset(cs.ID, se.Code, err) - cs.cc.forgetStreamID(cs.ID) - if se.Cause == nil { - se.Cause = cc.fr.errDetail - } - rl.endStreamError(cs, se) - } - continue - } else if err != nil { - return err - } - if VerboseLogs { - cc.vlogf("http2: Transport received %s", summarizeFrame(f)) - } - if !gotSettings { - if _, ok := f.(*SettingsFrame); !ok { - cc.logf("protocol error: received %T before a SETTINGS frame", f) - return ConnectionError(ErrCodeProtocol) - } - gotSettings = true - } - maybeIdle := false // whether frame might transition us to idle - - switch f := f.(type) { - case *MetaHeadersFrame: - err = rl.processHeaders(f) - maybeIdle = true - gotReply = true - case *DataFrame: - err = rl.processData(f) - maybeIdle = true - case *GoAwayFrame: - err = rl.processGoAway(f) - maybeIdle = true - case *RSTStreamFrame: - err = rl.processResetStream(f) - maybeIdle = true - case *SettingsFrame: - err = rl.processSettings(f) - case *PushPromiseFrame: - err = rl.processPushPromise(f) - case *WindowUpdateFrame: - err = rl.processWindowUpdate(f) - case *PingFrame: - err = rl.processPing(f) - default: - cc.logf("Transport: unhandled response frame type %T", f) - } - if err != nil { - if VerboseLogs { - cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err) - } - return err - } - if rl.closeWhenIdle && gotReply && maybeIdle { - cc.closeIfIdle() - } - } -} - -func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { - cc := rl.cc - cs := cc.streamByID(f.StreamID, false) - if cs == nil { - // We'd get here if we canceled a request while the - // server had its response still in flight. So if this - // was just something we canceled, ignore it. - return nil - } - if f.StreamEnded() { - // Issue 20521: If the stream has ended, streamByID() causes - // clientStream.done to be closed, which causes the request's bodyWriter - // to be closed with an errStreamClosed, which may be received by - // clientConn.RoundTrip before the result of processing these headers. - // Deferring stream closure allows the header processing to occur first. - // clientConn.RoundTrip may still receive the bodyWriter error first, but - // the fix for issue 16102 prioritises any response. - // - // Issue 22413: If there is no request body, we should close the - // stream before writing to cs.resc so that the stream is closed - // immediately once RoundTrip returns. - if cs.req.Body != nil { - defer cc.forgetStreamID(f.StreamID) - } else { - cc.forgetStreamID(f.StreamID) - } - } - if !cs.firstByte { - if cs.trace != nil { - // TODO(bradfitz): move first response byte earlier, - // when we first read the 9 byte header, not waiting - // until all the HEADERS+CONTINUATION frames have been - // merged. This works for now. - traceFirstResponseByte(cs.trace) - } - cs.firstByte = true - } - if !cs.pastHeaders { - cs.pastHeaders = true - } else { - return rl.processTrailers(cs, f) - } - - res, err := rl.handleResponse(cs, f) - if err != nil { - if _, ok := err.(ConnectionError); ok { - return err - } - // Any other error type is a stream error. - cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err) - cc.forgetStreamID(cs.ID) - cs.resc <- resAndError{err: err} - return nil // return nil from process* funcs to keep conn alive - } - if res == nil { - // (nil, nil) special case. See handleResponse docs. - return nil - } - cs.resTrailer = &res.Trailer - cs.resc <- resAndError{res: res} - return nil -} - -// may return error types nil, or ConnectionError. Any other error value -// is a StreamError of type ErrCodeProtocol. The returned error in that case -// is the detail. -// -// As a special case, handleResponse may return (nil, nil) to skip the -// frame (currently only used for 1xx responses). -func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) { - if f.Truncated { - return nil, errResponseHeaderListSize - } - - status := f.PseudoValue("status") - if status == "" { - return nil, errors.New("malformed response from server: missing status pseudo header") - } - statusCode, err := strconv.Atoi(status) - if err != nil { - return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header") - } - - header := make(http.Header) - res := &http.Response{ - Proto: "HTTP/2.0", - ProtoMajor: 2, - Header: header, - StatusCode: statusCode, - Status: status + " " + http.StatusText(statusCode), - } - for _, hf := range f.RegularFields() { - key := http.CanonicalHeaderKey(hf.Name) - if key == "Trailer" { - t := res.Trailer - if t == nil { - t = make(http.Header) - res.Trailer = t - } - foreachHeaderElement(hf.Value, func(v string) { - t[http.CanonicalHeaderKey(v)] = nil - }) - } else { - header[key] = append(header[key], hf.Value) - } - } - - if statusCode >= 100 && statusCode <= 199 { - cs.num1xx++ - const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http - if cs.num1xx > max1xxResponses { - return nil, errors.New("http2: too many 1xx informational responses") - } - if fn := cs.get1xxTraceFunc(); fn != nil { - if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil { - return nil, err - } - } - if statusCode == 100 { - traceGot100Continue(cs.trace) - if cs.on100 != nil { - cs.on100() // forces any write delay timer to fire - } - } - cs.pastHeaders = false // do it all again - return nil, nil - } - - streamEnded := f.StreamEnded() - isHead := cs.req.Method == "HEAD" - if !streamEnded || isHead { - res.ContentLength = -1 - if clens := res.Header["Content-Length"]; len(clens) == 1 { - if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil { - res.ContentLength = clen64 - } else { - // TODO: care? unlike http/1, it won't mess up our framing, so it's - // more safe smuggling-wise to ignore. - } - } else if len(clens) > 1 { - // TODO: care? unlike http/1, it won't mess up our framing, so it's - // more safe smuggling-wise to ignore. - } - } - - if streamEnded || isHead { - res.Body = noBody - return res, nil - } - - cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}} - cs.bytesRemain = res.ContentLength - res.Body = transportResponseBody{cs} - go cs.awaitRequestCancel(cs.req) - - if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" { - res.Header.Del("Content-Encoding") - res.Header.Del("Content-Length") - res.ContentLength = -1 - res.Body = &gzipReader{body: res.Body} - setResponseUncompressed(res) - } - return res, nil -} - -func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error { - if cs.pastTrailers { - // Too many HEADERS frames for this stream. - return ConnectionError(ErrCodeProtocol) - } - cs.pastTrailers = true - if !f.StreamEnded() { - // We expect that any headers for trailers also - // has END_STREAM. - return ConnectionError(ErrCodeProtocol) - } - if len(f.PseudoFields()) > 0 { - // No pseudo header fields are defined for trailers. - // TODO: ConnectionError might be overly harsh? Check. - return ConnectionError(ErrCodeProtocol) - } - - trailer := make(http.Header) - for _, hf := range f.RegularFields() { - key := http.CanonicalHeaderKey(hf.Name) - trailer[key] = append(trailer[key], hf.Value) - } - cs.trailer = trailer - - rl.endStream(cs) - return nil -} - -// transportResponseBody is the concrete type of Transport.RoundTrip's -// Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body. -// On Close it sends RST_STREAM if EOF wasn't already seen. -type transportResponseBody struct { - cs *clientStream -} - -func (b transportResponseBody) Read(p []byte) (n int, err error) { - cs := b.cs - cc := cs.cc - - if cs.readErr != nil { - return 0, cs.readErr - } - n, err = b.cs.bufPipe.Read(p) - if cs.bytesRemain != -1 { - if int64(n) > cs.bytesRemain { - n = int(cs.bytesRemain) - if err == nil { - err = errors.New("net/http: server replied with more than declared Content-Length; truncated") - cc.writeStreamReset(cs.ID, ErrCodeProtocol, err) - } - cs.readErr = err - return int(cs.bytesRemain), err - } - cs.bytesRemain -= int64(n) - if err == io.EOF && cs.bytesRemain > 0 { - err = io.ErrUnexpectedEOF - cs.readErr = err - return n, err - } - } - if n == 0 { - // No flow control tokens to send back. - return - } - - cc.mu.Lock() - defer cc.mu.Unlock() - - var connAdd, streamAdd int32 - // Check the conn-level first, before the stream-level. - if v := cc.inflow.available(); v < transportDefaultConnFlow/2 { - connAdd = transportDefaultConnFlow - v - cc.inflow.add(connAdd) - } - if err == nil { // No need to refresh if the stream is over or failed. - // Consider any buffered body data (read from the conn but not - // consumed by the client) when computing flow control for this - // stream. - v := int(cs.inflow.available()) + cs.bufPipe.Len() - if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh { - streamAdd = int32(transportDefaultStreamFlow - v) - cs.inflow.add(streamAdd) - } - } - if connAdd != 0 || streamAdd != 0 { - cc.wmu.Lock() - defer cc.wmu.Unlock() - if connAdd != 0 { - cc.fr.WriteWindowUpdate(0, mustUint31(connAdd)) - } - if streamAdd != 0 { - cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd)) - } - cc.bw.Flush() - } - return -} - -var errClosedResponseBody = errors.New("http2: response body closed") - -func (b transportResponseBody) Close() error { - cs := b.cs - cc := cs.cc - - serverSentStreamEnd := cs.bufPipe.Err() == io.EOF - unread := cs.bufPipe.Len() - - if unread > 0 || !serverSentStreamEnd { - cc.mu.Lock() - cc.wmu.Lock() - if !serverSentStreamEnd { - cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel) - cs.didReset = true - } - // Return connection-level flow control. - if unread > 0 { - cc.inflow.add(int32(unread)) - cc.fr.WriteWindowUpdate(0, uint32(unread)) - } - cc.bw.Flush() - cc.wmu.Unlock() - cc.mu.Unlock() - } - - cs.bufPipe.BreakWithError(errClosedResponseBody) - cc.forgetStreamID(cs.ID) - return nil -} - -func (rl *clientConnReadLoop) processData(f *DataFrame) error { - cc := rl.cc - cs := cc.streamByID(f.StreamID, f.StreamEnded()) - data := f.Data() - if cs == nil { - cc.mu.Lock() - neverSent := cc.nextStreamID - cc.mu.Unlock() - if f.StreamID >= neverSent { - // We never asked for this. - cc.logf("http2: Transport received unsolicited DATA frame; closing connection") - return ConnectionError(ErrCodeProtocol) - } - // We probably did ask for this, but canceled. Just ignore it. - // TODO: be stricter here? only silently ignore things which - // we canceled, but not things which were closed normally - // by the peer? Tough without accumulating too much state. - - // But at least return their flow control: - if f.Length > 0 { - cc.mu.Lock() - cc.inflow.add(int32(f.Length)) - cc.mu.Unlock() - - cc.wmu.Lock() - cc.fr.WriteWindowUpdate(0, uint32(f.Length)) - cc.bw.Flush() - cc.wmu.Unlock() - } - return nil - } - if !cs.firstByte { - cc.logf("protocol error: received DATA before a HEADERS frame") - rl.endStreamError(cs, StreamError{ - StreamID: f.StreamID, - Code: ErrCodeProtocol, - }) - return nil - } - if f.Length > 0 { - if cs.req.Method == "HEAD" && len(data) > 0 { - cc.logf("protocol error: received DATA on a HEAD request") - rl.endStreamError(cs, StreamError{ - StreamID: f.StreamID, - Code: ErrCodeProtocol, - }) - return nil - } - // Check connection-level flow control. - cc.mu.Lock() - if cs.inflow.available() >= int32(f.Length) { - cs.inflow.take(int32(f.Length)) - } else { - cc.mu.Unlock() - return ConnectionError(ErrCodeFlowControl) - } - // Return any padded flow control now, since we won't - // refund it later on body reads. - var refund int - if pad := int(f.Length) - len(data); pad > 0 { - refund += pad - } - // Return len(data) now if the stream is already closed, - // since data will never be read. - didReset := cs.didReset - if didReset { - refund += len(data) - } - if refund > 0 { - cc.inflow.add(int32(refund)) - cc.wmu.Lock() - cc.fr.WriteWindowUpdate(0, uint32(refund)) - if !didReset { - cs.inflow.add(int32(refund)) - cc.fr.WriteWindowUpdate(cs.ID, uint32(refund)) - } - cc.bw.Flush() - cc.wmu.Unlock() - } - cc.mu.Unlock() - - if len(data) > 0 && !didReset { - if _, err := cs.bufPipe.Write(data); err != nil { - rl.endStreamError(cs, err) - return err - } - } - } - - if f.StreamEnded() { - rl.endStream(cs) - } - return nil -} - -var errInvalidTrailers = errors.New("http2: invalid trailers") - -func (rl *clientConnReadLoop) endStream(cs *clientStream) { - // TODO: check that any declared content-length matches, like - // server.go's (*stream).endStream method. - rl.endStreamError(cs, nil) -} - -func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { - var code func() - if err == nil { - err = io.EOF - code = cs.copyTrailers - } - if isConnectionCloseRequest(cs.req) { - rl.closeWhenIdle = true - } - cs.bufPipe.closeWithErrorAndCode(err, code) - - select { - case cs.resc <- resAndError{err: err}: - default: - } -} - -func (cs *clientStream) copyTrailers() { - for k, vv := range cs.trailer { - t := cs.resTrailer - if *t == nil { - *t = make(http.Header) - } - (*t)[k] = vv - } -} - -func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error { - cc := rl.cc - cc.t.connPool().MarkDead(cc) - if f.ErrCode != 0 { - // TODO: deal with GOAWAY more. particularly the error code - cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode) - } - cc.setGoAway(f) - return nil -} - -func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error { - cc := rl.cc - cc.mu.Lock() - defer cc.mu.Unlock() - - if f.IsAck() { - if cc.wantSettingsAck { - cc.wantSettingsAck = false - return nil - } - return ConnectionError(ErrCodeProtocol) - } - - err := f.ForeachSetting(func(s Setting) error { - switch s.ID { - case SettingMaxFrameSize: - cc.maxFrameSize = s.Val - case SettingMaxConcurrentStreams: - cc.maxConcurrentStreams = s.Val - case SettingMaxHeaderListSize: - cc.peerMaxHeaderListSize = uint64(s.Val) - case SettingInitialWindowSize: - // Values above the maximum flow-control - // window size of 2^31-1 MUST be treated as a - // connection error (Section 5.4.1) of type - // FLOW_CONTROL_ERROR. - if s.Val > math.MaxInt32 { - return ConnectionError(ErrCodeFlowControl) - } - - // Adjust flow control of currently-open - // frames by the difference of the old initial - // window size and this one. - delta := int32(s.Val) - int32(cc.initialWindowSize) - for _, cs := range cc.streams { - cs.flow.add(delta) - } - cc.cond.Broadcast() - - cc.initialWindowSize = s.Val - default: - // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably. - cc.vlogf("Unhandled Setting: %v", s) - } - return nil - }) - if err != nil { - return err - } - - cc.wmu.Lock() - defer cc.wmu.Unlock() - - cc.fr.WriteSettingsAck() - cc.bw.Flush() - return cc.werr -} - -func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error { - cc := rl.cc - cs := cc.streamByID(f.StreamID, false) - if f.StreamID != 0 && cs == nil { - return nil - } - - cc.mu.Lock() - defer cc.mu.Unlock() - - fl := &cc.flow - if cs != nil { - fl = &cs.flow - } - if !fl.add(int32(f.Increment)) { - return ConnectionError(ErrCodeFlowControl) - } - cc.cond.Broadcast() - return nil -} - -func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { - cs := rl.cc.streamByID(f.StreamID, true) - if cs == nil { - // TODO: return error if server tries to RST_STEAM an idle stream - return nil - } - select { - case <-cs.peerReset: - // Already reset. - // This is the only goroutine - // which closes this, so there - // isn't a race. - default: - err := streamError(cs.ID, f.ErrCode) - cs.resetErr = err - close(cs.peerReset) - cs.bufPipe.CloseWithError(err) - cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl - } - return nil -} - -// Ping sends a PING frame to the server and waits for the ack. -// Public implementation is in go17.go and not_go17.go -func (cc *ClientConn) ping(ctx contextContext) error { - c := make(chan struct{}) - // Generate a random payload - var p [8]byte - for { - if _, err := rand.Read(p[:]); err != nil { - return err - } - cc.mu.Lock() - // check for dup before insert - if _, found := cc.pings[p]; !found { - cc.pings[p] = c - cc.mu.Unlock() - break - } - cc.mu.Unlock() - } - cc.wmu.Lock() - if err := cc.fr.WritePing(false, p); err != nil { - cc.wmu.Unlock() - return err - } - if err := cc.bw.Flush(); err != nil { - cc.wmu.Unlock() - return err - } - cc.wmu.Unlock() - select { - case <-c: - return nil - case <-ctx.Done(): - return ctx.Err() - case <-cc.readerDone: - // connection closed - return cc.readerErr - } -} - -func (rl *clientConnReadLoop) processPing(f *PingFrame) error { - if f.IsAck() { - cc := rl.cc - cc.mu.Lock() - defer cc.mu.Unlock() - // If ack, notify listener if any - if c, ok := cc.pings[f.Data]; ok { - close(c) - delete(cc.pings, f.Data) - } - return nil - } - cc := rl.cc - cc.wmu.Lock() - defer cc.wmu.Unlock() - if err := cc.fr.WritePing(true, f.Data); err != nil { - return err - } - return cc.bw.Flush() -} - -func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error { - // We told the peer we don't want them. - // Spec says: - // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH - // setting of the peer endpoint is set to 0. An endpoint that - // has set this setting and has received acknowledgement MUST - // treat the receipt of a PUSH_PROMISE frame as a connection - // error (Section 5.4.1) of type PROTOCOL_ERROR." - return ConnectionError(ErrCodeProtocol) -} - -func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) { - // TODO: map err to more interesting error codes, once the - // HTTP community comes up with some. But currently for - // RST_STREAM there's no equivalent to GOAWAY frame's debug - // data, and the error codes are all pretty vague ("cancel"). - cc.wmu.Lock() - cc.fr.WriteRSTStream(streamID, code) - cc.bw.Flush() - cc.wmu.Unlock() -} - -var ( - errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit") - errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit") - errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers") -) - -func (cc *ClientConn) logf(format string, args ...interface{}) { - cc.t.logf(format, args...) -} - -func (cc *ClientConn) vlogf(format string, args ...interface{}) { - cc.t.vlogf(format, args...) -} - -func (t *Transport) vlogf(format string, args ...interface{}) { - if VerboseLogs { - t.logf(format, args...) - } -} - -func (t *Transport) logf(format string, args ...interface{}) { - log.Printf(format, args...) -} - -var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil)) - -func strSliceContains(ss []string, s string) bool { - for _, v := range ss { - if v == s { - return true - } - } - return false -} - -type erringRoundTripper struct{ err error } - -func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err } - -// gzipReader wraps a response body so it can lazily -// call gzip.NewReader on the first call to Read -type gzipReader struct { - body io.ReadCloser // underlying Response.Body - zr *gzip.Reader // lazily-initialized gzip reader - zerr error // sticky error -} - -func (gz *gzipReader) Read(p []byte) (n int, err error) { - if gz.zerr != nil { - return 0, gz.zerr - } - if gz.zr == nil { - gz.zr, err = gzip.NewReader(gz.body) - if err != nil { - gz.zerr = err - return 0, err - } - } - return gz.zr.Read(p) -} - -func (gz *gzipReader) Close() error { - return gz.body.Close() -} - -type errorReader struct{ err error } - -func (r errorReader) Read(p []byte) (int, error) { return 0, r.err } - -// bodyWriterState encapsulates various state around the Transport's writing -// of the request body, particularly regarding doing delayed writes of the body -// when the request contains "Expect: 100-continue". -type bodyWriterState struct { - cs *clientStream - timer *time.Timer // if non-nil, we're doing a delayed write - fnonce *sync.Once // to call fn with - fn func() // the code to run in the goroutine, writing the body - resc chan error // result of fn's execution - delay time.Duration // how long we should delay a delayed write for -} - -func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) { - s.cs = cs - if body == nil { - return - } - resc := make(chan error, 1) - s.resc = resc - s.fn = func() { - cs.cc.mu.Lock() - cs.startedWrite = true - cs.cc.mu.Unlock() - resc <- cs.writeRequestBody(body, cs.req.Body) - } - s.delay = t.expectContinueTimeout() - if s.delay == 0 || - !httpguts.HeaderValuesContainsToken( - cs.req.Header["Expect"], - "100-continue") { - return - } - s.fnonce = new(sync.Once) - - // Arm the timer with a very large duration, which we'll - // intentionally lower later. It has to be large now because - // we need a handle to it before writing the headers, but the - // s.delay value is defined to not start until after the - // request headers were written. - const hugeDuration = 365 * 24 * time.Hour - s.timer = time.AfterFunc(hugeDuration, func() { - s.fnonce.Do(s.fn) - }) - return -} - -func (s bodyWriterState) cancel() { - if s.timer != nil { - s.timer.Stop() - } -} - -func (s bodyWriterState) on100() { - if s.timer == nil { - // If we didn't do a delayed write, ignore the server's - // bogus 100 continue response. - return - } - s.timer.Stop() - go func() { s.fnonce.Do(s.fn) }() -} - -// scheduleBodyWrite starts writing the body, either immediately (in -// the common case) or after the delay timeout. It should not be -// called until after the headers have been written. -func (s bodyWriterState) scheduleBodyWrite() { - if s.timer == nil { - // We're not doing a delayed write (see - // getBodyWriterState), so just start the writing - // goroutine immediately. - go s.fn() - return - } - traceWait100Continue(s.cs.trace) - if s.timer.Stop() { - s.timer.Reset(s.delay) - } -} - -// isConnectionCloseRequest reports whether req should use its own -// connection for a single request and then close the connection. -func isConnectionCloseRequest(req *http.Request) bool { - return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close") -} diff --git a/examples/golang.org/x/net/http2/transport_test.go b/examples/golang.org/x/net/http2/transport_test.go deleted file mode 100644 index 5b5c076..0000000 --- a/examples/golang.org/x/net/http2/transport_test.go +++ /dev/null @@ -1,4185 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bufio" - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "math/rand" - "net" - "net/http" - "net/http/httptest" - "net/textproto" - "net/url" - "os" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2/hpack" -) - -var ( - extNet = flag.Bool("extnet", false, "do external network tests") - transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport") - insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove? -) - -var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true} - -var canceledCtx context.Context - -func init() { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - canceledCtx = ctx -} - -func TestTransportExternal(t *testing.T) { - if !*extNet { - t.Skip("skipping external network test") - } - req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil) - rt := &Transport{TLSClientConfig: tlsConfigInsecure} - res, err := rt.RoundTrip(req) - if err != nil { - t.Fatalf("%v", err) - } - res.Write(os.Stdout) -} - -type fakeTLSConn struct { - net.Conn -} - -func (c *fakeTLSConn) ConnectionState() tls.ConnectionState { - return tls.ConnectionState{ - Version: tls.VersionTLS12, - CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - } -} - -func startH2cServer(t *testing.T) net.Listener { - h2Server := &Server{} - l := newLocalListener(t) - go func() { - conn, err := l.Accept() - if err != nil { - t.Error(err) - return - } - h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil) - })}) - }() - return l -} - -func TestTransportH2c(t *testing.T) { - l := startH2cServer(t) - defer l.Close() - req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil) - if err != nil { - t.Fatal(err) - } - tr := &Transport{ - AllowHTTP: true, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - return net.Dial(network, addr) - }, - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if res.ProtoMajor != 2 { - t.Fatal("proto not h2c") - } - body, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if got, want := string(body), "Hello, /foobar, http: true"; got != want { - t.Fatalf("response got %v, want %v", got, want) - } -} - -func TestTransport(t *testing.T) { - const body = "sup" - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, body) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - t.Logf("Got res: %+v", res) - if g, w := res.StatusCode, 200; g != w { - t.Errorf("StatusCode = %v; want %v", g, w) - } - if g, w := res.Status, "200 OK"; g != w { - t.Errorf("Status = %q; want %q", g, w) - } - wantHeader := http.Header{ - "Content-Length": []string{"3"}, - "Content-Type": []string{"text/plain; charset=utf-8"}, - "Date": []string{"XXX"}, // see cleanDate - } - cleanDate(res) - if !reflect.DeepEqual(res.Header, wantHeader) { - t.Errorf("res Header = %v; want %v", res.Header, wantHeader) - } - if res.Request != req { - t.Errorf("Response.Request = %p; want %p", res.Request, req) - } - if res.TLS == nil { - t.Error("Response.TLS = nil; want non-nil") - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Errorf("Body read: %v", err) - } else if string(slurp) != body { - t.Errorf("Body = %q; want %q", slurp, body) - } -} - -func onSameConn(t *testing.T, modReq func(*http.Request)) bool { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.RemoteAddr) - }, optOnlyServer, func(c net.Conn, st http.ConnState) { - t.Logf("conn %v is now state %v", c.RemoteAddr(), st) - }) - defer st.Close() - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - get := func() string { - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - modReq(req) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatalf("Body read: %v", err) - } - addr := strings.TrimSpace(string(slurp)) - if addr == "" { - t.Fatalf("didn't get an addr in response") - } - return addr - } - first := get() - second := get() - return first == second -} - -func TestTransportReusesConns(t *testing.T) { - if !onSameConn(t, func(*http.Request) {}) { - t.Errorf("first and second responses were on different connections") - } -} - -func TestTransportReusesConn_RequestClose(t *testing.T) { - if onSameConn(t, func(r *http.Request) { r.Close = true }) { - t.Errorf("first and second responses were not on different connections") - } -} - -func TestTransportReusesConn_ConnClose(t *testing.T) { - if onSameConn(t, func(r *http.Request) { r.Header.Set("Connection", "close") }) { - t.Errorf("first and second responses were not on different connections") - } -} - -// Tests that the Transport only keeps one pending dial open per destination address. -// https://golang.org/issue/13397 -func TestTransportGroupsPendingDials(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.RemoteAddr) - }, optOnlyServer) - defer st.Close() - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - } - defer tr.CloseIdleConnections() - var ( - mu sync.Mutex - dials = map[string]int{} - ) - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Error(err) - return - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Error(err) - return - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Errorf("Body read: %v", err) - } - addr := strings.TrimSpace(string(slurp)) - if addr == "" { - t.Errorf("didn't get an addr in response") - } - mu.Lock() - dials[addr]++ - mu.Unlock() - }() - } - wg.Wait() - if len(dials) != 1 { - t.Errorf("saw %d dials; want 1: %v", len(dials), dials) - } - tr.CloseIdleConnections() - if err := retry(50, 10*time.Millisecond, func() error { - cp, ok := tr.connPool().(*clientConnPool) - if !ok { - return fmt.Errorf("Conn pool is %T; want *clientConnPool", tr.connPool()) - } - cp.mu.Lock() - defer cp.mu.Unlock() - if len(cp.dialing) != 0 { - return fmt.Errorf("dialing map = %v; want empty", cp.dialing) - } - if len(cp.conns) != 0 { - return fmt.Errorf("conns = %v; want empty", cp.conns) - } - if len(cp.keys) != 0 { - return fmt.Errorf("keys = %v; want empty", cp.keys) - } - return nil - }); err != nil { - t.Errorf("State of pool after CloseIdleConnections: %v", err) - } -} - -func retry(tries int, delay time.Duration, fn func() error) error { - var err error - for i := 0; i < tries; i++ { - err = fn() - if err == nil { - return nil - } - time.Sleep(delay) - } - return err -} - -func TestTransportAbortClosesPipes(t *testing.T) { - shutdown := make(chan struct{}) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() - <-shutdown - }, - optOnlyServer, - ) - defer st.Close() - defer close(shutdown) // we must shutdown before st.Close() to avoid hanging - - done := make(chan struct{}) - requestMade := make(chan struct{}) - go func() { - defer close(done) - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - close(requestMade) - _, err = ioutil.ReadAll(res.Body) - if err == nil { - t.Error("expected error from res.Body.Read") - } - }() - - <-requestMade - // Now force the serve loop to end, via closing the connection. - st.closeConn() - // deadlock? that's a bug. - select { - case <-done: - case <-time.After(3 * time.Second): - t.Fatal("timeout") - } -} - -// TODO: merge this with TestTransportBody to make TestTransportRequest? This -// could be a table-driven test with extra goodies. -func TestTransportPath(t *testing.T) { - gotc := make(chan *url.URL, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - gotc <- r.URL - }, - optOnlyServer, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - const ( - path = "/testpath" - query = "q=1" - ) - surl := st.ts.URL + path + "?" + query - req, err := http.NewRequest("POST", surl, nil) - if err != nil { - t.Fatal(err) - } - c := &http.Client{Transport: tr} - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - got := <-gotc - if got.Path != path { - t.Errorf("Read Path = %q; want %q", got.Path, path) - } - if got.RawQuery != query { - t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query) - } -} - -func randString(n int) string { - rnd := rand.New(rand.NewSource(int64(n))) - b := make([]byte, n) - for i := range b { - b[i] = byte(rnd.Intn(256)) - } - return string(b) -} - -type panicReader struct{} - -func (panicReader) Read([]byte) (int, error) { panic("unexpected Read") } -func (panicReader) Close() error { panic("unexpected Close") } - -func TestActualContentLength(t *testing.T) { - tests := []struct { - req *http.Request - want int64 - }{ - // Verify we don't read from Body: - 0: { - req: &http.Request{Body: panicReader{}}, - want: -1, - }, - // nil Body means 0, regardless of ContentLength: - 1: { - req: &http.Request{Body: nil, ContentLength: 5}, - want: 0, - }, - // ContentLength is used if set. - 2: { - req: &http.Request{Body: panicReader{}, ContentLength: 5}, - want: 5, - }, - // http.NoBody means 0, not -1. - 3: { - req: &http.Request{Body: go18httpNoBody()}, - want: 0, - }, - } - for i, tt := range tests { - got := actualContentLength(tt.req) - if got != tt.want { - t.Errorf("test[%d]: got %d; want %d", i, got, tt.want) - } - } -} - -func TestTransportBody(t *testing.T) { - bodyTests := []struct { - body string - noContentLen bool - }{ - {body: "some message"}, - {body: "some message", noContentLen: true}, - {body: strings.Repeat("a", 1<<20), noContentLen: true}, - {body: strings.Repeat("a", 1<<20)}, - {body: randString(16<<10 - 1)}, - {body: randString(16 << 10)}, - {body: randString(16<<10 + 1)}, - {body: randString(512<<10 - 1)}, - {body: randString(512 << 10)}, - {body: randString(512<<10 + 1)}, - {body: randString(1<<20 - 1)}, - {body: randString(1 << 20)}, - {body: randString(1<<20 + 2)}, - } - - type reqInfo struct { - req *http.Request - slurp []byte - err error - } - gotc := make(chan reqInfo, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - slurp, err := ioutil.ReadAll(r.Body) - if err != nil { - gotc <- reqInfo{err: err} - } else { - gotc <- reqInfo{req: r, slurp: slurp} - } - }, - optOnlyServer, - ) - defer st.Close() - - for i, tt := range bodyTests { - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - var body io.Reader = strings.NewReader(tt.body) - if tt.noContentLen { - body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods - } - req, err := http.NewRequest("POST", st.ts.URL, body) - if err != nil { - t.Fatalf("#%d: %v", i, err) - } - c := &http.Client{Transport: tr} - res, err := c.Do(req) - if err != nil { - t.Fatalf("#%d: %v", i, err) - } - defer res.Body.Close() - ri := <-gotc - if ri.err != nil { - t.Errorf("#%d: read error: %v", i, ri.err) - continue - } - if got := string(ri.slurp); got != tt.body { - t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body)) - } - wantLen := int64(len(tt.body)) - if tt.noContentLen && tt.body != "" { - wantLen = -1 - } - if ri.req.ContentLength != wantLen { - t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen) - } - } -} - -func shortString(v string) string { - const maxLen = 100 - if len(v) <= maxLen { - return v - } - return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:]) -} - -func TestTransportDialTLS(t *testing.T) { - var mu sync.Mutex // guards following - var gotReq, didDial bool - - ts := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - gotReq = true - mu.Unlock() - }, - optOnlyServer, - ) - defer ts.Close() - tr := &Transport{ - DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) { - mu.Lock() - didDial = true - mu.Unlock() - cfg.InsecureSkipVerify = true - c, err := tls.Dial(netw, addr, cfg) - if err != nil { - return nil, err - } - return c, c.Handshake() - }, - } - defer tr.CloseIdleConnections() - client := &http.Client{Transport: tr} - res, err := client.Get(ts.ts.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - mu.Lock() - if !gotReq { - t.Error("didn't get request") - } - if !didDial { - t.Error("didn't use dial hook") - } -} - -func TestConfigureTransport(t *testing.T) { - t1 := &http.Transport{} - err := ConfigureTransport(t1) - if err == errTransportVersion { - t.Skip(err) - } - if err != nil { - t.Fatal(err) - } - if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) { - // Laziness, to avoid buildtags. - t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got) - } - wantNextProtos := []string{"h2", "http/1.1"} - if t1.TLSClientConfig == nil { - t.Errorf("nil t1.TLSClientConfig") - } else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) { - t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos) - } - if err := ConfigureTransport(t1); err == nil { - t.Error("unexpected success on second call to ConfigureTransport") - } - - // And does it work? - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.Proto) - }, optOnlyServer) - defer st.Close() - - t1.TLSClientConfig.InsecureSkipVerify = true - c := &http.Client{Transport: t1} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if got, want := string(slurp), "HTTP/2.0"; got != want { - t.Errorf("body = %q; want %q", got, want) - } -} - -type capitalizeReader struct { - r io.Reader -} - -func (cr capitalizeReader) Read(p []byte) (n int, err error) { - n, err = cr.r.Read(p) - for i, b := range p[:n] { - if b >= 'a' && b <= 'z' { - p[i] = b - ('a' - 'A') - } - } - return -} - -type flushWriter struct { - w io.Writer -} - -func (fw flushWriter) Write(p []byte) (n int, err error) { - n, err = fw.w.Write(p) - if f, ok := fw.w.(http.Flusher); ok { - f.Flush() - } - return -} - -type clientTester struct { - t *testing.T - tr *Transport - sc, cc net.Conn // server and client conn - fr *Framer // server's framer - client func() error - server func() error -} - -func newClientTester(t *testing.T) *clientTester { - var dialOnce struct { - sync.Mutex - dialed bool - } - ct := &clientTester{ - t: t, - } - ct.tr = &Transport{ - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - dialOnce.Lock() - defer dialOnce.Unlock() - if dialOnce.dialed { - return nil, errors.New("only one dial allowed in test mode") - } - dialOnce.dialed = true - return ct.cc, nil - }, - } - - ln := newLocalListener(t) - cc, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - t.Fatal(err) - - } - sc, err := ln.Accept() - if err != nil { - t.Fatal(err) - } - ln.Close() - ct.cc = cc - ct.sc = sc - ct.fr = NewFramer(sc, sc) - return ct -} - -func newLocalListener(t *testing.T) net.Listener { - ln, err := net.Listen("tcp4", "127.0.0.1:0") - if err == nil { - return ln - } - ln, err = net.Listen("tcp6", "[::1]:0") - if err != nil { - t.Fatal(err) - } - return ln -} - -func (ct *clientTester) greet(settings ...Setting) { - buf := make([]byte, len(ClientPreface)) - _, err := io.ReadFull(ct.sc, buf) - if err != nil { - ct.t.Fatalf("reading client preface: %v", err) - } - f, err := ct.fr.ReadFrame() - if err != nil { - ct.t.Fatalf("Reading client settings frame: %v", err) - } - if sf, ok := f.(*SettingsFrame); !ok { - ct.t.Fatalf("Wanted client settings frame; got %v", f) - _ = sf // stash it away? - } - if err := ct.fr.WriteSettings(settings...); err != nil { - ct.t.Fatal(err) - } - if err := ct.fr.WriteSettingsAck(); err != nil { - ct.t.Fatal(err) - } -} - -func (ct *clientTester) readNonSettingsFrame() (Frame, error) { - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return nil, err - } - if _, ok := f.(*SettingsFrame); ok { - continue - } - return f, nil - } -} - -func (ct *clientTester) cleanup() { - ct.tr.CloseIdleConnections() -} - -func (ct *clientTester) run() { - errc := make(chan error, 2) - ct.start("client", errc, ct.client) - ct.start("server", errc, ct.server) - defer ct.cleanup() - for i := 0; i < 2; i++ { - if err := <-errc; err != nil { - ct.t.Error(err) - return - } - } -} - -func (ct *clientTester) start(which string, errc chan<- error, fn func() error) { - go func() { - finished := false - var err error - defer func() { - if !finished { - err = fmt.Errorf("%s goroutine didn't finish.", which) - } else if err != nil { - err = fmt.Errorf("%s: %v", which, err) - } - errc <- err - }() - err = fn() - finished = true - }() -} - -func (ct *clientTester) readFrame() (Frame, error) { - return readFrameTimeout(ct.fr, 2*time.Second) -} - -func (ct *clientTester) firstHeaders() (*HeadersFrame, error) { - for { - f, err := ct.readFrame() - if err != nil { - return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - hf, ok := f.(*HeadersFrame) - if !ok { - return nil, fmt.Errorf("Got %T; want HeadersFrame", f) - } - return hf, nil - } -} - -type countingReader struct { - n *int64 -} - -func (r countingReader) Read(p []byte) (n int, err error) { - for i := range p { - p[i] = byte(i) - } - atomic.AddInt64(r.n, int64(len(p))) - return len(p), err -} - -func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) } -func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) } - -func testTransportReqBodyAfterResponse(t *testing.T, status int) { - const bodySize = 10 << 20 - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - - var n int64 // atomic - req, err := http.NewRequest("PUT", "https://dummy.tld/", io.LimitReader(countingReader{&n}, bodySize)) - if err != nil { - return err - } - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != status { - return fmt.Errorf("status code = %v; want %v", res.StatusCode, status) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("Slurp: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("unexpected body: %q", slurp) - } - if status == 200 { - if got := atomic.LoadInt64(&n); got != bodySize { - return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize) - } - } else { - if got := atomic.LoadInt64(&n); got == 0 || got >= bodySize { - return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize) - } - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - var dataRecv int64 - var closed bool - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - //println(fmt.Sprintf("server got frame: %v", f)) - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - if f.StreamEnded() { - return fmt.Errorf("headers contains END_STREAM unexpectedly: %v", f) - } - case *DataFrame: - dataLen := len(f.Data()) - if dataLen > 0 { - if dataRecv == 0 { - enc.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - } - if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { - return err - } - if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { - return err - } - } - dataRecv += int64(dataLen) - - if !closed && ((status != 200 && dataRecv > 0) || - (status == 200 && dataRecv == bodySize)) { - closed = true - if err := ct.fr.WriteData(f.StreamID, true, nil); err != nil { - return err - } - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -// See golang.org/issue/13444 -func TestTransportFullDuplex(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) // redundant but for clarity - w.(http.Flusher).Flush() - io.Copy(flushWriter{w}, capitalizeReader{r.Body}) - fmt.Fprintf(w, "bye.\n") - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - pr, pw := io.Pipe() - req, err := http.NewRequest("PUT", st.ts.URL, ioutil.NopCloser(pr)) - if err != nil { - t.Fatal(err) - } - req.ContentLength = -1 - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - t.Fatalf("StatusCode = %v; want %v", res.StatusCode, 200) - } - bs := bufio.NewScanner(res.Body) - want := func(v string) { - if !bs.Scan() { - t.Fatalf("wanted to read %q but Scan() = false, err = %v", v, bs.Err()) - } - } - write := func(v string) { - _, err := io.WriteString(pw, v) - if err != nil { - t.Fatalf("pipe write: %v", err) - } - } - write("foo\n") - want("FOO") - write("bar\n") - want("BAR") - pw.Close() - want("bye.") - if err := bs.Err(); err != nil { - t.Fatal(err) - } -} - -func TestTransportConnectRequest(t *testing.T) { - gotc := make(chan *http.Request, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - gotc <- r - }, optOnlyServer) - defer st.Close() - - u, err := url.Parse(st.ts.URL) - if err != nil { - t.Fatal(err) - } - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - tests := []struct { - req *http.Request - want string - }{ - { - req: &http.Request{ - Method: "CONNECT", - Header: http.Header{}, - URL: u, - }, - want: u.Host, - }, - { - req: &http.Request{ - Method: "CONNECT", - Header: http.Header{}, - URL: u, - Host: "example.com:123", - }, - want: "example.com:123", - }, - } - - for i, tt := range tests { - res, err := c.Do(tt.req) - if err != nil { - t.Errorf("%d. RoundTrip = %v", i, err) - continue - } - res.Body.Close() - req := <-gotc - if req.Method != "CONNECT" { - t.Errorf("method = %q; want CONNECT", req.Method) - } - if req.Host != tt.want { - t.Errorf("Host = %q; want %q", req.Host, tt.want) - } - if req.URL.Host != tt.want { - t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want) - } - } -} - -type headerType int - -const ( - noHeader headerType = iota // omitted - oneHeader - splitHeader // broken into continuation on purpose -) - -const ( - f0 = noHeader - f1 = oneHeader - f2 = splitHeader - d0 = false - d1 = true -) - -// Test all 36 combinations of response frame orders: -// (3 ways of 100-continue) * (2 ways of headers) * (2 ways of data) * (3 ways of trailers):func TestTransportResponsePattern_00f0(t *testing.T) { testTransportResponsePattern(h0, h1, false, h0) } -// Generated by http://play.golang.org/p/SScqYKJYXd -func TestTransportResPattern_c0h1d0t0(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f0) } -func TestTransportResPattern_c0h1d0t1(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f1) } -func TestTransportResPattern_c0h1d0t2(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f2) } -func TestTransportResPattern_c0h1d1t0(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f0) } -func TestTransportResPattern_c0h1d1t1(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f1) } -func TestTransportResPattern_c0h1d1t2(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f2) } -func TestTransportResPattern_c0h2d0t0(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f0) } -func TestTransportResPattern_c0h2d0t1(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f1) } -func TestTransportResPattern_c0h2d0t2(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f2) } -func TestTransportResPattern_c0h2d1t0(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f0) } -func TestTransportResPattern_c0h2d1t1(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f1) } -func TestTransportResPattern_c0h2d1t2(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f2) } -func TestTransportResPattern_c1h1d0t0(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f0) } -func TestTransportResPattern_c1h1d0t1(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f1) } -func TestTransportResPattern_c1h1d0t2(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f2) } -func TestTransportResPattern_c1h1d1t0(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f0) } -func TestTransportResPattern_c1h1d1t1(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f1) } -func TestTransportResPattern_c1h1d1t2(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f2) } -func TestTransportResPattern_c1h2d0t0(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f0) } -func TestTransportResPattern_c1h2d0t1(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f1) } -func TestTransportResPattern_c1h2d0t2(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f2) } -func TestTransportResPattern_c1h2d1t0(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f0) } -func TestTransportResPattern_c1h2d1t1(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f1) } -func TestTransportResPattern_c1h2d1t2(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f2) } -func TestTransportResPattern_c2h1d0t0(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f0) } -func TestTransportResPattern_c2h1d0t1(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f1) } -func TestTransportResPattern_c2h1d0t2(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f2) } -func TestTransportResPattern_c2h1d1t0(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f0) } -func TestTransportResPattern_c2h1d1t1(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f1) } -func TestTransportResPattern_c2h1d1t2(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f2) } -func TestTransportResPattern_c2h2d0t0(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f0) } -func TestTransportResPattern_c2h2d0t1(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f1) } -func TestTransportResPattern_c2h2d0t2(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f2) } -func TestTransportResPattern_c2h2d1t0(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f0) } -func TestTransportResPattern_c2h2d1t1(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f1) } -func TestTransportResPattern_c2h2d1t2(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f2) } - -func testTransportResPattern(t *testing.T, expect100Continue, resHeader headerType, withData bool, trailers headerType) { - const reqBody = "some request body" - const resBody = "some response body" - - if resHeader == noHeader { - // TODO: test 100-continue followed by immediate - // server stream reset, without headers in the middle? - panic("invalid combination") - } - - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("POST", "https://dummy.tld/", strings.NewReader(reqBody)) - if expect100Continue != noHeader { - req.Header.Set("Expect", "100-continue") - } - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("Slurp: %v", err) - } - wantBody := resBody - if !withData { - wantBody = "" - } - if string(slurp) != wantBody { - return fmt.Errorf("body = %q; want %q", slurp, wantBody) - } - if trailers == noHeader { - if len(res.Trailer) > 0 { - t.Errorf("Trailer = %v; want none", res.Trailer) - } - } else { - want := http.Header{"Some-Trailer": {"some-value"}} - if !reflect.DeepEqual(res.Trailer, want) { - t.Errorf("Trailer = %v; want %v", res.Trailer, want) - } - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - endStream := false - send := func(mode headerType) { - hbf := buf.Bytes() - switch mode { - case oneHeader: - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.Header().StreamID, - EndHeaders: true, - EndStream: endStream, - BlockFragment: hbf, - }) - case splitHeader: - if len(hbf) < 2 { - panic("too small") - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.Header().StreamID, - EndHeaders: false, - EndStream: endStream, - BlockFragment: hbf[:1], - }) - ct.fr.WriteContinuation(f.Header().StreamID, true, hbf[1:]) - default: - panic("bogus mode") - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *DataFrame: - if !f.StreamEnded() { - // No need to send flow control tokens. The test request body is tiny. - continue - } - // Response headers (1+ frames; 1 or 2 in this test, but never 0) - { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "x-foo", Value: "blah"}) - enc.WriteField(hpack.HeaderField{Name: "x-bar", Value: "more"}) - if trailers != noHeader { - enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "some-trailer"}) - } - endStream = withData == false && trailers == noHeader - send(resHeader) - } - if withData { - endStream = trailers == noHeader - ct.fr.WriteData(f.StreamID, endStream, []byte(resBody)) - } - if trailers != noHeader { - endStream = true - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "some-value"}) - send(trailers) - } - if endStream { - return nil - } - case *HeadersFrame: - if expect100Continue != noHeader { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"}) - send(expect100Continue) - } - } - } - } - ct.run() -} - -// Issue 26189, Issue 17739: ignore unknown 1xx responses -func TestTransportUnknown1xx(t *testing.T) { - var buf bytes.Buffer - defer func() { got1xxFuncForTests = nil }() - got1xxFuncForTests = func(code int, header textproto.MIMEHeader) error { - fmt.Fprintf(&buf, "code=%d header=%v\n", code, header) - return nil - } - - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 204 { - return fmt.Errorf("status code = %v; want 204", res.StatusCode) - } - want := `code=110 header=map[Foo-Bar:[110]] -code=111 header=map[Foo-Bar:[111]] -code=112 header=map[Foo-Bar:[112]] -code=113 header=map[Foo-Bar:[113]] -code=114 header=map[Foo-Bar:[114]] -` - if got := buf.String(); got != want { - t.Errorf("Got trace:\n%s\nWant:\n%s", got, want) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - for i := 110; i <= 114; i++ { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: fmt.Sprint(i)}) - enc.WriteField(hpack.HeaderField{Name: "foo-bar", Value: fmt.Sprint(i)}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - } - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - return nil - } - } - } - ct.run() - -} - -func TestTransportReceiveUndeclaredTrailer(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("res.Body ReadAll error = %q, %v; want %v", slurp, err, nil) - } - if len(slurp) > 0 { - return fmt.Errorf("body = %q; want nothing", slurp) - } - if _, ok := res.Trailer["Some-Trailer"]; !ok { - return fmt.Errorf("expected Some-Trailer") - } - return nil - } - ct.server = func() error { - ct.greet() - - var n int - var hf *HeadersFrame - for hf == nil && n < 10 { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - hf, _ = f.(*HeadersFrame) - n++ - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - // send headers without Trailer header - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - // send trailers - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "I'm an undeclared Trailer!"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - return nil - } - ct.run() -} - -func TestTransportInvalidTrailer_Pseudo1(t *testing.T) { - testTransportInvalidTrailer_Pseudo(t, oneHeader) -} -func TestTransportInvalidTrailer_Pseudo2(t *testing.T) { - testTransportInvalidTrailer_Pseudo(t, splitHeader) -} -func testTransportInvalidTrailer_Pseudo(t *testing.T, trailers headerType) { - testInvalidTrailer(t, trailers, pseudoHeaderError(":colon"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: ":colon", Value: "foo"}) - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - }) -} - -func TestTransportInvalidTrailer_Capital1(t *testing.T) { - testTransportInvalidTrailer_Capital(t, oneHeader) -} -func TestTransportInvalidTrailer_Capital2(t *testing.T) { - testTransportInvalidTrailer_Capital(t, splitHeader) -} -func testTransportInvalidTrailer_Capital(t *testing.T, trailers headerType) { - testInvalidTrailer(t, trailers, headerFieldNameError("Capital"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - enc.WriteField(hpack.HeaderField{Name: "Capital", Value: "bad"}) - }) -} -func TestTransportInvalidTrailer_EmptyFieldName(t *testing.T) { - testInvalidTrailer(t, oneHeader, headerFieldNameError(""), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "", Value: "bad"}) - }) -} -func TestTransportInvalidTrailer_BinaryFieldValue(t *testing.T) { - testInvalidTrailer(t, oneHeader, headerFieldValueError("has\nnewline"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "x", Value: "has\nnewline"}) - }) -} - -func testInvalidTrailer(t *testing.T, trailers headerType, wantErr error, writeTrailer func(*hpack.Encoder)) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - se, ok := err.(StreamError) - if !ok || se.Cause != wantErr { - return fmt.Errorf("res.Body ReadAll error = %q, %#v; want StreamError with cause %T, %#v", slurp, err, wantErr, wantErr) - } - if len(slurp) > 0 { - return fmt.Errorf("body = %q; want nothing", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *HeadersFrame: - var endStream bool - send := func(mode headerType) { - hbf := buf.Bytes() - switch mode { - case oneHeader: - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: endStream, - BlockFragment: hbf, - }) - case splitHeader: - if len(hbf) < 2 { - panic("too small") - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: false, - EndStream: endStream, - BlockFragment: hbf[:1], - }) - ct.fr.WriteContinuation(f.StreamID, true, hbf[1:]) - default: - panic("bogus mode") - } - } - // Response headers (1+ frames; 1 or 2 in this test, but never 0) - { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "declared"}) - endStream = false - send(oneHeader) - } - // Trailers: - { - endStream = true - buf.Reset() - writeTrailer(enc) - send(trailers) - } - return nil - } - } - } - ct.run() -} - -// headerListSize returns the HTTP2 header list size of h. -// http://httpwg.org/specs/rfc7540.html#SETTINGS_MAX_HEADER_LIST_SIZE -// http://httpwg.org/specs/rfc7540.html#MaxHeaderBlock -func headerListSize(h http.Header) (size uint32) { - for k, vv := range h { - for _, v := range vv { - hf := hpack.HeaderField{Name: k, Value: v} - size += hf.Size() - } - } - return size -} - -// padHeaders adds data to an http.Header until headerListSize(h) == -// limit. Due to the way header list sizes are calculated, padHeaders -// cannot add fewer than len("Pad-Headers") + 32 bytes to h, and will -// call t.Fatal if asked to do so. PadHeaders first reserves enough -// space for an empty "Pad-Headers" key, then adds as many copies of -// filler as possible. Any remaining bytes necessary to push the -// header list size up to limit are added to h["Pad-Headers"]. -func padHeaders(t *testing.T, h http.Header, limit uint64, filler string) { - if limit > 0xffffffff { - t.Fatalf("padHeaders: refusing to pad to more than 2^32-1 bytes. limit = %v", limit) - } - hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} - minPadding := uint64(hf.Size()) - size := uint64(headerListSize(h)) - - minlimit := size + minPadding - if limit < minlimit { - t.Fatalf("padHeaders: limit %v < %v", limit, minlimit) - } - - // Use a fixed-width format for name so that fieldSize - // remains constant. - nameFmt := "Pad-Headers-%06d" - hf = hpack.HeaderField{Name: fmt.Sprintf(nameFmt, 1), Value: filler} - fieldSize := uint64(hf.Size()) - - // Add as many complete filler values as possible, leaving - // room for at least one empty "Pad-Headers" key. - limit = limit - minPadding - for i := 0; size+fieldSize < limit; i++ { - name := fmt.Sprintf(nameFmt, i) - h.Add(name, filler) - size += fieldSize - } - - // Add enough bytes to reach limit. - remain := limit - size - lastValue := strings.Repeat("*", int(remain)) - h.Add("Pad-Headers", lastValue) -} - -func TestPadHeaders(t *testing.T) { - check := func(h http.Header, limit uint32, fillerLen int) { - if h == nil { - h = make(http.Header) - } - filler := strings.Repeat("f", fillerLen) - padHeaders(t, h, uint64(limit), filler) - gotSize := headerListSize(h) - if gotSize != limit { - t.Errorf("Got size = %v; want %v", gotSize, limit) - } - } - // Try all possible combinations for small fillerLen and limit. - hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} - minLimit := hf.Size() - for limit := minLimit; limit <= 128; limit++ { - for fillerLen := 0; uint32(fillerLen) <= limit; fillerLen++ { - check(nil, limit, fillerLen) - } - } - - // Try a few tests with larger limits, plus cumulative - // tests. Since these tests are cumulative, tests[i+1].limit - // must be >= tests[i].limit + minLimit. See the comment on - // padHeaders for more info on why the limit arg has this - // restriction. - tests := []struct { - fillerLen int - limit uint32 - }{ - { - fillerLen: 64, - limit: 1024, - }, - { - fillerLen: 1024, - limit: 1286, - }, - { - fillerLen: 256, - limit: 2048, - }, - { - fillerLen: 1024, - limit: 10 * 1024, - }, - { - fillerLen: 1023, - limit: 11 * 1024, - }, - } - h := make(http.Header) - for _, tc := range tests { - check(nil, tc.limit, tc.fillerLen) - check(h, tc.limit, tc.fillerLen) - } -} - -func TestTransportChecksRequestHeaderListSize(t *testing.T) { - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - // Consume body & force client to send - // trailers before writing response. - // ioutil.ReadAll returns non-nil err for - // requests that attempt to send greater than - // maxHeaderListSize bytes of trailers, since - // those requests generate a stream reset. - ioutil.ReadAll(r.Body) - r.Body.Close() - }, - func(ts *httptest.Server) { - ts.Config.MaxHeaderBytes = 16 << 10 - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - checkRoundTrip := func(req *http.Request, wantErr error, desc string) { - res, err := tr.RoundTrip(req) - if err != wantErr { - if res != nil { - res.Body.Close() - } - t.Errorf("%v: RoundTrip err = %v; want %v", desc, err, wantErr) - return - } - if err == nil { - if res == nil { - t.Errorf("%v: response nil; want non-nil.", desc) - return - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - t.Errorf("%v: response status = %v; want %v", desc, res.StatusCode, http.StatusOK) - } - return - } - if res != nil { - t.Errorf("%v: RoundTrip err = %v but response non-nil", desc, err) - } - } - headerListSizeForRequest := func(req *http.Request) (size uint64) { - contentLen := actualContentLength(req) - trailers, err := commaSeparatedTrailers(req) - if err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} - cc.henc = hpack.NewEncoder(&cc.hbuf) - cc.mu.Lock() - hdrs, err := cc.encodeHeaders(req, true, trailers, contentLen) - cc.mu.Unlock() - if err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(hf hpack.HeaderField) { - size += uint64(hf.Size()) - }) - if len(hdrs) > 0 { - if _, err := hpackDec.Write(hdrs); err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - } - return size - } - // Create a new Request for each test, rather than reusing the - // same Request, to avoid a race when modifying req.Headers. - // See https://github.com/golang/go/issues/21316 - newRequest := func() *http.Request { - // Body must be non-nil to enable writing trailers. - body := strings.NewReader("hello") - req, err := http.NewRequest("POST", st.ts.URL, body) - if err != nil { - t.Fatalf("newRequest: NewRequest: %v", err) - } - return req - } - - // Make an arbitrary request to ensure we get the server's - // settings frame and initialize peerMaxHeaderListSize. - req := newRequest() - checkRoundTrip(req, nil, "Initial request") - - // Get the ClientConn associated with the request and validate - // peerMaxHeaderListSize. - addr := authorityAddr(req.URL.Scheme, req.URL.Host) - cc, err := tr.connPool().GetClientConn(req, addr) - if err != nil { - t.Fatalf("GetClientConn: %v", err) - } - cc.mu.Lock() - peerSize := cc.peerMaxHeaderListSize - cc.mu.Unlock() - st.scMu.Lock() - wantSize := uint64(st.sc.maxHeaderListSize()) - st.scMu.Unlock() - if peerSize != wantSize { - t.Errorf("peerMaxHeaderListSize = %v; want %v", peerSize, wantSize) - } - - // Sanity check peerSize. (*serverConn) maxHeaderListSize adds - // 320 bytes of padding. - wantHeaderBytes := uint64(st.ts.Config.MaxHeaderBytes) + 320 - if peerSize != wantHeaderBytes { - t.Errorf("peerMaxHeaderListSize = %v; want %v.", peerSize, wantHeaderBytes) - } - - // Pad headers & trailers, but stay under peerSize. - req = newRequest() - req.Header = make(http.Header) - req.Trailer = make(http.Header) - filler := strings.Repeat("*", 1024) - padHeaders(t, req.Trailer, peerSize, filler) - // cc.encodeHeaders adds some default headers to the request, - // so we need to leave room for those. - defaultBytes := headerListSizeForRequest(req) - padHeaders(t, req.Header, peerSize-defaultBytes, filler) - checkRoundTrip(req, nil, "Headers & Trailers under limit") - - // Add enough header bytes to push us over peerSize. - req = newRequest() - req.Header = make(http.Header) - padHeaders(t, req.Header, peerSize, filler) - checkRoundTrip(req, errRequestHeaderListSize, "Headers over limit") - - // Push trailers over the limit. - req = newRequest() - req.Trailer = make(http.Header) - padHeaders(t, req.Trailer, peerSize+1, filler) - checkRoundTrip(req, errRequestHeaderListSize, "Trailers over limit") - - // Send headers with a single large value. - req = newRequest() - filler = strings.Repeat("*", int(peerSize)) - req.Header = make(http.Header) - req.Header.Set("Big", filler) - checkRoundTrip(req, errRequestHeaderListSize, "Single large header") - - // Send trailers with a single large value. - req = newRequest() - req.Trailer = make(http.Header) - req.Trailer.Set("Big", filler) - checkRoundTrip(req, errRequestHeaderListSize, "Single large trailer") -} - -func TestTransportChecksResponseHeaderListSize(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != errResponseHeaderListSize { - if res != nil { - res.Body.Close() - } - size := int64(0) - for k, vv := range res.Header { - for _, v := range vv { - size += int64(len(k)) + int64(len(v)) + 32 - } - } - return fmt.Errorf("RoundTrip Error = %v (and %d bytes of response headers); want errResponseHeaderListSize", err, size) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *HeadersFrame: - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - large := strings.Repeat("a", 1<<10) - for i := 0; i < 5042; i++ { - enc.WriteField(hpack.HeaderField{Name: large, Value: large}) - } - if size, want := buf.Len(), 6329; size != want { - // Note: this number might change if - // our hpack implementation - // changes. That's fine. This is - // just a sanity check that our - // response can fit in a single - // header block fragment frame. - return fmt.Errorf("encoding over 10MB of duplicate keypairs took %d bytes; expected %d", size, want) - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - return nil - } - } - } - ct.run() -} - -// Test that the Transport returns a typed error from Response.Body.Read calls -// when the server sends an error. (here we use a panic, since that should generate -// a stream error, but others like cancel should be similar) -func TestTransportBodyReadErrorType(t *testing.T) { - doPanic := make(chan bool, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() // force headers out - <-doPanic - panic("boom") - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - doPanic <- true - buf := make([]byte, 100) - n, err := res.Body.Read(buf) - want := StreamError{StreamID: 0x1, Code: 0x2} - if !reflect.DeepEqual(want, err) { - t.Errorf("Read = %v, %#v; want error %#v", n, err, want) - } -} - -// golang.org/issue/13924 -// This used to fail after many iterations, especially with -race: -// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race -func TestTransportDoubleCloseOnWriteError(t *testing.T) { - var ( - mu sync.Mutex - conn net.Conn // to close if set - ) - - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - defer mu.Unlock() - if conn != nil { - conn.Close() - } - }, - optOnlyServer, - ) - defer st.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - mu.Lock() - defer mu.Unlock() - conn = tc - return tc, nil - }, - } - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - c.Get(st.ts.URL) -} - -// Test that the http1 Transport.DisableKeepAlives option is respected -// and connections are closed as soon as idle. -// See golang.org/issue/14008 -func TestTransportDisableKeepAlives(t *testing.T) { - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "hi") - }, - optOnlyServer, - ) - defer st.Close() - - connClosed := make(chan struct{}) // closed on tls.Conn.Close - tr := &Transport{ - t1: &http.Transport{ - DisableKeepAlives: true, - }, - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - return ¬eCloseConn{Conn: tc, closefn: func() { close(connClosed) }}, nil - }, - } - c := &http.Client{Transport: tr} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - if _, err := ioutil.ReadAll(res.Body); err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - select { - case <-connClosed: - case <-time.After(1 * time.Second): - t.Errorf("timeout") - } - -} - -// Test concurrent requests with Transport.DisableKeepAlives. We can share connections, -// but when things are totally idle, it still needs to close. -func TestTransportDisableKeepAlives_Concurrency(t *testing.T) { - const D = 25 * time.Millisecond - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - time.Sleep(D) - io.WriteString(w, "hi") - }, - optOnlyServer, - ) - defer st.Close() - - var dials int32 - var conns sync.WaitGroup - tr := &Transport{ - t1: &http.Transport{ - DisableKeepAlives: true, - }, - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - atomic.AddInt32(&dials, 1) - conns.Add(1) - return ¬eCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil - }, - } - c := &http.Client{Transport: tr} - var reqs sync.WaitGroup - const N = 20 - for i := 0; i < N; i++ { - reqs.Add(1) - if i == N-1 { - // For the final request, try to make all the - // others close. This isn't verified in the - // count, other than the Log statement, since - // it's so timing dependent. This test is - // really to make sure we don't interrupt a - // valid request. - time.Sleep(D * 2) - } - go func() { - defer reqs.Done() - res, err := c.Get(st.ts.URL) - if err != nil { - t.Error(err) - return - } - if _, err := ioutil.ReadAll(res.Body); err != nil { - t.Error(err) - return - } - res.Body.Close() - }() - } - reqs.Wait() - conns.Wait() - t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N) -} - -type noteCloseConn struct { - net.Conn - onceClose sync.Once - closefn func() -} - -func (c *noteCloseConn) Close() error { - c.onceClose.Do(c.closefn) - return c.Conn.Close() -} - -func isTimeout(err error) bool { - switch err := err.(type) { - case nil: - return false - case *url.Error: - return isTimeout(err.Err) - case net.Error: - return err.Timeout() - } - return false -} - -// Test that the http1 Transport.ResponseHeaderTimeout option and cancel is sent. -func TestTransportResponseHeaderTimeout_NoBody(t *testing.T) { - testTransportResponseHeaderTimeout(t, false) -} -func TestTransportResponseHeaderTimeout_Body(t *testing.T) { - testTransportResponseHeaderTimeout(t, true) -} - -func testTransportResponseHeaderTimeout(t *testing.T, body bool) { - ct := newClientTester(t) - ct.tr.t1 = &http.Transport{ - ResponseHeaderTimeout: 5 * time.Millisecond, - } - ct.client = func() error { - c := &http.Client{Transport: ct.tr} - var err error - var n int64 - const bodySize = 4 << 20 - if body { - _, err = c.Post("https://dummy.tld/", "text/foo", io.LimitReader(countingReader{&n}, bodySize)) - } else { - _, err = c.Get("https://dummy.tld/") - } - if !isTimeout(err) { - t.Errorf("client expected timeout error; got %#v", err) - } - if body && n != bodySize { - t.Errorf("only read %d bytes of body; want %d", n, bodySize) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - switch f := f.(type) { - case *DataFrame: - dataLen := len(f.Data()) - if dataLen > 0 { - if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { - return err - } - if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { - return err - } - } - case *RSTStreamFrame: - if f.StreamID == 1 && f.ErrCode == ErrCodeCancel { - return nil - } - } - } - } - ct.run() -} - -func TestTransportDisableCompression(t *testing.T) { - const body = "sup" - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - want := http.Header{ - "User-Agent": []string{"Go-http-client/2.0"}, - } - if !reflect.DeepEqual(r.Header, want) { - t.Errorf("request headers = %v; want %v", r.Header, want) - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - t1: &http.Transport{ - DisableCompression: true, - }, - } - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() -} - -// RFC 7540 section 8.1.2.2 -func TestTransportRejectsConnHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - var got []string - for k := range r.Header { - got = append(got, k) - } - sort.Strings(got) - w.Header().Set("Got-Header", strings.Join(got, ",")) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - tests := []struct { - key string - value []string - want string - }{ - { - key: "Upgrade", - value: []string{"anything"}, - want: "ERROR: http2: invalid Upgrade request header: [\"anything\"]", - }, - { - key: "Connection", - value: []string{"foo"}, - want: "ERROR: http2: invalid Connection request header: [\"foo\"]", - }, - { - key: "Connection", - value: []string{"close"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Connection", - value: []string{"CLoSe"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Connection", - value: []string{"close", "something-else"}, - want: "ERROR: http2: invalid Connection request header: [\"close\" \"something-else\"]", - }, - { - key: "Connection", - value: []string{"keep-alive"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Connection", - value: []string{"Keep-ALIVE"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Proxy-Connection", // just deleted and ignored - value: []string{"keep-alive"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{""}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{"foo"}, - want: "ERROR: http2: invalid Transfer-Encoding request header: [\"foo\"]", - }, - { - key: "Transfer-Encoding", - value: []string{"chunked"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{"chunked", "other"}, - want: "ERROR: http2: invalid Transfer-Encoding request header: [\"chunked\" \"other\"]", - }, - { - key: "Content-Length", - value: []string{"123"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Keep-Alive", - value: []string{"doop"}, - want: "Accept-Encoding,User-Agent", - }, - } - - for _, tt := range tests { - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Header[tt.key] = tt.value - res, err := tr.RoundTrip(req) - var got string - if err != nil { - got = fmt.Sprintf("ERROR: %v", err) - } else { - got = res.Header.Get("Got-Header") - res.Body.Close() - } - if got != tt.want { - t.Errorf("For key %q, value %q, got = %q; want %q", tt.key, tt.value, got, tt.want) - } - } -} - -// golang.org/issue/14048 -func TestTransportFailsOnInvalidHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - var got []string - for k := range r.Header { - got = append(got, k) - } - sort.Strings(got) - w.Header().Set("Got-Header", strings.Join(got, ",")) - }, optOnlyServer) - defer st.Close() - - tests := [...]struct { - h http.Header - wantErr string - }{ - 0: { - h: http.Header{"with space": {"foo"}}, - wantErr: `invalid HTTP header name "with space"`, - }, - 1: { - h: http.Header{"name": {"Брэд"}}, - wantErr: "", // okay - }, - 2: { - h: http.Header{"имя": {"Brad"}}, - wantErr: `invalid HTTP header name "имя"`, - }, - 3: { - h: http.Header{"foo": {"foo\x01bar"}}, - wantErr: `invalid HTTP header value "foo\x01bar" for header "foo"`, - }, - } - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - for i, tt := range tests { - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Header = tt.h - res, err := tr.RoundTrip(req) - var bad bool - if tt.wantErr == "" { - if err != nil { - bad = true - t.Errorf("case %d: error = %v; want no error", i, err) - } - } else { - if !strings.Contains(fmt.Sprint(err), tt.wantErr) { - bad = true - t.Errorf("case %d: error = %v; want error %q", i, err, tt.wantErr) - } - } - if err == nil { - if bad { - t.Logf("case %d: server got headers %q", i, res.Header.Get("Got-Header")) - } - res.Body.Close() - } - } -} - -// Tests that gzipReader doesn't crash on a second Read call following -// the first Read call's gzip.NewReader returning an error. -func TestGzipReader_DoubleReadCrash(t *testing.T) { - gz := &gzipReader{ - body: ioutil.NopCloser(strings.NewReader("0123456789")), - } - var buf [1]byte - n, err1 := gz.Read(buf[:]) - if n != 0 || !strings.Contains(fmt.Sprint(err1), "invalid header") { - t.Fatalf("Read = %v, %v; want 0, invalid header", n, err1) - } - n, err2 := gz.Read(buf[:]) - if n != 0 || err2 != err1 { - t.Fatalf("second Read = %v, %v; want 0, %v", n, err2, err1) - } -} - -func TestTransportNewTLSConfig(t *testing.T) { - tests := [...]struct { - conf *tls.Config - host string - want *tls.Config - }{ - // Normal case. - 0: { - conf: nil, - host: "foo.com", - want: &tls.Config{ - ServerName: "foo.com", - NextProtos: []string{NextProtoTLS}, - }, - }, - - // User-provided name (bar.com) takes precedence: - 1: { - conf: &tls.Config{ - ServerName: "bar.com", - }, - host: "foo.com", - want: &tls.Config{ - ServerName: "bar.com", - NextProtos: []string{NextProtoTLS}, - }, - }, - - // NextProto is prepended: - 2: { - conf: &tls.Config{ - NextProtos: []string{"foo", "bar"}, - }, - host: "example.com", - want: &tls.Config{ - ServerName: "example.com", - NextProtos: []string{NextProtoTLS, "foo", "bar"}, - }, - }, - - // NextProto is not duplicated: - 3: { - conf: &tls.Config{ - NextProtos: []string{"foo", "bar", NextProtoTLS}, - }, - host: "example.com", - want: &tls.Config{ - ServerName: "example.com", - NextProtos: []string{"foo", "bar", NextProtoTLS}, - }, - }, - } - for i, tt := range tests { - // Ignore the session ticket keys part, which ends up populating - // unexported fields in the Config: - if tt.conf != nil { - tt.conf.SessionTicketsDisabled = true - } - - tr := &Transport{TLSClientConfig: tt.conf} - got := tr.newTLSConfig(tt.host) - - got.SessionTicketsDisabled = false - - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d. got %#v; want %#v", i, got, tt.want) - } - } -} - -// The Google GFE responds to HEAD requests with a HEADERS frame -// without END_STREAM, followed by a 0-length DATA frame with -// END_STREAM. Make sure we don't get confused by that. (We did.) -func TestTransportReadHeadResponse(t *testing.T) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - if res.ContentLength != 123 { - return fmt.Errorf("Content-Length = %d; want 123", res.ContentLength) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("ReadAll: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, // as the GFE does - BlockFragment: buf.Bytes(), - }) - ct.fr.WriteData(hf.StreamID, true, nil) - - <-clientDone - return nil - } - } - ct.run() -} - -func TestTransportReadHeadResponseWithBody(t *testing.T) { - // This test use not valid response format. - // Discarding logger output to not spam tests output. - log.SetOutput(ioutil.Discard) - defer log.SetOutput(os.Stderr) - - response := "redirecting to /elsewhere" - ct := newClientTester(t) - clientDone := make(chan struct{}) - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - if res.ContentLength != int64(len(response)) { - return fmt.Errorf("Content-Length = %d; want %d", res.ContentLength, len(response)) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("ReadAll: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: strconv.Itoa(len(response))}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - ct.fr.WriteData(hf.StreamID, true, []byte(response)) - - <-clientDone - return nil - } - } - ct.run() -} - -type neverEnding byte - -func (b neverEnding) Read(p []byte) (int, error) { - for i := range p { - p[i] = byte(b) - } - return len(p), nil -} - -// golang.org/issue/15425: test that a handler closing the request -// body doesn't terminate the stream to the peer. (It just stops -// readability from the handler's side, and eventually the client -// runs out of flow control tokens) -func TestTransportHandlerBodyClose(t *testing.T) { - const bodySize = 10 << 20 - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - r.Body.Close() - io.Copy(w, io.LimitReader(neverEnding('A'), bodySize)) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - g0 := runtime.NumGoroutine() - - const numReq = 10 - for i := 0; i < numReq; i++ { - req, err := http.NewRequest("POST", st.ts.URL, struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - n, err := io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - if n != bodySize || err != nil { - t.Fatalf("req#%d: Copy = %d, %v; want %d, nil", i, n, err, bodySize) - } - } - tr.CloseIdleConnections() - - if !waitCondition(5*time.Second, 100*time.Millisecond, func() bool { - gd := runtime.NumGoroutine() - g0 - return gd < numReq/2 - }) { - t.Errorf("appeared to leak goroutines") - } -} - -// https://golang.org/issue/15930 -func TestTransportFlowControl(t *testing.T) { - const bufLen = 64 << 10 - var total int64 = 100 << 20 // 100MB - if testing.Short() { - total = 10 << 20 - } - - var wrote int64 // updated atomically - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - b := make([]byte, bufLen) - for wrote < total { - n, err := w.Write(b) - atomic.AddInt64(&wrote, int64(n)) - if err != nil { - t.Errorf("ResponseWriter.Write error: %v", err) - break - } - w.(http.Flusher).Flush() - } - }, optOnlyServer) - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal("NewRequest error:", err) - } - resp, err := tr.RoundTrip(req) - if err != nil { - t.Fatal("RoundTrip error:", err) - } - defer resp.Body.Close() - - var read int64 - b := make([]byte, bufLen) - for { - n, err := resp.Body.Read(b) - if err == io.EOF { - break - } - if err != nil { - t.Fatal("Read error:", err) - } - read += int64(n) - - const max = transportDefaultStreamFlow - if w := atomic.LoadInt64(&wrote); -max > read-w || read-w > max { - t.Fatalf("Too much data inflight: server wrote %v bytes but client only received %v", w, read) - } - - // Let the server get ahead of the client. - time.Sleep(1 * time.Millisecond) - } -} - -// golang.org/issue/14627 -- if the server sends a GOAWAY frame, make -// the Transport remember it and return it back to users (via -// RoundTrip or request body reads) if needed (e.g. if the server -// proceeds to close the TCP connection before the client gets its -// response) -func TestTransportUsesGoAwayDebugError_RoundTrip(t *testing.T) { - testTransportUsesGoAwayDebugError(t, false) -} - -func TestTransportUsesGoAwayDebugError_Body(t *testing.T) { - testTransportUsesGoAwayDebugError(t, true) -} - -func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - - const goAwayErrCode = ErrCodeHTTP11Required // arbitrary - const goAwayDebugData = "some debug data" - - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if failMidBody { - if err != nil { - return fmt.Errorf("unexpected client RoundTrip error: %v", err) - } - _, err = io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - } - want := GoAwayError{ - LastStreamID: 5, - ErrCode: goAwayErrCode, - DebugData: goAwayDebugData, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("RoundTrip error = %T: %#v, want %T (%#v)", err, err, want, want) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - if failMidBody { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - } - // Write two GOAWAY frames, to test that the Transport takes - // the interesting parts of both. - ct.fr.WriteGoAway(5, ErrCodeNo, []byte(goAwayDebugData)) - ct.fr.WriteGoAway(5, goAwayErrCode, nil) - ct.sc.(*net.TCPConn).CloseWrite() - <-clientDone - return nil - } - } - ct.run() -} - -func testTransportReturnsUnusedFlowControl(t *testing.T, oneDataFrame bool) { - ct := newClientTester(t) - - clientClosed := make(chan struct{}) - serverWroteFirstByte := make(chan struct{}) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - <-serverWroteFirstByte - - if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 { - return fmt.Errorf("body read = %v, %v; want 1, nil", n, err) - } - res.Body.Close() // leaving 4999 bytes unread - close(clientClosed) - - return nil - } - ct.server = func() error { - ct.greet() - - var hf *HeadersFrame - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - var ok bool - hf, ok = f.(*HeadersFrame) - if !ok { - return fmt.Errorf("Got %T; want HeadersFrame", f) - } - break - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - // Two cases: - // - Send one DATA frame with 5000 bytes. - // - Send two DATA frames with 1 and 4999 bytes each. - // - // In both cases, the client should consume one byte of data, - // refund that byte, then refund the following 4999 bytes. - // - // In the second case, the server waits for the client connection to - // close before seconding the second DATA frame. This tests the case - // where the client receives a DATA frame after it has reset the stream. - if oneDataFrame { - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 5000)) - close(serverWroteFirstByte) - <-clientClosed - } else { - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 1)) - close(serverWroteFirstByte) - <-clientClosed - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 4999)) - } - - waitingFor := "RSTStreamFrame" - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for %s: %v", waitingFor, err) - } - if _, ok := f.(*SettingsFrame); ok { - continue - } - switch waitingFor { - case "RSTStreamFrame": - if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel { - return fmt.Errorf("Expected a RSTStreamFrame with code cancel; got %v", summarizeFrame(f)) - } - waitingFor = "WindowUpdateFrame" - case "WindowUpdateFrame": - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != 4999 { - return fmt.Errorf("Expected WindowUpdateFrame for 4999 bytes; got %v", summarizeFrame(f)) - } - return nil - } - } - } - ct.run() -} - -// See golang.org/issue/16481 -func TestTransportReturnsUnusedFlowControlSingleWrite(t *testing.T) { - testTransportReturnsUnusedFlowControl(t, true) -} - -// See golang.org/issue/20469 -func TestTransportReturnsUnusedFlowControlMultipleWrites(t *testing.T) { - testTransportReturnsUnusedFlowControl(t, false) -} - -// Issue 16612: adjust flow control on open streams when transport -// receives SETTINGS with INITIAL_WINDOW_SIZE from server. -func TestTransportAdjustsFlowControl(t *testing.T) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - - const bodySize = 1 << 20 - - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - - req, _ := http.NewRequest("POST", "https://dummy.tld/", struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - res.Body.Close() - return nil - } - ct.server = func() error { - _, err := io.ReadFull(ct.sc, make([]byte, len(ClientPreface))) - if err != nil { - return fmt.Errorf("reading client preface: %v", err) - } - - var gotBytes int64 - var sentSettings bool - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - return nil - default: - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - } - switch f := f.(type) { - case *DataFrame: - gotBytes += int64(len(f.Data())) - // After we've got half the client's - // initial flow control window's worth - // of request body data, give it just - // enough flow control to finish. - if gotBytes >= initialWindowSize/2 && !sentSettings { - sentSettings = true - - ct.fr.WriteSettings(Setting{ID: SettingInitialWindowSize, Val: bodySize}) - ct.fr.WriteWindowUpdate(0, bodySize) - ct.fr.WriteSettingsAck() - } - - if f.StreamEnded() { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - } - } - } - ct.run() -} - -// See golang.org/issue/16556 -func TestTransportReturnsDataPaddingFlowControl(t *testing.T) { - ct := newClientTester(t) - - unblockClient := make(chan bool, 1) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - defer res.Body.Close() - <-unblockClient - return nil - } - ct.server = func() error { - ct.greet() - - var hf *HeadersFrame - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - var ok bool - hf, ok = f.(*HeadersFrame) - if !ok { - return fmt.Errorf("Got %T; want HeadersFrame", f) - } - break - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - pad := make([]byte, 5) - ct.fr.WriteDataPadded(hf.StreamID, false, make([]byte, 5000), pad) // without ending stream - - f, err := ct.readNonSettingsFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for first WindowUpdateFrame: %v", err) - } - wantBack := uint32(len(pad)) + 1 // one byte for the length of the padding - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID != 0 { - return fmt.Errorf("Expected conn WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) - } - - f, err = ct.readNonSettingsFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for second WindowUpdateFrame: %v", err) - } - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID == 0 { - return fmt.Errorf("Expected stream WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) - } - unblockClient <- true - return nil - } - ct.run() -} - -// golang.org/issue/16572 -- RoundTrip shouldn't hang when it gets a -// StreamError as a result of the response HEADERS -func TestTransportReturnsErrorOnBadResponseHeaders(t *testing.T) { - ct := newClientTester(t) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err == nil { - res.Body.Close() - return errors.New("unexpected successful GET") - } - want := StreamError{1, ErrCodeProtocol, headerFieldNameError(" content-type")} - if !reflect.DeepEqual(want, err) { - t.Errorf("RoundTrip error = %#v; want %#v", err, want) - } - return nil - } - ct.server = func() error { - ct.greet() - - hf, err := ct.firstHeaders() - if err != nil { - return err - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: " content-type", Value: "bogus"}) // bogus spaces - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - for { - fr, err := ct.readFrame() - if err != nil { - return fmt.Errorf("error waiting for RST_STREAM from client: %v", err) - } - if _, ok := fr.(*SettingsFrame); ok { - continue - } - if rst, ok := fr.(*RSTStreamFrame); !ok || rst.StreamID != 1 || rst.ErrCode != ErrCodeProtocol { - t.Errorf("Frame = %v; want RST_STREAM for stream 1 with ErrCodeProtocol", summarizeFrame(fr)) - } - break - } - - return nil - } - ct.run() -} - -// byteAndEOFReader returns is in an io.Reader which reads one byte -// (the underlying byte) and io.EOF at once in its Read call. -type byteAndEOFReader byte - -func (b byteAndEOFReader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - panic("unexpected useless call") - } - p[0] = byte(b) - return 1, io.EOF -} - -// Issue 16788: the Transport had a regression where it started -// sending a spurious DATA frame with a duplicate END_STREAM bit after -// the request body writer goroutine had already read an EOF from the -// Request.Body and included the END_STREAM on a data-carrying DATA -// frame. -// -// Notably, to trigger this, the requests need to use a Request.Body -// which returns (non-0, io.EOF) and also needs to set the ContentLength -// explicitly. -func TestTransportBodyDoubleEndStream(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // Nothing. - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - for i := 0; i < 2; i++ { - req, _ := http.NewRequest("POST", st.ts.URL, byteAndEOFReader('a')) - req.ContentLength = 1 - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatalf("failure on req %d: %v", i+1, err) - } - defer res.Body.Close() - } -} - -// golang.org/issue/16847, golang.org/issue/19103 -func TestTransportRequestPathPseudo(t *testing.T) { - type result struct { - path string - err string - } - tests := []struct { - req *http.Request - want result - }{ - 0: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Host: "foo.com", - Path: "/foo", - }, - }, - want: result{path: "/foo"}, - }, - // In Go 1.7, we accepted paths of "//foo". - // In Go 1.8, we rejected it (issue 16847). - // In Go 1.9, we accepted it again (issue 19103). - 1: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Host: "foo.com", - Path: "//foo", - }, - }, - want: result{path: "//foo"}, - }, - - // Opaque with //$Matching_Hostname/path - 2: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "https", - Opaque: "//foo.com/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque with some other Request.Host instead: - 3: { - req: &http.Request{ - Method: "GET", - Host: "bar.com", - URL: &url.URL{ - Scheme: "https", - Opaque: "//bar.com/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque without the leading "//": - 4: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Opaque: "/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque we can't handle: - 5: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "https", - Opaque: "//unknown_host/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{err: `invalid request :path "https://unknown_host/path" from URL.Opaque = "//unknown_host/path"`}, - }, - - // A CONNECT request: - 6: { - req: &http.Request{ - Method: "CONNECT", - URL: &url.URL{ - Host: "foo.com", - }, - }, - want: result{}, - }, - } - for i, tt := range tests { - cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} - cc.henc = hpack.NewEncoder(&cc.hbuf) - cc.mu.Lock() - hdrs, err := cc.encodeHeaders(tt.req, false, "", -1) - cc.mu.Unlock() - var got result - hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) { - if f.Name == ":path" { - got.path = f.Value - } - }) - if err != nil { - got.err = err.Error() - } else if len(hdrs) > 0 { - if _, err := hpackDec.Write(hdrs); err != nil { - t.Errorf("%d. bogus hpack: %v", i, err) - continue - } - } - if got != tt.want { - t.Errorf("%d. got %+v; want %+v", i, got, tt.want) - } - - } - -} - -// golang.org/issue/17071 -- don't sniff the first byte of the request body -// before we've determined that the ClientConn is usable. -func TestRoundTripDoesntConsumeRequestBodyEarly(t *testing.T) { - const body = "foo" - req, _ := http.NewRequest("POST", "http://foo.com/", ioutil.NopCloser(strings.NewReader(body))) - cc := &ClientConn{ - closed: true, - } - _, err := cc.RoundTrip(req) - if err != errClientConnUnusable { - t.Fatalf("RoundTrip = %v; want errClientConnUnusable", err) - } - slurp, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ReadAll = %v", err) - } - if string(slurp) != body { - t.Errorf("Body = %q; want %q", slurp, body) - } -} - -func TestClientConnPing(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}, optOnlyServer) - defer st.Close() - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false) - if err != nil { - t.Fatal(err) - } - if err = cc.Ping(context.Background()); err != nil { - t.Fatal(err) - } -} - -// Issue 16974: if the server sent a DATA frame after the user -// canceled the Transport's Request, the Transport previously wrote to a -// closed pipe, got an error, and ended up closing the whole TCP -// connection. -func TestTransportCancelDataResponseRace(t *testing.T) { - cancel := make(chan struct{}) - clientGotError := make(chan bool, 1) - - const msg = "Hello." - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if strings.Contains(r.URL.Path, "/hello") { - time.Sleep(50 * time.Millisecond) - io.WriteString(w, msg) - return - } - for i := 0; i < 50; i++ { - io.WriteString(w, "Some data.") - w.(http.Flusher).Flush() - if i == 2 { - close(cancel) - <-clientGotError - } - time.Sleep(10 * time.Millisecond) - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - c := &http.Client{Transport: tr} - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Cancel = cancel - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - if _, err = io.Copy(ioutil.Discard, res.Body); err == nil { - t.Fatal("unexpected success") - } - clientGotError <- true - - res, err = c.Get(st.ts.URL + "/hello") - if err != nil { - t.Fatal(err) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(slurp) != msg { - t.Errorf("Got = %q; want %q", slurp, msg) - } -} - -// Issue 21316: It should be safe to reuse an http.Request after the -// request has completed. -func TestTransportNoRaceOnRequestObjectAfterRequestComplete(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) - io.WriteString(w, "body") - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, _ := http.NewRequest("GET", st.ts.URL, nil) - resp, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil { - t.Fatalf("error reading response body: %v", err) - } - if err := resp.Body.Close(); err != nil { - t.Fatalf("error closing response body: %v", err) - } - - // This access of req.Header should not race with code in the transport. - req.Header = http.Header{} -} - -func TestTransportRetryAfterGOAWAY(t *testing.T) { - var dialer struct { - sync.Mutex - count int - } - ct1 := make(chan *clientTester) - ct2 := make(chan *clientTester) - - ln := newLocalListener(t) - defer ln.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - } - tr.DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) { - dialer.Lock() - defer dialer.Unlock() - dialer.count++ - if dialer.count == 3 { - return nil, errors.New("unexpected number of dials") - } - cc, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - return nil, fmt.Errorf("dial error: %v", err) - } - sc, err := ln.Accept() - if err != nil { - return nil, fmt.Errorf("accept error: %v", err) - } - ct := &clientTester{ - t: t, - tr: tr, - cc: cc, - sc: sc, - fr: NewFramer(sc, sc), - } - switch dialer.count { - case 1: - ct1 <- ct - case 2: - ct2 <- ct - } - return cc, nil - } - - errs := make(chan error, 3) - done := make(chan struct{}) - defer close(done) - - // Client. - go func() { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := tr.RoundTrip(req) - if res != nil { - res.Body.Close() - if got := res.Header.Get("Foo"); got != "bar" { - err = fmt.Errorf("foo header = %q; want bar", got) - } - } - if err != nil { - err = fmt.Errorf("RoundTrip: %v", err) - } - errs <- err - }() - - connToClose := make(chan io.Closer, 2) - - // Server for the first request. - go func() { - var ct *clientTester - select { - case ct = <-ct1: - case <-done: - return - } - - connToClose <- ct.cc - ct.greet() - hf, err := ct.firstHeaders() - if err != nil { - errs <- fmt.Errorf("server1 failed reading HEADERS: %v", err) - return - } - t.Logf("server1 got %v", hf) - if err := ct.fr.WriteGoAway(0 /*max id*/, ErrCodeNo, nil); err != nil { - errs <- fmt.Errorf("server1 failed writing GOAWAY: %v", err) - return - } - errs <- nil - }() - - // Server for the second request. - go func() { - var ct *clientTester - select { - case ct = <-ct2: - case <-done: - return - } - - connToClose <- ct.cc - ct.greet() - hf, err := ct.firstHeaders() - if err != nil { - errs <- fmt.Errorf("server2 failed reading HEADERS: %v", err) - return - } - t.Logf("server2 got %v", hf) - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - err = ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - if err != nil { - errs <- fmt.Errorf("server2 failed writing response HEADERS: %v", err) - } else { - errs <- nil - } - }() - - for k := 0; k < 3; k++ { - select { - case err := <-errs: - if err != nil { - t.Error(err) - } - case <-time.After(1 * time.Second): - t.Errorf("timed out") - } - } - - for { - select { - case c := <-connToClose: - c.Close() - default: - return - } - } -} - -func TestTransportRetryAfterRefusedStream(t *testing.T) { - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - resp, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - resp.Body.Close() - if resp.StatusCode != 204 { - return fmt.Errorf("Status = %v; want 204", resp.StatusCode) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - nreq := 0 - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - nreq++ - if nreq == 1 { - ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) - } else { - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -func TestTransportRetryHasLimit(t *testing.T) { - // Skip in short mode because the total expected delay is 1s+2s+4s+8s+16s=29s. - if testing.Short() { - t.Skip("skipping long test in short mode") - } - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - resp, err := ct.tr.RoundTrip(req) - if err == nil { - return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) - } - t.Logf("expected error, got: %v", err) - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -func TestTransportResponseDataBeforeHeaders(t *testing.T) { - // This test use not valid response format. - // Discarding logger output to not spam tests output. - log.SetOutput(ioutil.Discard) - defer log.SetOutput(os.Stderr) - - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - req := httptest.NewRequest("GET", "https://dummy.tld/", nil) - // First request is normal to ensure the check is per stream and not per connection. - _, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip expected no error, got: %v", err) - } - // Second request returns a DATA frame with no HEADERS. - resp, err := ct.tr.RoundTrip(req) - if err == nil { - return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) - } - if err, ok := err.(StreamError); !ok || err.Code != ErrCodeProtocol { - return fmt.Errorf("expected stream PROTOCOL_ERROR, got: %v", err) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - switch f.StreamID { - case 1: - // Send a valid response to first request. - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - case 3: - ct.fr.WriteData(f.StreamID, true, []byte("payload")) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} -func TestTransportRequestsStallAtServerLimit(t *testing.T) { - const maxConcurrent = 2 - - greet := make(chan struct{}) // server sends initial SETTINGS frame - gotRequest := make(chan struct{}) // server received a request - clientDone := make(chan struct{}) - - // Collect errors from goroutines. - var wg sync.WaitGroup - errs := make(chan error, 100) - defer func() { - wg.Wait() - close(errs) - for err := range errs { - t.Error(err) - } - }() - - // We will send maxConcurrent+2 requests. This checker goroutine waits for the - // following stages: - // 1. The first maxConcurrent requests are received by the server. - // 2. The client will cancel the next request - // 3. The server is unblocked so it can service the first maxConcurrent requests - // 4. The client will send the final request - wg.Add(1) - unblockClient := make(chan struct{}) - clientRequestCancelled := make(chan struct{}) - unblockServer := make(chan struct{}) - go func() { - defer wg.Done() - // Stage 1. - for k := 0; k < maxConcurrent; k++ { - <-gotRequest - } - // Stage 2. - close(unblockClient) - <-clientRequestCancelled - // Stage 3: give some time for the final RoundTrip call to be scheduled and - // verify that the final request is not sent. - time.Sleep(50 * time.Millisecond) - select { - case <-gotRequest: - errs <- errors.New("last request did not stall") - close(unblockServer) - return - default: - } - close(unblockServer) - // Stage 4. - <-gotRequest - }() - - ct := newClientTester(t) - ct.client = func() error { - var wg sync.WaitGroup - defer func() { - wg.Wait() - close(clientDone) - ct.cc.(*net.TCPConn).CloseWrite() - }() - for k := 0; k < maxConcurrent+2; k++ { - wg.Add(1) - go func(k int) { - defer wg.Done() - // Don't send the second request until after receiving SETTINGS from the server - // to avoid a race where we use the default SettingMaxConcurrentStreams, which - // is much larger than maxConcurrent. We have to send the first request before - // waiting because the first request triggers the dial and greet. - if k > 0 { - <-greet - } - // Block until maxConcurrent requests are sent before sending any more. - if k >= maxConcurrent { - <-unblockClient - } - req, _ := http.NewRequest("GET", fmt.Sprintf("https://dummy.tld/%d", k), nil) - if k == maxConcurrent { - // This request will be canceled. - cancel := make(chan struct{}) - req.Cancel = cancel - close(cancel) - _, err := ct.tr.RoundTrip(req) - close(clientRequestCancelled) - if err == nil { - errs <- fmt.Errorf("RoundTrip(%d) should have failed due to cancel", k) - return - } - } else { - resp, err := ct.tr.RoundTrip(req) - if err != nil { - errs <- fmt.Errorf("RoundTrip(%d): %v", k, err) - return - } - ioutil.ReadAll(resp.Body) - resp.Body.Close() - if resp.StatusCode != 204 { - errs <- fmt.Errorf("Status = %v; want 204", resp.StatusCode) - return - } - } - }(k) - } - return nil - } - - ct.server = func() error { - var wg sync.WaitGroup - defer wg.Wait() - - ct.greet(Setting{SettingMaxConcurrentStreams, maxConcurrent}) - - // Server write loop. - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - writeResp := make(chan uint32, maxConcurrent+1) - - wg.Add(1) - go func() { - defer wg.Done() - <-unblockServer - for id := range writeResp { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: id, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - }() - - // Server read loop. - var nreq int - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it will have reported any errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame: - case *SettingsFrame: - // Wait for the client SETTINGS ack until ending the greet. - close(greet) - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - gotRequest <- struct{}{} - nreq++ - writeResp <- f.StreamID - if nreq == maxConcurrent+1 { - close(writeResp) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - - ct.run() -} - -func TestAuthorityAddr(t *testing.T) { - tests := []struct { - scheme, authority string - want string - }{ - {"http", "foo.com", "foo.com:80"}, - {"https", "foo.com", "foo.com:443"}, - {"https", "foo.com:1234", "foo.com:1234"}, - {"https", "1.2.3.4:1234", "1.2.3.4:1234"}, - {"https", "1.2.3.4", "1.2.3.4:443"}, - {"https", "[::1]:1234", "[::1]:1234"}, - {"https", "[::1]", "[::1]:443"}, - } - for _, tt := range tests { - got := authorityAddr(tt.scheme, tt.authority) - if got != tt.want { - t.Errorf("authorityAddr(%q, %q) = %q; want %q", tt.scheme, tt.authority, got, tt.want) - } - } -} - -// Issue 20448: stop allocating for DATA frames' payload after -// Response.Body.Close is called. -func TestTransportAllocationsAfterResponseBodyClose(t *testing.T) { - megabyteZero := make([]byte, 1<<20) - - writeErr := make(chan error, 1) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() - var sum int64 - for i := 0; i < 100; i++ { - n, err := w.Write(megabyteZero) - sum += int64(n) - if err != nil { - writeErr <- err - return - } - } - t.Logf("wrote all %d bytes", sum) - writeErr <- nil - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - var buf [1]byte - if _, err := res.Body.Read(buf[:]); err != nil { - t.Error(err) - } - if err := res.Body.Close(); err != nil { - t.Error(err) - } - - trb, ok := res.Body.(transportResponseBody) - if !ok { - t.Fatalf("res.Body = %T; want transportResponseBody", res.Body) - } - if trb.cs.bufPipe.b != nil { - t.Errorf("response body pipe is still open") - } - - gotErr := <-writeErr - if gotErr == nil { - t.Errorf("Handler unexpectedly managed to write its entire response without getting an error") - } else if gotErr != errStreamClosed { - t.Errorf("Handler Write err = %v; want errStreamClosed", gotErr) - } -} - -// Issue 18891: make sure Request.Body == NoBody means no DATA frame -// is ever sent, even if empty. -func TestTransportNoBodyMeansNoDATA(t *testing.T) { - ct := newClientTester(t) - - unblockClient := make(chan bool) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", go18httpNoBody()) - ct.tr.RoundTrip(req) - <-unblockClient - return nil - } - ct.server = func() error { - defer close(unblockClient) - defer ct.cc.(*net.TCPConn).Close() - ct.greet() - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f := f.(type) { - default: - return fmt.Errorf("Got %T; want HeadersFrame", f) - case *WindowUpdateFrame, *SettingsFrame: - continue - case *HeadersFrame: - if !f.StreamEnded() { - return fmt.Errorf("got headers frame without END_STREAM") - } - return nil - } - } - } - ct.run() -} - -func benchSimpleRoundTrip(b *testing.B, nHeaders int) { - defer disableGoroutineTracking()() - b.ReportAllocs() - st := newServerTester(b, - func(w http.ResponseWriter, r *http.Request) { - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - b.Fatal(err) - } - - for i := 0; i < nHeaders; i++ { - name := fmt.Sprint("A-", i) - req.Header.Set(name, "*") - } - - b.ResetTimer() - - for i := 0; i < b.N; i++ { - res, err := tr.RoundTrip(req) - if err != nil { - if res != nil { - res.Body.Close() - } - b.Fatalf("RoundTrip err = %v; want nil", err) - } - res.Body.Close() - if res.StatusCode != http.StatusOK { - b.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) - } - } -} - -type infiniteReader struct{} - -func (r infiniteReader) Read(b []byte) (int, error) { - return len(b), nil -} - -// Issue 20521: it is not an error to receive a response and end stream -// from the server without the body being consumed. -func TestTransportResponseAndResetWithoutConsumingBodyRace(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - // The request body needs to be big enough to trigger flow control. - req, _ := http.NewRequest("PUT", st.ts.URL, infiniteReader{}) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if res.StatusCode != http.StatusOK { - t.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) - } -} - -// Verify transport doesn't crash when receiving bogus response lacking a :status header. -// Issue 22880. -func TestTransportHandlesInvalidStatuslessResponse(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - _, err := ct.tr.RoundTrip(req) - const substr = "malformed response from server: missing status pseudo header" - if !strings.Contains(fmt.Sprint(err), substr) { - return fmt.Errorf("RoundTrip error = %v; want substring %q", err, substr) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *HeadersFrame: - enc.WriteField(hpack.HeaderField{Name: "content-type", Value: "text/html"}) // no :status header - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: false, // we'll send some DATA to try to crash the transport - BlockFragment: buf.Bytes(), - }) - ct.fr.WriteData(f.StreamID, true, []byte("payload")) - return nil - } - } - } - ct.run() -} - -func BenchmarkClientRequestHeaders(b *testing.B) { - b.Run(" 0 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 0) }) - b.Run(" 10 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 10) }) - b.Run(" 100 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 100) }) - b.Run("1000 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 1000) }) -} - -func activeStreams(cc *ClientConn) int { - cc.mu.Lock() - defer cc.mu.Unlock() - return len(cc.streams) -} - -type closeMode int - -const ( - closeAtHeaders closeMode = iota - closeAtBody - shutdown - shutdownCancel -) - -// See golang.org/issue/17292 -func testClientConnClose(t *testing.T, closeMode closeMode) { - clientDone := make(chan struct{}) - defer close(clientDone) - handlerDone := make(chan struct{}) - closeDone := make(chan struct{}) - beforeHeader := func() {} - bodyWrite := func(w http.ResponseWriter) {} - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - defer close(handlerDone) - beforeHeader() - w.WriteHeader(http.StatusOK) - w.(http.Flusher).Flush() - bodyWrite(w) - select { - case <-w.(http.CloseNotifier).CloseNotify(): - // client closed connection before completion - if closeMode == shutdown || closeMode == shutdownCancel { - t.Error("expected request to complete") - } - case <-clientDone: - if closeMode == closeAtHeaders || closeMode == closeAtBody { - t.Error("expected connection closed by client") - } - } - }, optOnlyServer) - defer st.Close() - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false) - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - if closeMode == closeAtHeaders { - beforeHeader = func() { - if err := cc.Close(); err != nil { - t.Error(err) - } - close(closeDone) - } - } - var sendBody chan struct{} - if closeMode == closeAtBody { - sendBody = make(chan struct{}) - bodyWrite = func(w http.ResponseWriter) { - <-sendBody - b := make([]byte, 32) - w.Write(b) - w.(http.Flusher).Flush() - if err := cc.Close(); err != nil { - t.Errorf("unexpected ClientConn close error: %v", err) - } - close(closeDone) - w.Write(b) - w.(http.Flusher).Flush() - } - } - res, err := cc.RoundTrip(req) - if res != nil { - defer res.Body.Close() - } - if closeMode == closeAtHeaders { - got := fmt.Sprint(err) - want := "http2: client connection force closed via ClientConn.Close" - if got != want { - t.Fatalf("RoundTrip error = %v, want %v", got, want) - } - } else { - if err != nil { - t.Fatalf("RoundTrip: %v", err) - } - if got, want := activeStreams(cc), 1; got != want { - t.Errorf("got %d active streams, want %d", got, want) - } - } - switch closeMode { - case shutdownCancel: - if err = cc.Shutdown(canceledCtx); err != errCanceled { - t.Errorf("got %v, want %v", err, errCanceled) - } - if cc.closing == false { - t.Error("expected closing to be true") - } - if cc.CanTakeNewRequest() == true { - t.Error("CanTakeNewRequest to return false") - } - if v, want := len(cc.streams), 1; v != want { - t.Errorf("expected %d active streams, got %d", want, v) - } - clientDone <- struct{}{} - <-handlerDone - case shutdown: - wait := make(chan struct{}) - shutdownEnterWaitStateHook = func() { - close(wait) - shutdownEnterWaitStateHook = func() {} - } - defer func() { shutdownEnterWaitStateHook = func() {} }() - shutdown := make(chan struct{}, 1) - go func() { - if err = cc.Shutdown(context.Background()); err != nil { - t.Error(err) - } - close(shutdown) - }() - // Let the shutdown to enter wait state - <-wait - cc.mu.Lock() - if cc.closing == false { - t.Error("expected closing to be true") - } - cc.mu.Unlock() - if cc.CanTakeNewRequest() == true { - t.Error("CanTakeNewRequest to return false") - } - if got, want := activeStreams(cc), 1; got != want { - t.Errorf("got %d active streams, want %d", got, want) - } - // Let the active request finish - clientDone <- struct{}{} - // Wait for the shutdown to end - select { - case <-shutdown: - case <-time.After(2 * time.Second): - t.Fatal("expected server connection to close") - } - case closeAtHeaders, closeAtBody: - if closeMode == closeAtBody { - go close(sendBody) - if _, err := io.Copy(ioutil.Discard, res.Body); err == nil { - t.Error("expected a Copy error, got nil") - } - } - <-closeDone - if got, want := activeStreams(cc), 0; got != want { - t.Errorf("got %d active streams, want %d", got, want) - } - // wait for server to get the connection close notice - select { - case <-handlerDone: - case <-time.After(2 * time.Second): - t.Fatal("expected server connection to close") - } - } -} - -// The client closes the connection just after the server got the client's HEADERS -// frame, but before the server sends its HEADERS response back. The expected -// result is an error on RoundTrip explaining the client closed the connection. -func TestClientConnCloseAtHeaders(t *testing.T) { - testClientConnClose(t, closeAtHeaders) -} - -// The client closes the connection between two server's response DATA frames. -// The expected behavior is a response body io read error on the client. -func TestClientConnCloseAtBody(t *testing.T) { - testClientConnClose(t, closeAtBody) -} - -// The client sends a GOAWAY frame before the server finished processing a request. -// We expect the connection not to close until the request is completed. -func TestClientConnShutdown(t *testing.T) { - testClientConnClose(t, shutdown) -} - -// The client sends a GOAWAY frame before the server finishes processing a request, -// but cancels the passed context before the request is completed. The expected -// behavior is the client closing the connection after the context is canceled. -func TestClientConnShutdownCancel(t *testing.T) { - testClientConnClose(t, shutdownCancel) -} - -// Issue 25009: use Request.GetBody if present, even if it seems like -// we might not need it. Apparently something else can still read from -// the original request body. Data race? In any case, rewinding -// unconditionally on retry is a nicer model anyway and should -// simplify code in the future (after the Go 1.11 freeze) -func TestTransportUsesGetBodyWhenPresent(t *testing.T) { - calls := 0 - someBody := func() io.ReadCloser { - return struct{ io.ReadCloser }{ioutil.NopCloser(bytes.NewReader(nil))} - } - req := &http.Request{ - Body: someBody(), - GetBody: func() (io.ReadCloser, error) { - calls++ - return someBody(), nil - }, - } - - afterBodyWrite := false // pretend we haven't read+written the body yet - req2, err := shouldRetryRequest(req, errClientConnUnusable, afterBodyWrite) - if err != nil { - t.Fatal(err) - } - if calls != 1 { - t.Errorf("Calls = %d; want 1", calls) - } - if req2 == req { - t.Error("req2 changed") - } - if req2 == nil { - t.Fatal("req2 is nil") - } - if req2.Body == nil { - t.Fatal("req2.Body is nil") - } - if req2.GetBody == nil { - t.Fatal("req2.GetBody is nil") - } - if req2.Body == req.Body { - t.Error("req2.Body unchanged") - } -} - -// Issue 22891: verify that the "https" altproto we register with net/http -// is a certain type: a struct with one field with our *http2.Transport in it. -func TestNoDialH2RoundTripperType(t *testing.T) { - t1 := new(http.Transport) - t2 := new(Transport) - rt := noDialH2RoundTripper{t2} - if err := registerHTTPSProtocol(t1, rt); err != nil { - t.Fatal(err) - } - rv := reflect.ValueOf(rt) - if rv.Type().Kind() != reflect.Struct { - t.Fatalf("kind = %v; net/http expects struct", rv.Type().Kind()) - } - if n := rv.Type().NumField(); n != 1 { - t.Fatalf("fields = %d; net/http expects 1", n) - } - v := rv.Field(0) - if _, ok := v.Interface().(*Transport); !ok { - t.Fatalf("wrong kind %T; want *Transport", v.Interface()) - } -} diff --git a/examples/golang.org/x/net/http2/write.go b/examples/golang.org/x/net/http2/write.go deleted file mode 100644 index 8a9711f..0000000 --- a/examples/golang.org/x/net/http2/write.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "fmt" - "log" - "net/http" - "net/url" - - "golang.org/x/net/http/httpguts" - "golang.org/x/net/http2/hpack" -) - -// writeFramer is implemented by any type that is used to write frames. -type writeFramer interface { - writeFrame(writeContext) error - - // staysWithinBuffer reports whether this writer promises that - // it will only write less than or equal to size bytes, and it - // won't Flush the write context. - staysWithinBuffer(size int) bool -} - -// writeContext is the interface needed by the various frame writer -// types below. All the writeFrame methods below are scheduled via the -// frame writing scheduler (see writeScheduler in writesched.go). -// -// This interface is implemented by *serverConn. -// -// TODO: decide whether to a) use this in the client code (which didn't -// end up using this yet, because it has a simpler design, not -// currently implementing priorities), or b) delete this and -// make the server code a bit more concrete. -type writeContext interface { - Framer() *Framer - Flush() error - CloseConn() error - // HeaderEncoder returns an HPACK encoder that writes to the - // returned buffer. - HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) -} - -// writeEndsStream reports whether w writes a frame that will transition -// the stream to a half-closed local state. This returns false for RST_STREAM, -// which closes the entire stream (not just the local half). -func writeEndsStream(w writeFramer) bool { - switch v := w.(type) { - case *writeData: - return v.endStream - case *writeResHeaders: - return v.endStream - case nil: - // This can only happen if the caller reuses w after it's - // been intentionally nil'ed out to prevent use. Keep this - // here to catch future refactoring breaking it. - panic("writeEndsStream called on nil writeFramer") - } - return false -} - -type flushFrameWriter struct{} - -func (flushFrameWriter) writeFrame(ctx writeContext) error { - return ctx.Flush() -} - -func (flushFrameWriter) staysWithinBuffer(max int) bool { return false } - -type writeSettings []Setting - -func (s writeSettings) staysWithinBuffer(max int) bool { - const settingSize = 6 // uint16 + uint32 - return frameHeaderLen+settingSize*len(s) <= max - -} - -func (s writeSettings) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteSettings([]Setting(s)...) -} - -type writeGoAway struct { - maxStreamID uint32 - code ErrCode -} - -func (p *writeGoAway) writeFrame(ctx writeContext) error { - err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil) - ctx.Flush() // ignore error: we're hanging up on them anyway - return err -} - -func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes - -type writeData struct { - streamID uint32 - p []byte - endStream bool -} - -func (w *writeData) String() string { - return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream) -} - -func (w *writeData) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteData(w.streamID, w.endStream, w.p) -} - -func (w *writeData) staysWithinBuffer(max int) bool { - return frameHeaderLen+len(w.p) <= max -} - -// handlerPanicRST is the message sent from handler goroutines when -// the handler panics. -type handlerPanicRST struct { - StreamID uint32 -} - -func (hp handlerPanicRST) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal) -} - -func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } - -func (se StreamError) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteRSTStream(se.StreamID, se.Code) -} - -func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } - -type writePingAck struct{ pf *PingFrame } - -func (w writePingAck) writeFrame(ctx writeContext) error { - return ctx.Framer().WritePing(true, w.pf.Data) -} - -func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max } - -type writeSettingsAck struct{} - -func (writeSettingsAck) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteSettingsAck() -} - -func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max } - -// splitHeaderBlock splits headerBlock into fragments so that each fragment fits -// in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true -// for the first/last fragment, respectively. -func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error { - // For now we're lazy and just pick the minimum MAX_FRAME_SIZE - // that all peers must support (16KB). Later we could care - // more and send larger frames if the peer advertised it, but - // there's little point. Most headers are small anyway (so we - // generally won't have CONTINUATION frames), and extra frames - // only waste 9 bytes anyway. - const maxFrameSize = 16384 - - first := true - for len(headerBlock) > 0 { - frag := headerBlock - if len(frag) > maxFrameSize { - frag = frag[:maxFrameSize] - } - headerBlock = headerBlock[len(frag):] - if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil { - return err - } - first = false - } - return nil -} - -// writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames -// for HTTP response headers or trailers from a server handler. -type writeResHeaders struct { - streamID uint32 - httpResCode int // 0 means no ":status" line - h http.Header // may be nil - trailers []string // if non-nil, which keys of h to write. nil means all. - endStream bool - - date string - contentType string - contentLength string -} - -func encKV(enc *hpack.Encoder, k, v string) { - if VerboseLogs { - log.Printf("http2: server encoding header %q = %q", k, v) - } - enc.WriteField(hpack.HeaderField{Name: k, Value: v}) -} - -func (w *writeResHeaders) staysWithinBuffer(max int) bool { - // TODO: this is a common one. It'd be nice to return true - // here and get into the fast path if we could be clever and - // calculate the size fast enough, or at least a conservative - // uppper bound that usually fires. (Maybe if w.h and - // w.trailers are nil, so we don't need to enumerate it.) - // Otherwise I'm afraid that just calculating the length to - // answer this question would be slower than the ~2µs benefit. - return false -} - -func (w *writeResHeaders) writeFrame(ctx writeContext) error { - enc, buf := ctx.HeaderEncoder() - buf.Reset() - - if w.httpResCode != 0 { - encKV(enc, ":status", httpCodeString(w.httpResCode)) - } - - encodeHeaders(enc, w.h, w.trailers) - - if w.contentType != "" { - encKV(enc, "content-type", w.contentType) - } - if w.contentLength != "" { - encKV(enc, "content-length", w.contentLength) - } - if w.date != "" { - encKV(enc, "date", w.date) - } - - headerBlock := buf.Bytes() - if len(headerBlock) == 0 && w.trailers == nil { - panic("unexpected empty hpack") - } - - return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) -} - -func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { - if firstFrag { - return ctx.Framer().WriteHeaders(HeadersFrameParam{ - StreamID: w.streamID, - BlockFragment: frag, - EndStream: w.endStream, - EndHeaders: lastFrag, - }) - } else { - return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) - } -} - -// writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames. -type writePushPromise struct { - streamID uint32 // pusher stream - method string // for :method - url *url.URL // for :scheme, :authority, :path - h http.Header - - // Creates an ID for a pushed stream. This runs on serveG just before - // the frame is written. The returned ID is copied to promisedID. - allocatePromisedID func() (uint32, error) - promisedID uint32 -} - -func (w *writePushPromise) staysWithinBuffer(max int) bool { - // TODO: see writeResHeaders.staysWithinBuffer - return false -} - -func (w *writePushPromise) writeFrame(ctx writeContext) error { - enc, buf := ctx.HeaderEncoder() - buf.Reset() - - encKV(enc, ":method", w.method) - encKV(enc, ":scheme", w.url.Scheme) - encKV(enc, ":authority", w.url.Host) - encKV(enc, ":path", w.url.RequestURI()) - encodeHeaders(enc, w.h, nil) - - headerBlock := buf.Bytes() - if len(headerBlock) == 0 { - panic("unexpected empty hpack") - } - - return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock) -} - -func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error { - if firstFrag { - return ctx.Framer().WritePushPromise(PushPromiseParam{ - StreamID: w.streamID, - PromiseID: w.promisedID, - BlockFragment: frag, - EndHeaders: lastFrag, - }) - } else { - return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag) - } -} - -type write100ContinueHeadersFrame struct { - streamID uint32 -} - -func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error { - enc, buf := ctx.HeaderEncoder() - buf.Reset() - encKV(enc, ":status", "100") - return ctx.Framer().WriteHeaders(HeadersFrameParam{ - StreamID: w.streamID, - BlockFragment: buf.Bytes(), - EndStream: false, - EndHeaders: true, - }) -} - -func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool { - // Sloppy but conservative: - return 9+2*(len(":status")+len("100")) <= max -} - -type writeWindowUpdate struct { - streamID uint32 // or 0 for conn-level - n uint32 -} - -func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max } - -func (wu writeWindowUpdate) writeFrame(ctx writeContext) error { - return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n) -} - -// encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k]) -// is encoded only only if k is in keys. -func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) { - if keys == nil { - sorter := sorterPool.Get().(*sorter) - // Using defer here, since the returned keys from the - // sorter.Keys method is only valid until the sorter - // is returned: - defer sorterPool.Put(sorter) - keys = sorter.Keys(h) - } - for _, k := range keys { - vv := h[k] - k = lowerHeader(k) - if !validWireHeaderFieldName(k) { - // Skip it as backup paranoia. Per - // golang.org/issue/14048, these should - // already be rejected at a higher level. - continue - } - isTE := k == "transfer-encoding" - for _, v := range vv { - if !httpguts.ValidHeaderFieldValue(v) { - // TODO: return an error? golang.org/issue/14048 - // For now just omit it. - continue - } - // TODO: more of "8.1.2.2 Connection-Specific Header Fields" - if isTE && v != "trailers" { - continue - } - encKV(enc, k, v) - } - } -} diff --git a/examples/golang.org/x/net/http2/writesched.go b/examples/golang.org/x/net/http2/writesched.go deleted file mode 100644 index 4fe3073..0000000 --- a/examples/golang.org/x/net/http2/writesched.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "fmt" - -// WriteScheduler is the interface implemented by HTTP/2 write schedulers. -// Methods are never called concurrently. -type WriteScheduler interface { - // OpenStream opens a new stream in the write scheduler. - // It is illegal to call this with streamID=0 or with a streamID that is - // already open -- the call may panic. - OpenStream(streamID uint32, options OpenStreamOptions) - - // CloseStream closes a stream in the write scheduler. Any frames queued on - // this stream should be discarded. It is illegal to call this on a stream - // that is not open -- the call may panic. - CloseStream(streamID uint32) - - // AdjustStream adjusts the priority of the given stream. This may be called - // on a stream that has not yet been opened or has been closed. Note that - // RFC 7540 allows PRIORITY frames to be sent on streams in any state. See: - // https://tools.ietf.org/html/rfc7540#section-5.1 - AdjustStream(streamID uint32, priority PriorityParam) - - // Push queues a frame in the scheduler. In most cases, this will not be - // called with wr.StreamID()!=0 unless that stream is currently open. The one - // exception is RST_STREAM frames, which may be sent on idle or closed streams. - Push(wr FrameWriteRequest) - - // Pop dequeues the next frame to write. Returns false if no frames can - // be written. Frames with a given wr.StreamID() are Pop'd in the same - // order they are Push'd. - Pop() (wr FrameWriteRequest, ok bool) -} - -// OpenStreamOptions specifies extra options for WriteScheduler.OpenStream. -type OpenStreamOptions struct { - // PusherID is zero if the stream was initiated by the client. Otherwise, - // PusherID names the stream that pushed the newly opened stream. - PusherID uint32 -} - -// FrameWriteRequest is a request to write a frame. -type FrameWriteRequest struct { - // write is the interface value that does the writing, once the - // WriteScheduler has selected this frame to write. The write - // functions are all defined in write.go. - write writeFramer - - // stream is the stream on which this frame will be written. - // nil for non-stream frames like PING and SETTINGS. - stream *stream - - // done, if non-nil, must be a buffered channel with space for - // 1 message and is sent the return value from write (or an - // earlier error) when the frame has been written. - done chan error -} - -// StreamID returns the id of the stream this frame will be written to. -// 0 is used for non-stream frames such as PING and SETTINGS. -func (wr FrameWriteRequest) StreamID() uint32 { - if wr.stream == nil { - if se, ok := wr.write.(StreamError); ok { - // (*serverConn).resetStream doesn't set - // stream because it doesn't necessarily have - // one. So special case this type of write - // message. - return se.StreamID - } - return 0 - } - return wr.stream.id -} - -// DataSize returns the number of flow control bytes that must be consumed -// to write this entire frame. This is 0 for non-DATA frames. -func (wr FrameWriteRequest) DataSize() int { - if wd, ok := wr.write.(*writeData); ok { - return len(wd.p) - } - return 0 -} - -// Consume consumes min(n, available) bytes from this frame, where available -// is the number of flow control bytes available on the stream. Consume returns -// 0, 1, or 2 frames, where the integer return value gives the number of frames -// returned. -// -// If flow control prevents consuming any bytes, this returns (_, _, 0). If -// the entire frame was consumed, this returns (wr, _, 1). Otherwise, this -// returns (consumed, rest, 2), where 'consumed' contains the consumed bytes and -// 'rest' contains the remaining bytes. The consumed bytes are deducted from the -// underlying stream's flow control budget. -func (wr FrameWriteRequest) Consume(n int32) (FrameWriteRequest, FrameWriteRequest, int) { - var empty FrameWriteRequest - - // Non-DATA frames are always consumed whole. - wd, ok := wr.write.(*writeData) - if !ok || len(wd.p) == 0 { - return wr, empty, 1 - } - - // Might need to split after applying limits. - allowed := wr.stream.flow.available() - if n < allowed { - allowed = n - } - if wr.stream.sc.maxFrameSize < allowed { - allowed = wr.stream.sc.maxFrameSize - } - if allowed <= 0 { - return empty, empty, 0 - } - if len(wd.p) > int(allowed) { - wr.stream.flow.take(allowed) - consumed := FrameWriteRequest{ - stream: wr.stream, - write: &writeData{ - streamID: wd.streamID, - p: wd.p[:allowed], - // Even if the original had endStream set, there - // are bytes remaining because len(wd.p) > allowed, - // so we know endStream is false. - endStream: false, - }, - // Our caller is blocking on the final DATA frame, not - // this intermediate frame, so no need to wait. - done: nil, - } - rest := FrameWriteRequest{ - stream: wr.stream, - write: &writeData{ - streamID: wd.streamID, - p: wd.p[allowed:], - endStream: wd.endStream, - }, - done: wr.done, - } - return consumed, rest, 2 - } - - // The frame is consumed whole. - // NB: This cast cannot overflow because allowed is <= math.MaxInt32. - wr.stream.flow.take(int32(len(wd.p))) - return wr, empty, 1 -} - -// String is for debugging only. -func (wr FrameWriteRequest) String() string { - var des string - if s, ok := wr.write.(fmt.Stringer); ok { - des = s.String() - } else { - des = fmt.Sprintf("%T", wr.write) - } - return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des) -} - -// replyToWriter sends err to wr.done and panics if the send must block -// This does nothing if wr.done is nil. -func (wr *FrameWriteRequest) replyToWriter(err error) { - if wr.done == nil { - return - } - select { - case wr.done <- err: - default: - panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write)) - } - wr.write = nil // prevent use (assume it's tainted after wr.done send) -} - -// writeQueue is used by implementations of WriteScheduler. -type writeQueue struct { - s []FrameWriteRequest -} - -func (q *writeQueue) empty() bool { return len(q.s) == 0 } - -func (q *writeQueue) push(wr FrameWriteRequest) { - q.s = append(q.s, wr) -} - -func (q *writeQueue) shift() FrameWriteRequest { - if len(q.s) == 0 { - panic("invalid use of queue") - } - wr := q.s[0] - // TODO: less copy-happy queue. - copy(q.s, q.s[1:]) - q.s[len(q.s)-1] = FrameWriteRequest{} - q.s = q.s[:len(q.s)-1] - return wr -} - -// consume consumes up to n bytes from q.s[0]. If the frame is -// entirely consumed, it is removed from the queue. If the frame -// is partially consumed, the frame is kept with the consumed -// bytes removed. Returns true iff any bytes were consumed. -func (q *writeQueue) consume(n int32) (FrameWriteRequest, bool) { - if len(q.s) == 0 { - return FrameWriteRequest{}, false - } - consumed, rest, numresult := q.s[0].Consume(n) - switch numresult { - case 0: - return FrameWriteRequest{}, false - case 1: - q.shift() - case 2: - q.s[0] = rest - } - return consumed, true -} - -type writeQueuePool []*writeQueue - -// put inserts an unused writeQueue into the pool. -func (p *writeQueuePool) put(q *writeQueue) { - for i := range q.s { - q.s[i] = FrameWriteRequest{} - } - q.s = q.s[:0] - *p = append(*p, q) -} - -// get returns an empty writeQueue. -func (p *writeQueuePool) get() *writeQueue { - ln := len(*p) - if ln == 0 { - return new(writeQueue) - } - x := ln - 1 - q := (*p)[x] - (*p)[x] = nil - *p = (*p)[:x] - return q -} diff --git a/examples/golang.org/x/net/http2/writesched_priority.go b/examples/golang.org/x/net/http2/writesched_priority.go deleted file mode 100644 index 848fed6..0000000 --- a/examples/golang.org/x/net/http2/writesched_priority.go +++ /dev/null @@ -1,452 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "fmt" - "math" - "sort" -) - -// RFC 7540, Section 5.3.5: the default weight is 16. -const priorityDefaultWeight = 15 // 16 = 15 + 1 - -// PriorityWriteSchedulerConfig configures a priorityWriteScheduler. -type PriorityWriteSchedulerConfig struct { - // MaxClosedNodesInTree controls the maximum number of closed streams to - // retain in the priority tree. Setting this to zero saves a small amount - // of memory at the cost of performance. - // - // See RFC 7540, Section 5.3.4: - // "It is possible for a stream to become closed while prioritization - // information ... is in transit. ... This potentially creates suboptimal - // prioritization, since the stream could be given a priority that is - // different from what is intended. To avoid these problems, an endpoint - // SHOULD retain stream prioritization state for a period after streams - // become closed. The longer state is retained, the lower the chance that - // streams are assigned incorrect or default priority values." - MaxClosedNodesInTree int - - // MaxIdleNodesInTree controls the maximum number of idle streams to - // retain in the priority tree. Setting this to zero saves a small amount - // of memory at the cost of performance. - // - // See RFC 7540, Section 5.3.4: - // Similarly, streams that are in the "idle" state can be assigned - // priority or become a parent of other streams. This allows for the - // creation of a grouping node in the dependency tree, which enables - // more flexible expressions of priority. Idle streams begin with a - // default priority (Section 5.3.5). - MaxIdleNodesInTree int - - // ThrottleOutOfOrderWrites enables write throttling to help ensure that - // data is delivered in priority order. This works around a race where - // stream B depends on stream A and both streams are about to call Write - // to queue DATA frames. If B wins the race, a naive scheduler would eagerly - // write as much data from B as possible, but this is suboptimal because A - // is a higher-priority stream. With throttling enabled, we write a small - // amount of data from B to minimize the amount of bandwidth that B can - // steal from A. - ThrottleOutOfOrderWrites bool -} - -// NewPriorityWriteScheduler constructs a WriteScheduler that schedules -// frames by following HTTP/2 priorities as described in RFC 7540 Section 5.3. -// If cfg is nil, default options are used. -func NewPriorityWriteScheduler(cfg *PriorityWriteSchedulerConfig) WriteScheduler { - if cfg == nil { - // For justification of these defaults, see: - // https://docs.google.com/document/d/1oLhNg1skaWD4_DtaoCxdSRN5erEXrH-KnLrMwEpOtFY - cfg = &PriorityWriteSchedulerConfig{ - MaxClosedNodesInTree: 10, - MaxIdleNodesInTree: 10, - ThrottleOutOfOrderWrites: false, - } - } - - ws := &priorityWriteScheduler{ - nodes: make(map[uint32]*priorityNode), - maxClosedNodesInTree: cfg.MaxClosedNodesInTree, - maxIdleNodesInTree: cfg.MaxIdleNodesInTree, - enableWriteThrottle: cfg.ThrottleOutOfOrderWrites, - } - ws.nodes[0] = &ws.root - if cfg.ThrottleOutOfOrderWrites { - ws.writeThrottleLimit = 1024 - } else { - ws.writeThrottleLimit = math.MaxInt32 - } - return ws -} - -type priorityNodeState int - -const ( - priorityNodeOpen priorityNodeState = iota - priorityNodeClosed - priorityNodeIdle -) - -// priorityNode is a node in an HTTP/2 priority tree. -// Each node is associated with a single stream ID. -// See RFC 7540, Section 5.3. -type priorityNode struct { - q writeQueue // queue of pending frames to write - id uint32 // id of the stream, or 0 for the root of the tree - weight uint8 // the actual weight is weight+1, so the value is in [1,256] - state priorityNodeState // open | closed | idle - bytes int64 // number of bytes written by this node, or 0 if closed - subtreeBytes int64 // sum(node.bytes) of all nodes in this subtree - - // These links form the priority tree. - parent *priorityNode - kids *priorityNode // start of the kids list - prev, next *priorityNode // doubly-linked list of siblings -} - -func (n *priorityNode) setParent(parent *priorityNode) { - if n == parent { - panic("setParent to self") - } - if n.parent == parent { - return - } - // Unlink from current parent. - if parent := n.parent; parent != nil { - if n.prev == nil { - parent.kids = n.next - } else { - n.prev.next = n.next - } - if n.next != nil { - n.next.prev = n.prev - } - } - // Link to new parent. - // If parent=nil, remove n from the tree. - // Always insert at the head of parent.kids (this is assumed by walkReadyInOrder). - n.parent = parent - if parent == nil { - n.next = nil - n.prev = nil - } else { - n.next = parent.kids - n.prev = nil - if n.next != nil { - n.next.prev = n - } - parent.kids = n - } -} - -func (n *priorityNode) addBytes(b int64) { - n.bytes += b - for ; n != nil; n = n.parent { - n.subtreeBytes += b - } -} - -// walkReadyInOrder iterates over the tree in priority order, calling f for each node -// with a non-empty write queue. When f returns true, this funcion returns true and the -// walk halts. tmp is used as scratch space for sorting. -// -// f(n, openParent) takes two arguments: the node to visit, n, and a bool that is true -// if any ancestor p of n is still open (ignoring the root node). -func (n *priorityNode) walkReadyInOrder(openParent bool, tmp *[]*priorityNode, f func(*priorityNode, bool) bool) bool { - if !n.q.empty() && f(n, openParent) { - return true - } - if n.kids == nil { - return false - } - - // Don't consider the root "open" when updating openParent since - // we can't send data frames on the root stream (only control frames). - if n.id != 0 { - openParent = openParent || (n.state == priorityNodeOpen) - } - - // Common case: only one kid or all kids have the same weight. - // Some clients don't use weights; other clients (like web browsers) - // use mostly-linear priority trees. - w := n.kids.weight - needSort := false - for k := n.kids.next; k != nil; k = k.next { - if k.weight != w { - needSort = true - break - } - } - if !needSort { - for k := n.kids; k != nil; k = k.next { - if k.walkReadyInOrder(openParent, tmp, f) { - return true - } - } - return false - } - - // Uncommon case: sort the child nodes. We remove the kids from the parent, - // then re-insert after sorting so we can reuse tmp for future sort calls. - *tmp = (*tmp)[:0] - for n.kids != nil { - *tmp = append(*tmp, n.kids) - n.kids.setParent(nil) - } - sort.Sort(sortPriorityNodeSiblings(*tmp)) - for i := len(*tmp) - 1; i >= 0; i-- { - (*tmp)[i].setParent(n) // setParent inserts at the head of n.kids - } - for k := n.kids; k != nil; k = k.next { - if k.walkReadyInOrder(openParent, tmp, f) { - return true - } - } - return false -} - -type sortPriorityNodeSiblings []*priorityNode - -func (z sortPriorityNodeSiblings) Len() int { return len(z) } -func (z sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] } -func (z sortPriorityNodeSiblings) Less(i, k int) bool { - // Prefer the subtree that has sent fewer bytes relative to its weight. - // See sections 5.3.2 and 5.3.4. - wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes) - wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes) - if bi == 0 && bk == 0 { - return wi >= wk - } - if bk == 0 { - return false - } - return bi/bk <= wi/wk -} - -type priorityWriteScheduler struct { - // root is the root of the priority tree, where root.id = 0. - // The root queues control frames that are not associated with any stream. - root priorityNode - - // nodes maps stream ids to priority tree nodes. - nodes map[uint32]*priorityNode - - // maxID is the maximum stream id in nodes. - maxID uint32 - - // lists of nodes that have been closed or are idle, but are kept in - // the tree for improved prioritization. When the lengths exceed either - // maxClosedNodesInTree or maxIdleNodesInTree, old nodes are discarded. - closedNodes, idleNodes []*priorityNode - - // From the config. - maxClosedNodesInTree int - maxIdleNodesInTree int - writeThrottleLimit int32 - enableWriteThrottle bool - - // tmp is scratch space for priorityNode.walkReadyInOrder to reduce allocations. - tmp []*priorityNode - - // pool of empty queues for reuse. - queuePool writeQueuePool -} - -func (ws *priorityWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { - // The stream may be currently idle but cannot be opened or closed. - if curr := ws.nodes[streamID]; curr != nil { - if curr.state != priorityNodeIdle { - panic(fmt.Sprintf("stream %d already opened", streamID)) - } - curr.state = priorityNodeOpen - return - } - - // RFC 7540, Section 5.3.5: - // "All streams are initially assigned a non-exclusive dependency on stream 0x0. - // Pushed streams initially depend on their associated stream. In both cases, - // streams are assigned a default weight of 16." - parent := ws.nodes[options.PusherID] - if parent == nil { - parent = &ws.root - } - n := &priorityNode{ - q: *ws.queuePool.get(), - id: streamID, - weight: priorityDefaultWeight, - state: priorityNodeOpen, - } - n.setParent(parent) - ws.nodes[streamID] = n - if streamID > ws.maxID { - ws.maxID = streamID - } -} - -func (ws *priorityWriteScheduler) CloseStream(streamID uint32) { - if streamID == 0 { - panic("violation of WriteScheduler interface: cannot close stream 0") - } - if ws.nodes[streamID] == nil { - panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID)) - } - if ws.nodes[streamID].state != priorityNodeOpen { - panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID)) - } - - n := ws.nodes[streamID] - n.state = priorityNodeClosed - n.addBytes(-n.bytes) - - q := n.q - ws.queuePool.put(&q) - n.q.s = nil - if ws.maxClosedNodesInTree > 0 { - ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n) - } else { - ws.removeNode(n) - } -} - -func (ws *priorityWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { - if streamID == 0 { - panic("adjustPriority on root") - } - - // If streamID does not exist, there are two cases: - // - A closed stream that has been removed (this will have ID <= maxID) - // - An idle stream that is being used for "grouping" (this will have ID > maxID) - n := ws.nodes[streamID] - if n == nil { - if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 { - return - } - ws.maxID = streamID - n = &priorityNode{ - q: *ws.queuePool.get(), - id: streamID, - weight: priorityDefaultWeight, - state: priorityNodeIdle, - } - n.setParent(&ws.root) - ws.nodes[streamID] = n - ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n) - } - - // Section 5.3.1: A dependency on a stream that is not currently in the tree - // results in that stream being given a default priority (Section 5.3.5). - parent := ws.nodes[priority.StreamDep] - if parent == nil { - n.setParent(&ws.root) - n.weight = priorityDefaultWeight - return - } - - // Ignore if the client tries to make a node its own parent. - if n == parent { - return - } - - // Section 5.3.3: - // "If a stream is made dependent on one of its own dependencies, the - // formerly dependent stream is first moved to be dependent on the - // reprioritized stream's previous parent. The moved dependency retains - // its weight." - // - // That is: if parent depends on n, move parent to depend on n.parent. - for x := parent.parent; x != nil; x = x.parent { - if x == n { - parent.setParent(n.parent) - break - } - } - - // Section 5.3.3: The exclusive flag causes the stream to become the sole - // dependency of its parent stream, causing other dependencies to become - // dependent on the exclusive stream. - if priority.Exclusive { - k := parent.kids - for k != nil { - next := k.next - if k != n { - k.setParent(n) - } - k = next - } - } - - n.setParent(parent) - n.weight = priority.Weight -} - -func (ws *priorityWriteScheduler) Push(wr FrameWriteRequest) { - var n *priorityNode - if id := wr.StreamID(); id == 0 { - n = &ws.root - } else { - n = ws.nodes[id] - if n == nil { - // id is an idle or closed stream. wr should not be a HEADERS or - // DATA frame. However, wr can be a RST_STREAM. In this case, we - // push wr onto the root, rather than creating a new priorityNode, - // since RST_STREAM is tiny and the stream's priority is unknown - // anyway. See issue #17919. - if wr.DataSize() > 0 { - panic("add DATA on non-open stream") - } - n = &ws.root - } - } - n.q.push(wr) -} - -func (ws *priorityWriteScheduler) Pop() (wr FrameWriteRequest, ok bool) { - ws.root.walkReadyInOrder(false, &ws.tmp, func(n *priorityNode, openParent bool) bool { - limit := int32(math.MaxInt32) - if openParent { - limit = ws.writeThrottleLimit - } - wr, ok = n.q.consume(limit) - if !ok { - return false - } - n.addBytes(int64(wr.DataSize())) - // If B depends on A and B continuously has data available but A - // does not, gradually increase the throttling limit to allow B to - // steal more and more bandwidth from A. - if openParent { - ws.writeThrottleLimit += 1024 - if ws.writeThrottleLimit < 0 { - ws.writeThrottleLimit = math.MaxInt32 - } - } else if ws.enableWriteThrottle { - ws.writeThrottleLimit = 1024 - } - return true - }) - return wr, ok -} - -func (ws *priorityWriteScheduler) addClosedOrIdleNode(list *[]*priorityNode, maxSize int, n *priorityNode) { - if maxSize == 0 { - return - } - if len(*list) == maxSize { - // Remove the oldest node, then shift left. - ws.removeNode((*list)[0]) - x := (*list)[1:] - copy(*list, x) - *list = (*list)[:len(x)] - } - *list = append(*list, n) -} - -func (ws *priorityWriteScheduler) removeNode(n *priorityNode) { - for k := n.kids; k != nil; k = k.next { - k.setParent(n.parent) - } - n.setParent(nil) - delete(ws.nodes, n.id) -} diff --git a/examples/golang.org/x/net/http2/writesched_priority_test.go b/examples/golang.org/x/net/http2/writesched_priority_test.go deleted file mode 100644 index f2b535a..0000000 --- a/examples/golang.org/x/net/http2/writesched_priority_test.go +++ /dev/null @@ -1,541 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "fmt" - "sort" - "testing" -) - -func defaultPriorityWriteScheduler() *priorityWriteScheduler { - return NewPriorityWriteScheduler(nil).(*priorityWriteScheduler) -} - -func checkPriorityWellFormed(ws *priorityWriteScheduler) error { - for id, n := range ws.nodes { - if id != n.id { - return fmt.Errorf("bad ws.nodes: ws.nodes[%d] = %d", id, n.id) - } - if n.parent == nil { - if n.next != nil || n.prev != nil { - return fmt.Errorf("bad node %d: nil parent but prev/next not nil", id) - } - continue - } - found := false - for k := n.parent.kids; k != nil; k = k.next { - if k.id == id { - found = true - break - } - } - if !found { - return fmt.Errorf("bad node %d: not found in parent %d kids list", id, n.parent.id) - } - } - return nil -} - -func fmtTree(ws *priorityWriteScheduler, fmtNode func(*priorityNode) string) string { - var ids []int - for _, n := range ws.nodes { - ids = append(ids, int(n.id)) - } - sort.Ints(ids) - - var buf bytes.Buffer - for _, id := range ids { - if buf.Len() != 0 { - buf.WriteString(" ") - } - if id == 0 { - buf.WriteString(fmtNode(&ws.root)) - } else { - buf.WriteString(fmtNode(ws.nodes[uint32(id)])) - } - } - return buf.String() -} - -func fmtNodeParentSkipRoot(n *priorityNode) string { - switch { - case n.id == 0: - return "" - case n.parent == nil: - return fmt.Sprintf("%d{parent:nil}", n.id) - default: - return fmt.Sprintf("%d{parent:%d}", n.id, n.parent.id) - } -} - -func fmtNodeWeightParentSkipRoot(n *priorityNode) string { - switch { - case n.id == 0: - return "" - case n.parent == nil: - return fmt.Sprintf("%d{weight:%d,parent:nil}", n.id, n.weight) - default: - return fmt.Sprintf("%d{weight:%d,parent:%d}", n.id, n.weight, n.parent.id) - } -} - -func TestPriorityTwoStreams(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - - want := "1{weight:15,parent:0} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - - // Move 1's parent to 2. - ws.AdjustStream(1, PriorityParam{ - StreamDep: 2, - Weight: 32, - Exclusive: false, - }) - want = "1{weight:32,parent:2} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityAdjustExclusiveZero(t *testing.T) { - // 1, 2, and 3 are all children of the 0 stream. - // Exclusive reprioritization to any of the streams should bring - // the rest of the streams under the reprioritized stream. - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - ws.OpenStream(3, OpenStreamOptions{}) - - want := "1{weight:15,parent:0} 2{weight:15,parent:0} 3{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - - ws.AdjustStream(2, PriorityParam{ - StreamDep: 0, - Weight: 20, - Exclusive: true, - }) - want = "1{weight:15,parent:2} 2{weight:20,parent:0} 3{weight:15,parent:2}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityAdjustOwnParent(t *testing.T) { - // Assigning a node as its own parent should have no effect. - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - ws.AdjustStream(2, PriorityParam{ - StreamDep: 2, - Weight: 20, - Exclusive: true, - }) - want := "1{weight:15,parent:0} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityClosedStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxClosedNodesInTree: 2}).(*priorityWriteScheduler) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - - // Close the first three streams. We lose 1, but keep 2 and 3. - ws.CloseStream(1) - ws.CloseStream(2) - ws.CloseStream(3) - - want := "2{weight:15,parent:0} 3{weight:15,parent:2} 4{weight:15,parent:3}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After close\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } - - // Adding a stream as an exclusive child of 1 gives it default - // priorities, since 1 is gone. - ws.OpenStream(5, OpenStreamOptions{}) - ws.AdjustStream(5, PriorityParam{StreamDep: 1, Weight: 15, Exclusive: true}) - - // Adding a stream as an exclusive child of 2 should work, since 2 is not gone. - ws.OpenStream(6, OpenStreamOptions{}) - ws.AdjustStream(6, PriorityParam{StreamDep: 2, Weight: 15, Exclusive: true}) - - want = "2{weight:15,parent:0} 3{weight:15,parent:6} 4{weight:15,parent:3} 5{weight:15,parent:0} 6{weight:15,parent:2}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After add streams\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityClosedStreamsDisabled(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - - // Close the first two streams. We keep only 3. - ws.CloseStream(1) - ws.CloseStream(2) - - want := "3{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After close\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityIdleStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxIdleNodesInTree: 2}).(*priorityWriteScheduler) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle - ws.OpenStream(4, OpenStreamOptions{}) - ws.OpenStream(5, OpenStreamOptions{}) - ws.OpenStream(6, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{StreamDep: 1, Weight: 15}) - ws.AdjustStream(5, PriorityParam{StreamDep: 2, Weight: 15}) - ws.AdjustStream(6, PriorityParam{StreamDep: 3, Weight: 15}) - - want := "2{weight:15,parent:0} 3{weight:20,parent:2} 4{weight:15,parent:0} 5{weight:15,parent:2} 6{weight:15,parent:3}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityIdleStreamsDisabled(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle - ws.OpenStream(4, OpenStreamOptions{}) - - want := "4{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection531NonExclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.1. - // A,B,C,D = 1,2,3,4 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{ - StreamDep: 1, - Weight: 15, - Exclusive: false, - }) - want := "1{parent:0} 2{parent:1} 3{parent:1} 4{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection531Exclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.1. - // A,B,C,D = 1,2,3,4 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{ - StreamDep: 1, - Weight: 15, - Exclusive: true, - }) - want := "1{parent:0} 2{parent:4} 3{parent:4} 4{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func makeSection533Tree() *priorityWriteScheduler { - // Initial tree from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - return ws -} - -func TestPrioritySection533NonExclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - ws.AdjustStream(1, PriorityParam{ - StreamDep: 4, - Weight: 15, - Exclusive: false, - }) - want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:4}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection533Exclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - ws.AdjustStream(1, PriorityParam{ - StreamDep: 4, - Weight: 15, - Exclusive: true, - }) - want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func checkPopAll(ws WriteScheduler, order []uint32) error { - for k, id := range order { - wr, ok := ws.Pop() - if !ok { - return fmt.Errorf("Pop[%d]: got ok=false, want %d (order=%v)", k, id, order) - } - if got := wr.StreamID(); got != id { - return fmt.Errorf("Pop[%d]: got %v, want %d (order=%v)", k, got, id, order) - } - } - wr, ok := ws.Pop() - if ok { - return fmt.Errorf("Pop[%d]: got %v, want ok=false (order=%v)", len(order), wr.StreamID(), order) - } - return nil -} - -func TestPriorityPopFrom533Tree(t *testing.T) { - ws := makeSection533Tree() - - ws.Push(makeWriteHeadersRequest(3 /*C*/)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteHeadersRequest(5 /*E*/)) - ws.Push(makeWriteHeadersRequest(1 /*A*/)) - t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) - - if err := checkPopAll(ws, []uint32{0 /*NonStream*/, 1, 3, 5}); err != nil { - t.Error(err) - } -} - -func TestPriorityPopFromLinearTree(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - - ws.Push(makeWriteHeadersRequest(3)) - ws.Push(makeWriteHeadersRequest(4)) - ws.Push(makeWriteHeadersRequest(1)) - ws.Push(makeWriteHeadersRequest(2)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteNonStreamRequest()) - t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) - - if err := checkPopAll(ws, []uint32{0, 0 /*NonStreams*/, 1, 2, 3, 4}); err != nil { - t.Error(err) - } -} - -func TestPriorityFlowControl(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: false}) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - - sc := &serverConn{maxFrameSize: 16} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 16), false}, st1, nil}) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 16), false}, st2, nil}) - ws.AdjustStream(2, PriorityParam{StreamDep: 1}) - - // No flow-control bytes available. - if wr, ok := ws.Pop(); ok { - t.Fatalf("Pop(limited by flow control)=%v,true, want false", wr) - } - - // Add enough flow-control bytes to write st2 in two Pop calls. - // Should write data from st2 even though it's lower priority than st1. - for i := 1; i <= 2; i++ { - st2.flow.add(8) - wr, ok := ws.Pop() - if !ok { - t.Fatalf("Pop(%d)=false, want true", i) - } - if got, want := wr.DataSize(), 8; got != want { - t.Fatalf("Pop(%d)=%d bytes, want %d bytes", i, got, want) - } - } -} - -func TestPriorityThrottleOutOfOrderWrites(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: true}) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - - sc := &serverConn{maxFrameSize: 4096} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - st1.flow.add(4096) - st2.flow.add(4096) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 4096), false}, st2, nil}) - ws.AdjustStream(2, PriorityParam{StreamDep: 1}) - - // We have enough flow-control bytes to write st2 in a single Pop call. - // However, due to out-of-order write throttling, the first call should - // only write 1KB. - wr, ok := ws.Pop() - if !ok { - t.Fatalf("Pop(st2.first)=false, want true") - } - if got, want := wr.StreamID(), uint32(2); got != want { - t.Fatalf("Pop(st2.first)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 1024; got != want { - t.Fatalf("Pop(st2.first)=%d bytes, want %d bytes", got, want) - } - - // Now add data on st1. This should take precedence. - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 4096), false}, st1, nil}) - wr, ok = ws.Pop() - if !ok { - t.Fatalf("Pop(st1)=false, want true") - } - if got, want := wr.StreamID(), uint32(1); got != want { - t.Fatalf("Pop(st1)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 4096; got != want { - t.Fatalf("Pop(st1)=%d bytes, want %d bytes", got, want) - } - - // Should go back to writing 1KB from st2. - wr, ok = ws.Pop() - if !ok { - t.Fatalf("Pop(st2.last)=false, want true") - } - if got, want := wr.StreamID(), uint32(2); got != want { - t.Fatalf("Pop(st2.last)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 1024; got != want { - t.Fatalf("Pop(st2.last)=%d bytes, want %d bytes", got, want) - } -} - -func TestPriorityWeights(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - - sc := &serverConn{maxFrameSize: 8} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - st1.flow.add(40) - st2.flow.add(40) - - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 40), false}, st1, nil}) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 40), false}, st2, nil}) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 34}) - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 9}) - - // st1 gets 3.5x the bandwidth of st2 (3.5 = (34+1)/(9+1)). - // The maximum frame size is 8 bytes. The write sequence should be: - // st1, total bytes so far is (st1=8, st=0) - // st2, total bytes so far is (st1=8, st=8) - // st1, total bytes so far is (st1=16, st=8) - // st1, total bytes so far is (st1=24, st=8) // 3x bandwidth - // st1, total bytes so far is (st1=32, st=8) // 4x bandwidth - // st2, total bytes so far is (st1=32, st=16) // 2x bandwidth - // st1, total bytes so far is (st1=40, st=16) - // st2, total bytes so far is (st1=40, st=24) - // st2, total bytes so far is (st1=40, st=32) - // st2, total bytes so far is (st1=40, st=40) - if err := checkPopAll(ws, []uint32{1, 2, 1, 1, 1, 2, 1, 2, 2, 2}); err != nil { - t.Error(err) - } -} - -func TestPriorityRstStreamOnNonOpenStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ - MaxClosedNodesInTree: 0, - MaxIdleNodesInTree: 0, - }) - ws.OpenStream(1, OpenStreamOptions{}) - ws.CloseStream(1) - ws.Push(FrameWriteRequest{write: streamError(1, ErrCodeProtocol)}) - ws.Push(FrameWriteRequest{write: streamError(2, ErrCodeProtocol)}) - - if err := checkPopAll(ws, []uint32{1, 2}); err != nil { - t.Error(err) - } -} diff --git a/examples/golang.org/x/net/http2/writesched_random.go b/examples/golang.org/x/net/http2/writesched_random.go deleted file mode 100644 index 36d7919..0000000 --- a/examples/golang.org/x/net/http2/writesched_random.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "math" - -// NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2 -// priorities. Control frames like SETTINGS and PING are written before DATA -// frames, but if no control frames are queued and multiple streams have queued -// HEADERS or DATA frames, Pop selects a ready stream arbitrarily. -func NewRandomWriteScheduler() WriteScheduler { - return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} -} - -type randomWriteScheduler struct { - // zero are frames not associated with a specific stream. - zero writeQueue - - // sq contains the stream-specific queues, keyed by stream ID. - // When a stream is idle or closed, it's deleted from the map. - sq map[uint32]*writeQueue - - // pool of empty queues for reuse. - queuePool writeQueuePool -} - -func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { - // no-op: idle streams are not tracked -} - -func (ws *randomWriteScheduler) CloseStream(streamID uint32) { - q, ok := ws.sq[streamID] - if !ok { - return - } - delete(ws.sq, streamID) - ws.queuePool.put(q) -} - -func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { - // no-op: priorities are ignored -} - -func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) { - id := wr.StreamID() - if id == 0 { - ws.zero.push(wr) - return - } - q, ok := ws.sq[id] - if !ok { - q = ws.queuePool.get() - ws.sq[id] = q - } - q.push(wr) -} - -func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) { - // Control frames first. - if !ws.zero.empty() { - return ws.zero.shift(), true - } - // Iterate over all non-idle streams until finding one that can be consumed. - for _, q := range ws.sq { - if wr, ok := q.consume(math.MaxInt32); ok { - return wr, true - } - } - return FrameWriteRequest{}, false -} diff --git a/examples/golang.org/x/net/http2/writesched_random_test.go b/examples/golang.org/x/net/http2/writesched_random_test.go deleted file mode 100644 index 3bf4aa3..0000000 --- a/examples/golang.org/x/net/http2/writesched_random_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import "testing" - -func TestRandomScheduler(t *testing.T) { - ws := NewRandomWriteScheduler() - ws.Push(makeWriteHeadersRequest(3)) - ws.Push(makeWriteHeadersRequest(4)) - ws.Push(makeWriteHeadersRequest(1)) - ws.Push(makeWriteHeadersRequest(2)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteNonStreamRequest()) - - // Pop all frames. Should get the non-stream requests first, - // followed by the stream requests in any order. - var order []FrameWriteRequest - for { - wr, ok := ws.Pop() - if !ok { - break - } - order = append(order, wr) - } - t.Logf("got frames: %v", order) - if len(order) != 6 { - t.Fatalf("got %d frames, expected 6", len(order)) - } - if order[0].StreamID() != 0 || order[1].StreamID() != 0 { - t.Fatal("expected non-stream frames first", order[0], order[1]) - } - got := make(map[uint32]bool) - for _, wr := range order[2:] { - got[wr.StreamID()] = true - } - for id := uint32(1); id <= 4; id++ { - if !got[id] { - t.Errorf("frame not found for stream %d", id) - } - } -} diff --git a/examples/golang.org/x/net/http2/writesched_test.go b/examples/golang.org/x/net/http2/writesched_test.go deleted file mode 100644 index 0807056..0000000 --- a/examples/golang.org/x/net/http2/writesched_test.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "fmt" - "math" - "reflect" - "testing" -) - -func makeWriteNonStreamRequest() FrameWriteRequest { - return FrameWriteRequest{writeSettingsAck{}, nil, nil} -} - -func makeWriteHeadersRequest(streamID uint32) FrameWriteRequest { - st := &stream{id: streamID} - return FrameWriteRequest{&writeResHeaders{streamID: streamID, httpResCode: 200}, st, nil} -} - -func checkConsume(wr FrameWriteRequest, nbytes int32, want []FrameWriteRequest) error { - consumed, rest, n := wr.Consume(nbytes) - var wantConsumed, wantRest FrameWriteRequest - switch len(want) { - case 0: - case 1: - wantConsumed = want[0] - case 2: - wantConsumed = want[0] - wantRest = want[1] - } - if !reflect.DeepEqual(consumed, wantConsumed) || !reflect.DeepEqual(rest, wantRest) || n != len(want) { - return fmt.Errorf("got %v, %v, %v\nwant %v, %v, %v", consumed, rest, n, wantConsumed, wantRest, len(want)) - } - return nil -} - -func TestFrameWriteRequestNonData(t *testing.T) { - wr := makeWriteNonStreamRequest() - if got, want := wr.DataSize(), 0; got != want { - t.Errorf("DataSize: got %v, want %v", got, want) - } - - // Non-DATA frames are always consumed whole. - if err := checkConsume(wr, 0, []FrameWriteRequest{wr}); err != nil { - t.Errorf("Consume:\n%v", err) - } -} - -func TestFrameWriteRequestData(t *testing.T) { - st := &stream{ - id: 1, - sc: &serverConn{maxFrameSize: 16}, - } - const size = 32 - wr := FrameWriteRequest{&writeData{st.id, make([]byte, size), true}, st, make(chan error)} - if got, want := wr.DataSize(), size; got != want { - t.Errorf("DataSize: got %v, want %v", got, want) - } - - // No flow-control bytes available: cannot consume anything. - if err := checkConsume(wr, math.MaxInt32, []FrameWriteRequest{}); err != nil { - t.Errorf("Consume(limited by flow control):\n%v", err) - } - - // Add enough flow-control bytes to consume the entire frame, - // but we're now restricted by st.sc.maxFrameSize. - st.flow.add(size) - want := []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, st.sc.maxFrameSize), false}, - stream: st, - done: nil, - }, - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(wr, math.MaxInt32, want); err != nil { - t.Errorf("Consume(limited by maxFrameSize):\n%v", err) - } - rest := want[1] - - // Consume 8 bytes from the remaining frame. - want = []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, 8), false}, - stream: st, - done: nil, - }, - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(rest, 8, want); err != nil { - t.Errorf("Consume(8):\n%v", err) - } - rest = want[1] - - // Consume all remaining bytes. - want = []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(rest, math.MaxInt32, want); err != nil { - t.Errorf("Consume(remainder):\n%v", err) - } -} - -func TestFrameWriteRequest_StreamID(t *testing.T) { - const streamID = 123 - wr := FrameWriteRequest{write: streamError(streamID, ErrCodeNo)} - if got := wr.StreamID(); got != streamID { - t.Errorf("FrameWriteRequest(StreamError) = %v; want %v", got, streamID) - } -} diff --git a/examples/golang.org/x/net/http2/z_spec_test.go b/examples/golang.org/x/net/http2/z_spec_test.go deleted file mode 100644 index 610b2cd..0000000 --- a/examples/golang.org/x/net/http2/z_spec_test.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package http2 - -import ( - "bytes" - "encoding/xml" - "flag" - "fmt" - "io" - "os" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "testing" -) - -var coverSpec = flag.Bool("coverspec", false, "Run spec coverage tests") - -// The global map of sentence coverage for the http2 spec. -var defaultSpecCoverage specCoverage - -var loadSpecOnce sync.Once - -func loadSpec() { - if f, err := os.Open("testdata/draft-ietf-httpbis-http2.xml"); err != nil { - panic(err) - } else { - defaultSpecCoverage = readSpecCov(f) - f.Close() - } -} - -// covers marks all sentences for section sec in defaultSpecCoverage. Sentences not -// "covered" will be included in report outputted by TestSpecCoverage. -func covers(sec, sentences string) { - loadSpecOnce.Do(loadSpec) - defaultSpecCoverage.cover(sec, sentences) -} - -type specPart struct { - section string - sentence string -} - -func (ss specPart) Less(oo specPart) bool { - atoi := func(s string) int { - n, err := strconv.Atoi(s) - if err != nil { - panic(err) - } - return n - } - a := strings.Split(ss.section, ".") - b := strings.Split(oo.section, ".") - for len(a) > 0 { - if len(b) == 0 { - return false - } - x, y := atoi(a[0]), atoi(b[0]) - if x == y { - a, b = a[1:], b[1:] - continue - } - return x < y - } - if len(b) > 0 { - return true - } - return false -} - -type bySpecSection []specPart - -func (a bySpecSection) Len() int { return len(a) } -func (a bySpecSection) Less(i, j int) bool { return a[i].Less(a[j]) } -func (a bySpecSection) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type specCoverage struct { - coverage map[specPart]bool - d *xml.Decoder -} - -func joinSection(sec []int) string { - s := fmt.Sprintf("%d", sec[0]) - for _, n := range sec[1:] { - s = fmt.Sprintf("%s.%d", s, n) - } - return s -} - -func (sc specCoverage) readSection(sec []int) { - var ( - buf = new(bytes.Buffer) - sub = 0 - ) - for { - tk, err := sc.d.Token() - if err != nil { - if err == io.EOF { - return - } - panic(err) - } - switch v := tk.(type) { - case xml.StartElement: - if skipElement(v) { - if err := sc.d.Skip(); err != nil { - panic(err) - } - if v.Name.Local == "section" { - sub++ - } - break - } - switch v.Name.Local { - case "section": - sub++ - sc.readSection(append(sec, sub)) - case "xref": - buf.Write(sc.readXRef(v)) - } - case xml.CharData: - if len(sec) == 0 { - break - } - buf.Write(v) - case xml.EndElement: - if v.Name.Local == "section" { - sc.addSentences(joinSection(sec), buf.String()) - return - } - } - } -} - -func (sc specCoverage) readXRef(se xml.StartElement) []byte { - var b []byte - for { - tk, err := sc.d.Token() - if err != nil { - panic(err) - } - switch v := tk.(type) { - case xml.CharData: - if b != nil { - panic("unexpected CharData") - } - b = []byte(string(v)) - case xml.EndElement: - if v.Name.Local != "xref" { - panic("expected ") - } - if b != nil { - return b - } - sig := attrSig(se) - switch sig { - case "target": - return []byte(fmt.Sprintf("[%s]", attrValue(se, "target"))) - case "fmt-of,rel,target", "fmt-,,rel,target": - return []byte(fmt.Sprintf("[%s, %s]", attrValue(se, "target"), attrValue(se, "rel"))) - case "fmt-of,sec,target", "fmt-,,sec,target": - return []byte(fmt.Sprintf("[section %s of %s]", attrValue(se, "sec"), attrValue(se, "target"))) - case "fmt-of,rel,sec,target": - return []byte(fmt.Sprintf("[section %s of %s, %s]", attrValue(se, "sec"), attrValue(se, "target"), attrValue(se, "rel"))) - default: - panic(fmt.Sprintf("unknown attribute signature %q in %#v", sig, fmt.Sprintf("%#v", se))) - } - default: - panic(fmt.Sprintf("unexpected tag %q", v)) - } - } -} - -var skipAnchor = map[string]bool{ - "intro": true, - "Overview": true, -} - -var skipTitle = map[string]bool{ - "Acknowledgements": true, - "Change Log": true, - "Document Organization": true, - "Conventions and Terminology": true, -} - -func skipElement(s xml.StartElement) bool { - switch s.Name.Local { - case "artwork": - return true - case "section": - for _, attr := range s.Attr { - switch attr.Name.Local { - case "anchor": - if skipAnchor[attr.Value] || strings.HasPrefix(attr.Value, "changes.since.") { - return true - } - case "title": - if skipTitle[attr.Value] { - return true - } - } - } - } - return false -} - -func readSpecCov(r io.Reader) specCoverage { - sc := specCoverage{ - coverage: map[specPart]bool{}, - d: xml.NewDecoder(r)} - sc.readSection(nil) - return sc -} - -func (sc specCoverage) addSentences(sec string, sentence string) { - for _, s := range parseSentences(sentence) { - sc.coverage[specPart{sec, s}] = false - } -} - -func (sc specCoverage) cover(sec string, sentence string) { - for _, s := range parseSentences(sentence) { - p := specPart{sec, s} - if _, ok := sc.coverage[p]; !ok { - panic(fmt.Sprintf("Not found in spec: %q, %q", sec, s)) - } - sc.coverage[specPart{sec, s}] = true - } - -} - -var whitespaceRx = regexp.MustCompile(`\s+`) - -func parseSentences(sens string) []string { - sens = strings.TrimSpace(sens) - if sens == "" { - return nil - } - ss := strings.Split(whitespaceRx.ReplaceAllString(sens, " "), ". ") - for i, s := range ss { - s = strings.TrimSpace(s) - if !strings.HasSuffix(s, ".") { - s += "." - } - ss[i] = s - } - return ss -} - -func TestSpecParseSentences(t *testing.T) { - tests := []struct { - ss string - want []string - }{ - {"Sentence 1. Sentence 2.", - []string{ - "Sentence 1.", - "Sentence 2.", - }}, - {"Sentence 1. \nSentence 2.\tSentence 3.", - []string{ - "Sentence 1.", - "Sentence 2.", - "Sentence 3.", - }}, - } - - for i, tt := range tests { - got := parseSentences(tt.ss) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d: got = %q, want %q", i, got, tt.want) - } - } -} - -func TestSpecCoverage(t *testing.T) { - if !*coverSpec { - t.Skip() - } - - loadSpecOnce.Do(loadSpec) - - var ( - list []specPart - cv = defaultSpecCoverage.coverage - total = len(cv) - complete = 0 - ) - - for sp, touched := range defaultSpecCoverage.coverage { - if touched { - complete++ - } else { - list = append(list, sp) - } - } - sort.Stable(bySpecSection(list)) - - if testing.Short() && len(list) > 5 { - list = list[:5] - } - - for _, p := range list { - t.Errorf("\tSECTION %s: %s", p.section, p.sentence) - } - - t.Logf("%d/%d (%d%%) sentences covered", complete, total, (complete/total)*100) -} - -func attrSig(se xml.StartElement) string { - var names []string - for _, attr := range se.Attr { - if attr.Name.Local == "fmt" { - names = append(names, "fmt-"+attr.Value) - } else { - names = append(names, attr.Name.Local) - } - } - sort.Strings(names) - return strings.Join(names, ",") -} - -func attrValue(se xml.StartElement, attr string) string { - for _, a := range se.Attr { - if a.Name.Local == attr { - return a.Value - } - } - panic("unknown attribute " + attr) -} - -func TestSpecPartLess(t *testing.T) { - tests := []struct { - sec1, sec2 string - want bool - }{ - {"6.2.1", "6.2", false}, - {"6.2", "6.2.1", true}, - {"6.10", "6.10.1", true}, - {"6.10", "6.1.1", false}, // 10, not 1 - {"6.1", "6.1", false}, // equal, so not less - } - for _, tt := range tests { - got := (specPart{tt.sec1, "foo"}).Less(specPart{tt.sec2, "foo"}) - if got != tt.want { - t.Errorf("Less(%q, %q) = %v; want %v", tt.sec1, tt.sec2, got, tt.want) - } - } -} diff --git a/examples/golang.org/x/net/internal/iana/const.go b/examples/golang.org/x/net/internal/iana/const.go deleted file mode 100644 index cea712f..0000000 --- a/examples/golang.org/x/net/internal/iana/const.go +++ /dev/null @@ -1,223 +0,0 @@ -// go generate gen.go -// Code generated by the command above; DO NOT EDIT. - -// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA). -package iana // import "golang.org/x/net/internal/iana" - -// Differentiated Services Field Codepoints (DSCP), Updated: 2018-05-04 -const ( - DiffServCS0 = 0x00 // CS0 - DiffServCS1 = 0x20 // CS1 - DiffServCS2 = 0x40 // CS2 - DiffServCS3 = 0x60 // CS3 - DiffServCS4 = 0x80 // CS4 - DiffServCS5 = 0xa0 // CS5 - DiffServCS6 = 0xc0 // CS6 - DiffServCS7 = 0xe0 // CS7 - DiffServAF11 = 0x28 // AF11 - DiffServAF12 = 0x30 // AF12 - DiffServAF13 = 0x38 // AF13 - DiffServAF21 = 0x48 // AF21 - DiffServAF22 = 0x50 // AF22 - DiffServAF23 = 0x58 // AF23 - DiffServAF31 = 0x68 // AF31 - DiffServAF32 = 0x70 // AF32 - DiffServAF33 = 0x78 // AF33 - DiffServAF41 = 0x88 // AF41 - DiffServAF42 = 0x90 // AF42 - DiffServAF43 = 0x98 // AF43 - DiffServEF = 0xb8 // EF - DiffServVOICEADMIT = 0xb0 // VOICE-ADMIT - NotECNTransport = 0x00 // Not-ECT (Not ECN-Capable Transport) - ECNTransport1 = 0x01 // ECT(1) (ECN-Capable Transport(1)) - ECNTransport0 = 0x02 // ECT(0) (ECN-Capable Transport(0)) - CongestionExperienced = 0x03 // CE (Congestion Experienced) -) - -// Protocol Numbers, Updated: 2017-10-13 -const ( - ProtocolIP = 0 // IPv4 encapsulation, pseudo protocol number - ProtocolHOPOPT = 0 // IPv6 Hop-by-Hop Option - ProtocolICMP = 1 // Internet Control Message - ProtocolIGMP = 2 // Internet Group Management - ProtocolGGP = 3 // Gateway-to-Gateway - ProtocolIPv4 = 4 // IPv4 encapsulation - ProtocolST = 5 // Stream - ProtocolTCP = 6 // Transmission Control - ProtocolCBT = 7 // CBT - ProtocolEGP = 8 // Exterior Gateway Protocol - ProtocolIGP = 9 // any private interior gateway (used by Cisco for their IGRP) - ProtocolBBNRCCMON = 10 // BBN RCC Monitoring - ProtocolNVPII = 11 // Network Voice Protocol - ProtocolPUP = 12 // PUP - ProtocolEMCON = 14 // EMCON - ProtocolXNET = 15 // Cross Net Debugger - ProtocolCHAOS = 16 // Chaos - ProtocolUDP = 17 // User Datagram - ProtocolMUX = 18 // Multiplexing - ProtocolDCNMEAS = 19 // DCN Measurement Subsystems - ProtocolHMP = 20 // Host Monitoring - ProtocolPRM = 21 // Packet Radio Measurement - ProtocolXNSIDP = 22 // XEROX NS IDP - ProtocolTRUNK1 = 23 // Trunk-1 - ProtocolTRUNK2 = 24 // Trunk-2 - ProtocolLEAF1 = 25 // Leaf-1 - ProtocolLEAF2 = 26 // Leaf-2 - ProtocolRDP = 27 // Reliable Data Protocol - ProtocolIRTP = 28 // Internet Reliable Transaction - ProtocolISOTP4 = 29 // ISO Transport Protocol Class 4 - ProtocolNETBLT = 30 // Bulk Data Transfer Protocol - ProtocolMFENSP = 31 // MFE Network Services Protocol - ProtocolMERITINP = 32 // MERIT Internodal Protocol - ProtocolDCCP = 33 // Datagram Congestion Control Protocol - Protocol3PC = 34 // Third Party Connect Protocol - ProtocolIDPR = 35 // Inter-Domain Policy Routing Protocol - ProtocolXTP = 36 // XTP - ProtocolDDP = 37 // Datagram Delivery Protocol - ProtocolIDPRCMTP = 38 // IDPR Control Message Transport Proto - ProtocolTPPP = 39 // TP++ Transport Protocol - ProtocolIL = 40 // IL Transport Protocol - ProtocolIPv6 = 41 // IPv6 encapsulation - ProtocolSDRP = 42 // Source Demand Routing Protocol - ProtocolIPv6Route = 43 // Routing Header for IPv6 - ProtocolIPv6Frag = 44 // Fragment Header for IPv6 - ProtocolIDRP = 45 // Inter-Domain Routing Protocol - ProtocolRSVP = 46 // Reservation Protocol - ProtocolGRE = 47 // Generic Routing Encapsulation - ProtocolDSR = 48 // Dynamic Source Routing Protocol - ProtocolBNA = 49 // BNA - ProtocolESP = 50 // Encap Security Payload - ProtocolAH = 51 // Authentication Header - ProtocolINLSP = 52 // Integrated Net Layer Security TUBA - ProtocolNARP = 54 // NBMA Address Resolution Protocol - ProtocolMOBILE = 55 // IP Mobility - ProtocolTLSP = 56 // Transport Layer Security Protocol using Kryptonet key management - ProtocolSKIP = 57 // SKIP - ProtocolIPv6ICMP = 58 // ICMP for IPv6 - ProtocolIPv6NoNxt = 59 // No Next Header for IPv6 - ProtocolIPv6Opts = 60 // Destination Options for IPv6 - ProtocolCFTP = 62 // CFTP - ProtocolSATEXPAK = 64 // SATNET and Backroom EXPAK - ProtocolKRYPTOLAN = 65 // Kryptolan - ProtocolRVD = 66 // MIT Remote Virtual Disk Protocol - ProtocolIPPC = 67 // Internet Pluribus Packet Core - ProtocolSATMON = 69 // SATNET Monitoring - ProtocolVISA = 70 // VISA Protocol - ProtocolIPCV = 71 // Internet Packet Core Utility - ProtocolCPNX = 72 // Computer Protocol Network Executive - ProtocolCPHB = 73 // Computer Protocol Heart Beat - ProtocolWSN = 74 // Wang Span Network - ProtocolPVP = 75 // Packet Video Protocol - ProtocolBRSATMON = 76 // Backroom SATNET Monitoring - ProtocolSUNND = 77 // SUN ND PROTOCOL-Temporary - ProtocolWBMON = 78 // WIDEBAND Monitoring - ProtocolWBEXPAK = 79 // WIDEBAND EXPAK - ProtocolISOIP = 80 // ISO Internet Protocol - ProtocolVMTP = 81 // VMTP - ProtocolSECUREVMTP = 82 // SECURE-VMTP - ProtocolVINES = 83 // VINES - ProtocolTTP = 84 // Transaction Transport Protocol - ProtocolIPTM = 84 // Internet Protocol Traffic Manager - ProtocolNSFNETIGP = 85 // NSFNET-IGP - ProtocolDGP = 86 // Dissimilar Gateway Protocol - ProtocolTCF = 87 // TCF - ProtocolEIGRP = 88 // EIGRP - ProtocolOSPFIGP = 89 // OSPFIGP - ProtocolSpriteRPC = 90 // Sprite RPC Protocol - ProtocolLARP = 91 // Locus Address Resolution Protocol - ProtocolMTP = 92 // Multicast Transport Protocol - ProtocolAX25 = 93 // AX.25 Frames - ProtocolIPIP = 94 // IP-within-IP Encapsulation Protocol - ProtocolSCCSP = 96 // Semaphore Communications Sec. Pro. - ProtocolETHERIP = 97 // Ethernet-within-IP Encapsulation - ProtocolENCAP = 98 // Encapsulation Header - ProtocolGMTP = 100 // GMTP - ProtocolIFMP = 101 // Ipsilon Flow Management Protocol - ProtocolPNNI = 102 // PNNI over IP - ProtocolPIM = 103 // Protocol Independent Multicast - ProtocolARIS = 104 // ARIS - ProtocolSCPS = 105 // SCPS - ProtocolQNX = 106 // QNX - ProtocolAN = 107 // Active Networks - ProtocolIPComp = 108 // IP Payload Compression Protocol - ProtocolSNP = 109 // Sitara Networks Protocol - ProtocolCompaqPeer = 110 // Compaq Peer Protocol - ProtocolIPXinIP = 111 // IPX in IP - ProtocolVRRP = 112 // Virtual Router Redundancy Protocol - ProtocolPGM = 113 // PGM Reliable Transport Protocol - ProtocolL2TP = 115 // Layer Two Tunneling Protocol - ProtocolDDX = 116 // D-II Data Exchange (DDX) - ProtocolIATP = 117 // Interactive Agent Transfer Protocol - ProtocolSTP = 118 // Schedule Transfer Protocol - ProtocolSRP = 119 // SpectraLink Radio Protocol - ProtocolUTI = 120 // UTI - ProtocolSMP = 121 // Simple Message Protocol - ProtocolPTP = 123 // Performance Transparency Protocol - ProtocolISIS = 124 // ISIS over IPv4 - ProtocolFIRE = 125 // FIRE - ProtocolCRTP = 126 // Combat Radio Transport Protocol - ProtocolCRUDP = 127 // Combat Radio User Datagram - ProtocolSSCOPMCE = 128 // SSCOPMCE - ProtocolIPLT = 129 // IPLT - ProtocolSPS = 130 // Secure Packet Shield - ProtocolPIPE = 131 // Private IP Encapsulation within IP - ProtocolSCTP = 132 // Stream Control Transmission Protocol - ProtocolFC = 133 // Fibre Channel - ProtocolRSVPE2EIGNORE = 134 // RSVP-E2E-IGNORE - ProtocolMobilityHeader = 135 // Mobility Header - ProtocolUDPLite = 136 // UDPLite - ProtocolMPLSinIP = 137 // MPLS-in-IP - ProtocolMANET = 138 // MANET Protocols - ProtocolHIP = 139 // Host Identity Protocol - ProtocolShim6 = 140 // Shim6 Protocol - ProtocolWESP = 141 // Wrapped Encapsulating Security Payload - ProtocolROHC = 142 // Robust Header Compression - ProtocolReserved = 255 // Reserved -) - -// Address Family Numbers, Updated: 2018-04-02 -const ( - AddrFamilyIPv4 = 1 // IP (IP version 4) - AddrFamilyIPv6 = 2 // IP6 (IP version 6) - AddrFamilyNSAP = 3 // NSAP - AddrFamilyHDLC = 4 // HDLC (8-bit multidrop) - AddrFamilyBBN1822 = 5 // BBN 1822 - AddrFamily802 = 6 // 802 (includes all 802 media plus Ethernet "canonical format") - AddrFamilyE163 = 7 // E.163 - AddrFamilyE164 = 8 // E.164 (SMDS, Frame Relay, ATM) - AddrFamilyF69 = 9 // F.69 (Telex) - AddrFamilyX121 = 10 // X.121 (X.25, Frame Relay) - AddrFamilyIPX = 11 // IPX - AddrFamilyAppletalk = 12 // Appletalk - AddrFamilyDecnetIV = 13 // Decnet IV - AddrFamilyBanyanVines = 14 // Banyan Vines - AddrFamilyE164withSubaddress = 15 // E.164 with NSAP format subaddress - AddrFamilyDNS = 16 // DNS (Domain Name System) - AddrFamilyDistinguishedName = 17 // Distinguished Name - AddrFamilyASNumber = 18 // AS Number - AddrFamilyXTPoverIPv4 = 19 // XTP over IP version 4 - AddrFamilyXTPoverIPv6 = 20 // XTP over IP version 6 - AddrFamilyXTPnativemodeXTP = 21 // XTP native mode XTP - AddrFamilyFibreChannelWorldWidePortName = 22 // Fibre Channel World-Wide Port Name - AddrFamilyFibreChannelWorldWideNodeName = 23 // Fibre Channel World-Wide Node Name - AddrFamilyGWID = 24 // GWID - AddrFamilyL2VPN = 25 // AFI for L2VPN information - AddrFamilyMPLSTPSectionEndpointID = 26 // MPLS-TP Section Endpoint Identifier - AddrFamilyMPLSTPLSPEndpointID = 27 // MPLS-TP LSP Endpoint Identifier - AddrFamilyMPLSTPPseudowireEndpointID = 28 // MPLS-TP Pseudowire Endpoint Identifier - AddrFamilyMTIPv4 = 29 // MT IP: Multi-Topology IP version 4 - AddrFamilyMTIPv6 = 30 // MT IPv6: Multi-Topology IP version 6 - AddrFamilyEIGRPCommonServiceFamily = 16384 // EIGRP Common Service Family - AddrFamilyEIGRPIPv4ServiceFamily = 16385 // EIGRP IPv4 Service Family - AddrFamilyEIGRPIPv6ServiceFamily = 16386 // EIGRP IPv6 Service Family - AddrFamilyLISPCanonicalAddressFormat = 16387 // LISP Canonical Address Format (LCAF) - AddrFamilyBGPLS = 16388 // BGP-LS - AddrFamily48bitMAC = 16389 // 48-bit MAC - AddrFamily64bitMAC = 16390 // 64-bit MAC - AddrFamilyOUI = 16391 // OUI - AddrFamilyMACFinal24bits = 16392 // MAC/24 - AddrFamilyMACFinal40bits = 16393 // MAC/40 - AddrFamilyIPv6Initial64bits = 16394 // IPv6/64 - AddrFamilyRBridgePortID = 16395 // RBridge Port ID - AddrFamilyTRILLNickname = 16396 // TRILL Nickname -) diff --git a/examples/golang.org/x/net/internal/iana/gen.go b/examples/golang.org/x/net/internal/iana/gen.go deleted file mode 100644 index 2a7661c..0000000 --- a/examples/golang.org/x/net/internal/iana/gen.go +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -//go:generate go run gen.go - -// This program generates internet protocol constants and tables by -// reading IANA protocol registries. -package main - -import ( - "bytes" - "encoding/xml" - "fmt" - "go/format" - "io" - "io/ioutil" - "net/http" - "os" - "strconv" - "strings" -) - -var registries = []struct { - url string - parse func(io.Writer, io.Reader) error -}{ - { - "https://www.iana.org/assignments/dscp-registry/dscp-registry.xml", - parseDSCPRegistry, - }, - { - "https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", - parseProtocolNumbers, - }, - { - "https://www.iana.org/assignments/address-family-numbers/address-family-numbers.xml", - parseAddrFamilyNumbers, - }, -} - -func main() { - var bb bytes.Buffer - fmt.Fprintf(&bb, "// go generate gen.go\n") - fmt.Fprintf(&bb, "// Code generated by the command above; DO NOT EDIT.\n\n") - fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") - fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n") - for _, r := range registries { - resp, err := http.Get(r.url) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) - os.Exit(1) - } - if err := r.parse(&bb, resp.Body); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - fmt.Fprintf(&bb, "\n") - } - b, err := format.Source(bb.Bytes()) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - if err := ioutil.WriteFile("const.go", b, 0644); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func parseDSCPRegistry(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var dr dscpRegistry - if err := dec.Decode(&dr); err != nil { - return err - } - fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) - fmt.Fprintf(w, "const (\n") - for _, dr := range dr.escapeDSCP() { - fmt.Fprintf(w, "DiffServ%s = %#02x", dr.Name, dr.Value) - fmt.Fprintf(w, "// %s\n", dr.OrigName) - } - for _, er := range dr.escapeECN() { - fmt.Fprintf(w, "%s = %#02x", er.Descr, er.Value) - fmt.Fprintf(w, "// %s\n", er.OrigDescr) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type dscpRegistry struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - Note string `xml:"note"` - Registries []struct { - Title string `xml:"title"` - Registries []struct { - Title string `xml:"title"` - Records []struct { - Name string `xml:"name"` - Space string `xml:"space"` - } `xml:"record"` - } `xml:"registry"` - Records []struct { - Value string `xml:"value"` - Descr string `xml:"description"` - } `xml:"record"` - } `xml:"registry"` -} - -type canonDSCPRecord struct { - OrigName string - Name string - Value int -} - -func (drr *dscpRegistry) escapeDSCP() []canonDSCPRecord { - var drs []canonDSCPRecord - for _, preg := range drr.Registries { - if !strings.Contains(preg.Title, "Differentiated Services Field Codepoints") { - continue - } - for _, reg := range preg.Registries { - if !strings.Contains(reg.Title, "Pool 1 Codepoints") { - continue - } - drs = make([]canonDSCPRecord, len(reg.Records)) - sr := strings.NewReplacer( - "+", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, dr := range reg.Records { - s := strings.TrimSpace(dr.Name) - drs[i].OrigName = s - drs[i].Name = sr.Replace(s) - n, err := strconv.ParseUint(dr.Space, 2, 8) - if err != nil { - continue - } - drs[i].Value = int(n) << 2 - } - } - } - return drs -} - -type canonECNRecord struct { - OrigDescr string - Descr string - Value int -} - -func (drr *dscpRegistry) escapeECN() []canonECNRecord { - var ers []canonECNRecord - for _, reg := range drr.Registries { - if !strings.Contains(reg.Title, "ECN Field") { - continue - } - ers = make([]canonECNRecord, len(reg.Records)) - sr := strings.NewReplacer( - "Capable", "", - "Not-ECT", "", - "ECT(1)", "", - "ECT(0)", "", - "CE", "", - "(", "", - ")", "", - "+", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, er := range reg.Records { - s := strings.TrimSpace(er.Descr) - ers[i].OrigDescr = s - ss := strings.Split(s, " ") - if len(ss) > 1 { - ers[i].Descr = strings.Join(ss[1:], " ") - } else { - ers[i].Descr = ss[0] - } - ers[i].Descr = sr.Replace(er.Descr) - n, err := strconv.ParseUint(er.Value, 2, 8) - if err != nil { - continue - } - ers[i].Value = int(n) - } - } - return ers -} - -func parseProtocolNumbers(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var pn protocolNumbers - if err := dec.Decode(&pn); err != nil { - return err - } - prs := pn.escape() - prs = append([]canonProtocolRecord{{ - Name: "IP", - Descr: "IPv4 encapsulation, pseudo protocol number", - Value: 0, - }}, prs...) - fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) - fmt.Fprintf(w, "const (\n") - for _, pr := range prs { - if pr.Name == "" { - continue - } - fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) - s := pr.Descr - if s == "" { - s = pr.OrigName - } - fmt.Fprintf(w, "// %s\n", s) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type protocolNumbers struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - RegTitle string `xml:"registry>title"` - Note string `xml:"registry>note"` - Records []struct { - Value string `xml:"value"` - Name string `xml:"name"` - Descr string `xml:"description"` - } `xml:"registry>record"` -} - -type canonProtocolRecord struct { - OrigName string - Name string - Descr string - Value int -} - -func (pn *protocolNumbers) escape() []canonProtocolRecord { - prs := make([]canonProtocolRecord, len(pn.Records)) - sr := strings.NewReplacer( - "-in-", "in", - "-within-", "within", - "-over-", "over", - "+", "P", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, pr := range pn.Records { - if strings.Contains(pr.Name, "Deprecated") || - strings.Contains(pr.Name, "deprecated") { - continue - } - prs[i].OrigName = pr.Name - s := strings.TrimSpace(pr.Name) - switch pr.Name { - case "ISIS over IPv4": - prs[i].Name = "ISIS" - case "manet": - prs[i].Name = "MANET" - default: - prs[i].Name = sr.Replace(s) - } - ss := strings.Split(pr.Descr, "\n") - for i := range ss { - ss[i] = strings.TrimSpace(ss[i]) - } - if len(ss) > 1 { - prs[i].Descr = strings.Join(ss, " ") - } else { - prs[i].Descr = ss[0] - } - prs[i].Value, _ = strconv.Atoi(pr.Value) - } - return prs -} - -func parseAddrFamilyNumbers(w io.Writer, r io.Reader) error { - dec := xml.NewDecoder(r) - var afn addrFamilylNumbers - if err := dec.Decode(&afn); err != nil { - return err - } - afrs := afn.escape() - fmt.Fprintf(w, "// %s, Updated: %s\n", afn.Title, afn.Updated) - fmt.Fprintf(w, "const (\n") - for _, afr := range afrs { - if afr.Name == "" { - continue - } - fmt.Fprintf(w, "AddrFamily%s = %d", afr.Name, afr.Value) - fmt.Fprintf(w, "// %s\n", afr.Descr) - } - fmt.Fprintf(w, ")\n") - return nil -} - -type addrFamilylNumbers struct { - XMLName xml.Name `xml:"registry"` - Title string `xml:"title"` - Updated string `xml:"updated"` - RegTitle string `xml:"registry>title"` - Note string `xml:"registry>note"` - Records []struct { - Value string `xml:"value"` - Descr string `xml:"description"` - } `xml:"registry>record"` -} - -type canonAddrFamilyRecord struct { - Name string - Descr string - Value int -} - -func (afn *addrFamilylNumbers) escape() []canonAddrFamilyRecord { - afrs := make([]canonAddrFamilyRecord, len(afn.Records)) - sr := strings.NewReplacer( - "IP version 4", "IPv4", - "IP version 6", "IPv6", - "Identifier", "ID", - "-", "", - "-", "", - "/", "", - ".", "", - " ", "", - ) - for i, afr := range afn.Records { - if strings.Contains(afr.Descr, "Unassigned") || - strings.Contains(afr.Descr, "Reserved") { - continue - } - afrs[i].Descr = afr.Descr - s := strings.TrimSpace(afr.Descr) - switch s { - case "IP (IP version 4)": - afrs[i].Name = "IPv4" - case "IP6 (IP version 6)": - afrs[i].Name = "IPv6" - case "AFI for L2VPN information": - afrs[i].Name = "L2VPN" - case "E.164 with NSAP format subaddress": - afrs[i].Name = "E164withSubaddress" - case "MT IP: Multi-Topology IP version 4": - afrs[i].Name = "MTIPv4" - case "MAC/24": - afrs[i].Name = "MACFinal24bits" - case "MAC/40": - afrs[i].Name = "MACFinal40bits" - case "IPv6/64": - afrs[i].Name = "IPv6Initial64bits" - default: - n := strings.Index(s, "(") - if n > 0 { - s = s[:n] - } - n = strings.Index(s, ":") - if n > 0 { - s = s[:n] - } - afrs[i].Name = sr.Replace(s) - } - afrs[i].Value, _ = strconv.Atoi(afr.Value) - } - return afrs -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_bsd.go b/examples/golang.org/x/net/internal/nettest/helper_bsd.go deleted file mode 100644 index a6e433b..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_bsd.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd netbsd openbsd - -package nettest - -import ( - "runtime" - "strconv" - "strings" - "syscall" -) - -var darwinVersion int - -func init() { - if runtime.GOOS == "darwin" { - // See http://support.apple.com/kb/HT1633. - s, err := syscall.Sysctl("kern.osrelease") - if err != nil { - return - } - ss := strings.Split(s, ".") - if len(ss) == 0 { - return - } - darwinVersion, _ = strconv.Atoi(ss[0]) - } -} - -func supportsIPv6MulticastDeliveryOnLoopback() bool { - switch runtime.GOOS { - case "freebsd": - // See http://www.freebsd.org/cgi/query-pr.cgi?pr=180065. - // Even after the fix, it looks like the latest - // kernels don't deliver link-local scoped multicast - // packets correctly. - return false - case "darwin": - return !causesIPv6Crash() - default: - return true - } -} - -func causesIPv6Crash() bool { - // We see some kernel crash when running IPv6 with IP-level - // options on Darwin kernel version 12 or below. - // See golang.org/issues/17015. - return darwinVersion < 13 -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_nobsd.go b/examples/golang.org/x/net/internal/nettest/helper_nobsd.go deleted file mode 100644 index bc7da5e..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_nobsd.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux solaris - -package nettest - -func supportsIPv6MulticastDeliveryOnLoopback() bool { - return true -} - -func causesIPv6Crash() bool { - return false -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_posix.go b/examples/golang.org/x/net/internal/nettest/helper_posix.go deleted file mode 100644 index 963ed99..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_posix.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package nettest - -import ( - "os" - "syscall" -) - -func protocolNotSupported(err error) bool { - switch err := err.(type) { - case syscall.Errno: - switch err { - case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: - return true - } - case *os.SyscallError: - switch err := err.Err.(type) { - case syscall.Errno: - switch err { - case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: - return true - } - } - } - return false -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_stub.go b/examples/golang.org/x/net/internal/nettest/helper_stub.go deleted file mode 100644 index d89cf29..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_stub.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build js nacl plan9 - -package nettest - -import ( - "fmt" - "runtime" -) - -func maxOpenFiles() int { - return defaultMaxOpenFiles -} - -func supportsRawIPSocket() (string, bool) { - return fmt.Sprintf("not supported on %s", runtime.GOOS), false -} - -func supportsIPv6MulticastDeliveryOnLoopback() bool { - return false -} - -func causesIPv6Crash() bool { - return false -} - -func protocolNotSupported(err error) bool { - return false -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_unix.go b/examples/golang.org/x/net/internal/nettest/helper_unix.go deleted file mode 100644 index ed13e44..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_unix.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package nettest - -import ( - "fmt" - "os" - "runtime" - "syscall" -) - -func maxOpenFiles() int { - var rlim syscall.Rlimit - if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim); err != nil { - return defaultMaxOpenFiles - } - return int(rlim.Cur) -} - -func supportsRawIPSocket() (string, bool) { - if os.Getuid() != 0 { - return fmt.Sprintf("must be root on %s", runtime.GOOS), false - } - return "", true -} diff --git a/examples/golang.org/x/net/internal/nettest/helper_windows.go b/examples/golang.org/x/net/internal/nettest/helper_windows.go deleted file mode 100644 index 3dcb727..0000000 --- a/examples/golang.org/x/net/internal/nettest/helper_windows.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package nettest - -import ( - "fmt" - "runtime" - "syscall" -) - -func maxOpenFiles() int { - return 4 * defaultMaxOpenFiles /* actually it's 16581375 */ -} - -func supportsRawIPSocket() (string, bool) { - // From http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548.aspx: - // Note: To use a socket of type SOCK_RAW requires administrative privileges. - // Users running Winsock applications that use raw sockets must be a member of - // the Administrators group on the local computer, otherwise raw socket calls - // will fail with an error code of WSAEACCES. On Windows Vista and later, access - // for raw sockets is enforced at socket creation. In earlier versions of Windows, - // access for raw sockets is enforced during other socket operations. - s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, 0) - if err == syscall.WSAEACCES { - return fmt.Sprintf("no access to raw socket allowed on %s", runtime.GOOS), false - } - if err != nil { - return err.Error(), false - } - syscall.Closesocket(s) - return "", true -} - -func supportsIPv6MulticastDeliveryOnLoopback() bool { - return true -} - -func causesIPv6Crash() bool { - return false -} diff --git a/examples/golang.org/x/net/internal/nettest/interface.go b/examples/golang.org/x/net/internal/nettest/interface.go deleted file mode 100644 index 8e6333a..0000000 --- a/examples/golang.org/x/net/internal/nettest/interface.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package nettest - -import "net" - -// IsMulticastCapable reports whether ifi is an IP multicast-capable -// network interface. Network must be "ip", "ip4" or "ip6". -func IsMulticastCapable(network string, ifi *net.Interface) (net.IP, bool) { - switch network { - case "ip", "ip4", "ip6": - default: - return nil, false - } - if ifi == nil || ifi.Flags&net.FlagUp == 0 || ifi.Flags&net.FlagMulticast == 0 { - return nil, false - } - return hasRoutableIP(network, ifi) -} - -// RoutedInterface returns a network interface that can route IP -// traffic and satisfies flags. It returns nil when an appropriate -// network interface is not found. Network must be "ip", "ip4" or -// "ip6". -func RoutedInterface(network string, flags net.Flags) *net.Interface { - switch network { - case "ip", "ip4", "ip6": - default: - return nil - } - ift, err := net.Interfaces() - if err != nil { - return nil - } - for _, ifi := range ift { - if ifi.Flags&flags != flags { - continue - } - if _, ok := hasRoutableIP(network, &ifi); !ok { - continue - } - return &ifi - } - return nil -} - -func hasRoutableIP(network string, ifi *net.Interface) (net.IP, bool) { - ifat, err := ifi.Addrs() - if err != nil { - return nil, false - } - for _, ifa := range ifat { - switch ifa := ifa.(type) { - case *net.IPAddr: - if ip := routableIP(network, ifa.IP); ip != nil { - return ip, true - } - case *net.IPNet: - if ip := routableIP(network, ifa.IP); ip != nil { - return ip, true - } - } - } - return nil, false -} - -func routableIP(network string, ip net.IP) net.IP { - if !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !ip.IsGlobalUnicast() { - return nil - } - switch network { - case "ip4": - if ip := ip.To4(); ip != nil { - return ip - } - case "ip6": - if ip.IsLoopback() { // addressing scope of the loopback address depends on each implementation - return nil - } - if ip := ip.To16(); ip != nil && ip.To4() == nil { - return ip - } - default: - if ip := ip.To4(); ip != nil { - return ip - } - if ip := ip.To16(); ip != nil { - return ip - } - } - return nil -} diff --git a/examples/golang.org/x/net/internal/nettest/rlimit.go b/examples/golang.org/x/net/internal/nettest/rlimit.go deleted file mode 100644 index bb34aec..0000000 --- a/examples/golang.org/x/net/internal/nettest/rlimit.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package nettest - -const defaultMaxOpenFiles = 256 - -// MaxOpenFiles returns the maximum number of open files for the -// caller's process. -func MaxOpenFiles() int { return maxOpenFiles() } diff --git a/examples/golang.org/x/net/internal/nettest/stack.go b/examples/golang.org/x/net/internal/nettest/stack.go deleted file mode 100644 index 46d2fcc..0000000 --- a/examples/golang.org/x/net/internal/nettest/stack.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package nettest provides utilities for network testing. -package nettest // import "golang.org/x/net/internal/nettest" - -import ( - "fmt" - "io/ioutil" - "net" - "os" - "runtime" -) - -var ( - supportsIPv4 bool - supportsIPv6 bool -) - -func init() { - if ln, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { - ln.Close() - supportsIPv4 = true - } - if ln, err := net.Listen("tcp6", "[::1]:0"); err == nil { - ln.Close() - supportsIPv6 = true - } -} - -// SupportsIPv4 reports whether the platform supports IPv4 networking -// functionality. -func SupportsIPv4() bool { return supportsIPv4 } - -// SupportsIPv6 reports whether the platform supports IPv6 networking -// functionality. -func SupportsIPv6() bool { return supportsIPv6 } - -// SupportsRawIPSocket reports whether the platform supports raw IP -// sockets. -func SupportsRawIPSocket() (string, bool) { - return supportsRawIPSocket() -} - -// SupportsIPv6MulticastDeliveryOnLoopback reports whether the -// platform supports IPv6 multicast packet delivery on software -// loopback interface. -func SupportsIPv6MulticastDeliveryOnLoopback() bool { - return supportsIPv6MulticastDeliveryOnLoopback() -} - -// ProtocolNotSupported reports whether err is a protocol not -// supported error. -func ProtocolNotSupported(err error) bool { - return protocolNotSupported(err) -} - -// TestableNetwork reports whether network is testable on the current -// platform configuration. -func TestableNetwork(network string) bool { - // This is based on logic from standard library's - // net/platform_test.go. - switch network { - case "unix", "unixgram": - switch runtime.GOOS { - case "android", "js", "nacl", "plan9", "windows": - return false - } - if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") { - return false - } - case "unixpacket": - switch runtime.GOOS { - case "android", "darwin", "freebsd", "js", "nacl", "plan9", "windows": - return false - case "netbsd": - // It passes on amd64 at least. 386 fails (Issue 22927). arm is unknown. - if runtime.GOARCH == "386" { - return false - } - } - } - return true -} - -// NewLocalListener returns a listener which listens to a loopback IP -// address or local file system path. -// Network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket". -func NewLocalListener(network string) (net.Listener, error) { - switch network { - case "tcp": - if supportsIPv4 { - if ln, err := net.Listen("tcp4", "127.0.0.1:0"); err == nil { - return ln, nil - } - } - if supportsIPv6 { - return net.Listen("tcp6", "[::1]:0") - } - case "tcp4": - if supportsIPv4 { - return net.Listen("tcp4", "127.0.0.1:0") - } - case "tcp6": - if supportsIPv6 { - return net.Listen("tcp6", "[::1]:0") - } - case "unix", "unixpacket": - return net.Listen(network, localPath()) - } - return nil, fmt.Errorf("%s is not supported", network) -} - -// NewLocalPacketListener returns a packet listener which listens to a -// loopback IP address or local file system path. -// Network must be "udp", "udp4", "udp6" or "unixgram". -func NewLocalPacketListener(network string) (net.PacketConn, error) { - switch network { - case "udp": - if supportsIPv4 { - if c, err := net.ListenPacket("udp4", "127.0.0.1:0"); err == nil { - return c, nil - } - } - if supportsIPv6 { - return net.ListenPacket("udp6", "[::1]:0") - } - case "udp4": - if supportsIPv4 { - return net.ListenPacket("udp4", "127.0.0.1:0") - } - case "udp6": - if supportsIPv6 { - return net.ListenPacket("udp6", "[::1]:0") - } - case "unixgram": - return net.ListenPacket(network, localPath()) - } - return nil, fmt.Errorf("%s is not supported", network) -} - -func localPath() string { - f, err := ioutil.TempFile("", "nettest") - if err != nil { - panic(err) - } - path := f.Name() - f.Close() - os.Remove(path) - return path -} diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr.go b/examples/golang.org/x/net/internal/socket/cmsghdr.go deleted file mode 100644 index 1eb07d2..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package socket - -func (h *cmsghdr) len() int { return int(h.Len) } -func (h *cmsghdr) lvl() int { return int(h.Level) } -func (h *cmsghdr) typ() int { return int(h.Type) } diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr_bsd.go b/examples/golang.org/x/net/internal/socket/cmsghdr_bsd.go deleted file mode 100644 index d1d0c2d..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr_bsd.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd netbsd openbsd - -package socket - -func (h *cmsghdr) set(l, lvl, typ int) { - h.Len = uint32(l) - h.Level = int32(lvl) - h.Type = int32(typ) -} diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr_linux_32bit.go b/examples/golang.org/x/net/internal/socket/cmsghdr_linux_32bit.go deleted file mode 100644 index bac6681..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr_linux_32bit.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm mips mipsle 386 -// +build linux - -package socket - -func (h *cmsghdr) set(l, lvl, typ int) { - h.Len = uint32(l) - h.Level = int32(lvl) - h.Type = int32(typ) -} diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr_linux_64bit.go b/examples/golang.org/x/net/internal/socket/cmsghdr_linux_64bit.go deleted file mode 100644 index 63f0534..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr_linux_64bit.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x -// +build linux - -package socket - -func (h *cmsghdr) set(l, lvl, typ int) { - h.Len = uint64(l) - h.Level = int32(lvl) - h.Type = int32(typ) -} diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr_solaris_64bit.go b/examples/golang.org/x/net/internal/socket/cmsghdr_solaris_64bit.go deleted file mode 100644 index 7dedd43..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr_solaris_64bit.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 -// +build solaris - -package socket - -func (h *cmsghdr) set(l, lvl, typ int) { - h.Len = uint32(l) - h.Level = int32(lvl) - h.Type = int32(typ) -} diff --git a/examples/golang.org/x/net/internal/socket/cmsghdr_stub.go b/examples/golang.org/x/net/internal/socket/cmsghdr_stub.go deleted file mode 100644 index a4e7122..0000000 --- a/examples/golang.org/x/net/internal/socket/cmsghdr_stub.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris - -package socket - -type cmsghdr struct{} - -const sizeofCmsghdr = 0 - -func (h *cmsghdr) len() int { return 0 } -func (h *cmsghdr) lvl() int { return 0 } -func (h *cmsghdr) typ() int { return 0 } - -func (h *cmsghdr) set(l, lvl, typ int) {} diff --git a/examples/golang.org/x/net/internal/socket/defs_darwin.go b/examples/golang.org/x/net/internal/socket/defs_darwin.go deleted file mode 100644 index 14e28c0..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_darwin.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_dragonfly.go b/examples/golang.org/x/net/internal/socket/defs_dragonfly.go deleted file mode 100644 index 14e28c0..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_dragonfly.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_freebsd.go b/examples/golang.org/x/net/internal/socket/defs_freebsd.go deleted file mode 100644 index 14e28c0..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_freebsd.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_linux.go b/examples/golang.org/x/net/internal/socket/defs_linux.go deleted file mode 100644 index ce9ec2f..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_linux.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include -#include - -#define _GNU_SOURCE -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type mmsghdr C.struct_mmsghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofMmsghdr = C.sizeof_struct_mmsghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_netbsd.go b/examples/golang.org/x/net/internal/socket/defs_netbsd.go deleted file mode 100644 index 3f84335..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_netbsd.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type mmsghdr C.struct_mmsghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofMmsghdr = C.sizeof_struct_mmsghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_openbsd.go b/examples/golang.org/x/net/internal/socket/defs_openbsd.go deleted file mode 100644 index 14e28c0..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_openbsd.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/defs_solaris.go b/examples/golang.org/x/net/internal/socket/defs_solaris.go deleted file mode 100644 index 14e28c0..0000000 --- a/examples/golang.org/x/net/internal/socket/defs_solaris.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// +godefs map struct_in_addr [4]byte /* in_addr */ -// +godefs map struct_in6_addr [16]byte /* in6_addr */ - -package socket - -/* -#include - -#include -*/ -import "C" - -const ( - sysAF_UNSPEC = C.AF_UNSPEC - sysAF_INET = C.AF_INET - sysAF_INET6 = C.AF_INET6 - - sysSOCK_RAW = C.SOCK_RAW -) - -type iovec C.struct_iovec - -type msghdr C.struct_msghdr - -type cmsghdr C.struct_cmsghdr - -type sockaddrInet C.struct_sockaddr_in - -type sockaddrInet6 C.struct_sockaddr_in6 - -const ( - sizeofIovec = C.sizeof_struct_iovec - sizeofMsghdr = C.sizeof_struct_msghdr - sizeofCmsghdr = C.sizeof_struct_cmsghdr - - sizeofSockaddrInet = C.sizeof_struct_sockaddr_in - sizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 -) diff --git a/examples/golang.org/x/net/internal/socket/error_unix.go b/examples/golang.org/x/net/internal/socket/error_unix.go deleted file mode 100644 index 93dff91..0000000 --- a/examples/golang.org/x/net/internal/socket/error_unix.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package socket - -import "syscall" - -var ( - errEAGAIN error = syscall.EAGAIN - errEINVAL error = syscall.EINVAL - errENOENT error = syscall.ENOENT -) - -// errnoErr returns common boxed Errno values, to prevent allocations -// at runtime. -func errnoErr(errno syscall.Errno) error { - switch errno { - case 0: - return nil - case syscall.EAGAIN: - return errEAGAIN - case syscall.EINVAL: - return errEINVAL - case syscall.ENOENT: - return errENOENT - } - return errno -} diff --git a/examples/golang.org/x/net/internal/socket/error_windows.go b/examples/golang.org/x/net/internal/socket/error_windows.go deleted file mode 100644 index 6a6379a..0000000 --- a/examples/golang.org/x/net/internal/socket/error_windows.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import "syscall" - -var ( - errERROR_IO_PENDING error = syscall.ERROR_IO_PENDING - errEINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent allocations -// at runtime. -func errnoErr(errno syscall.Errno) error { - switch errno { - case 0: - return nil - case syscall.ERROR_IO_PENDING: - return errERROR_IO_PENDING - case syscall.EINVAL: - return errEINVAL - } - return errno -} diff --git a/examples/golang.org/x/net/internal/socket/iovec_32bit.go b/examples/golang.org/x/net/internal/socket/iovec_32bit.go deleted file mode 100644 index 05d6082..0000000 --- a/examples/golang.org/x/net/internal/socket/iovec_32bit.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm mips mipsle 386 -// +build darwin dragonfly freebsd linux netbsd openbsd - -package socket - -import "unsafe" - -func (v *iovec) set(b []byte) { - l := len(b) - if l == 0 { - return - } - v.Base = (*byte)(unsafe.Pointer(&b[0])) - v.Len = uint32(l) -} diff --git a/examples/golang.org/x/net/internal/socket/iovec_64bit.go b/examples/golang.org/x/net/internal/socket/iovec_64bit.go deleted file mode 100644 index afb34ad..0000000 --- a/examples/golang.org/x/net/internal/socket/iovec_64bit.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x -// +build darwin dragonfly freebsd linux netbsd openbsd - -package socket - -import "unsafe" - -func (v *iovec) set(b []byte) { - l := len(b) - if l == 0 { - return - } - v.Base = (*byte)(unsafe.Pointer(&b[0])) - v.Len = uint64(l) -} diff --git a/examples/golang.org/x/net/internal/socket/iovec_solaris_64bit.go b/examples/golang.org/x/net/internal/socket/iovec_solaris_64bit.go deleted file mode 100644 index 8d17a40..0000000 --- a/examples/golang.org/x/net/internal/socket/iovec_solaris_64bit.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 -// +build solaris - -package socket - -import "unsafe" - -func (v *iovec) set(b []byte) { - l := len(b) - if l == 0 { - return - } - v.Base = (*int8)(unsafe.Pointer(&b[0])) - v.Len = uint64(l) -} diff --git a/examples/golang.org/x/net/internal/socket/iovec_stub.go b/examples/golang.org/x/net/internal/socket/iovec_stub.go deleted file mode 100644 index c87d2a9..0000000 --- a/examples/golang.org/x/net/internal/socket/iovec_stub.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris - -package socket - -type iovec struct{} - -func (v *iovec) set(b []byte) {} diff --git a/examples/golang.org/x/net/internal/socket/mmsghdr_stub.go b/examples/golang.org/x/net/internal/socket/mmsghdr_stub.go deleted file mode 100644 index 2e80a9c..0000000 --- a/examples/golang.org/x/net/internal/socket/mmsghdr_stub.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !linux,!netbsd - -package socket - -import "net" - -type mmsghdr struct{} - -type mmsghdrs []mmsghdr - -func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error { - return nil -} - -func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error { - return nil -} diff --git a/examples/golang.org/x/net/internal/socket/mmsghdr_unix.go b/examples/golang.org/x/net/internal/socket/mmsghdr_unix.go deleted file mode 100644 index 3c42ea7..0000000 --- a/examples/golang.org/x/net/internal/socket/mmsghdr_unix.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux netbsd - -package socket - -import "net" - -type mmsghdrs []mmsghdr - -func (hs mmsghdrs) pack(ms []Message, parseFn func([]byte, string) (net.Addr, error), marshalFn func(net.Addr) []byte) error { - for i := range hs { - vs := make([]iovec, len(ms[i].Buffers)) - var sa []byte - if parseFn != nil { - sa = make([]byte, sizeofSockaddrInet6) - } - if marshalFn != nil { - sa = marshalFn(ms[i].Addr) - } - hs[i].Hdr.pack(vs, ms[i].Buffers, ms[i].OOB, sa) - } - return nil -} - -func (hs mmsghdrs) unpack(ms []Message, parseFn func([]byte, string) (net.Addr, error), hint string) error { - for i := range hs { - ms[i].N = int(hs[i].Len) - ms[i].NN = hs[i].Hdr.controllen() - ms[i].Flags = hs[i].Hdr.flags() - if parseFn != nil { - var err error - ms[i].Addr, err = parseFn(hs[i].Hdr.name(), hint) - if err != nil { - return err - } - } - } - return nil -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_bsd.go b/examples/golang.org/x/net/internal/socket/msghdr_bsd.go deleted file mode 100644 index 5567afc..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_bsd.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd netbsd openbsd - -package socket - -import "unsafe" - -func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { - for i := range vs { - vs[i].set(bs[i]) - } - h.setIov(vs) - if len(oob) > 0 { - h.Control = (*byte)(unsafe.Pointer(&oob[0])) - h.Controllen = uint32(len(oob)) - } - if sa != nil { - h.Name = (*byte)(unsafe.Pointer(&sa[0])) - h.Namelen = uint32(len(sa)) - } -} - -func (h *msghdr) name() []byte { - if h.Name != nil && h.Namelen > 0 { - return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen] - } - return nil -} - -func (h *msghdr) controllen() int { - return int(h.Controllen) -} - -func (h *msghdr) flags() int { - return int(h.Flags) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_bsdvar.go b/examples/golang.org/x/net/internal/socket/msghdr_bsdvar.go deleted file mode 100644 index b8c87b7..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_bsdvar.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd netbsd - -package socket - -func (h *msghdr) setIov(vs []iovec) { - l := len(vs) - if l == 0 { - return - } - h.Iov = &vs[0] - h.Iovlen = int32(l) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_linux.go b/examples/golang.org/x/net/internal/socket/msghdr_linux.go deleted file mode 100644 index 5a38798..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_linux.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import "unsafe" - -func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { - for i := range vs { - vs[i].set(bs[i]) - } - h.setIov(vs) - if len(oob) > 0 { - h.setControl(oob) - } - if sa != nil { - h.Name = (*byte)(unsafe.Pointer(&sa[0])) - h.Namelen = uint32(len(sa)) - } -} - -func (h *msghdr) name() []byte { - if h.Name != nil && h.Namelen > 0 { - return (*[sizeofSockaddrInet6]byte)(unsafe.Pointer(h.Name))[:h.Namelen] - } - return nil -} - -func (h *msghdr) controllen() int { - return int(h.Controllen) -} - -func (h *msghdr) flags() int { - return int(h.Flags) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_linux_32bit.go b/examples/golang.org/x/net/internal/socket/msghdr_linux_32bit.go deleted file mode 100644 index a7a5987..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_linux_32bit.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm mips mipsle 386 -// +build linux - -package socket - -import "unsafe" - -func (h *msghdr) setIov(vs []iovec) { - l := len(vs) - if l == 0 { - return - } - h.Iov = &vs[0] - h.Iovlen = uint32(l) -} - -func (h *msghdr) setControl(b []byte) { - h.Control = (*byte)(unsafe.Pointer(&b[0])) - h.Controllen = uint32(len(b)) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_linux_64bit.go b/examples/golang.org/x/net/internal/socket/msghdr_linux_64bit.go deleted file mode 100644 index 610fc4f..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_linux_64bit.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm64 amd64 ppc64 ppc64le mips64 mips64le s390x -// +build linux - -package socket - -import "unsafe" - -func (h *msghdr) setIov(vs []iovec) { - l := len(vs) - if l == 0 { - return - } - h.Iov = &vs[0] - h.Iovlen = uint64(l) -} - -func (h *msghdr) setControl(b []byte) { - h.Control = (*byte)(unsafe.Pointer(&b[0])) - h.Controllen = uint64(len(b)) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_openbsd.go b/examples/golang.org/x/net/internal/socket/msghdr_openbsd.go deleted file mode 100644 index 71a69e2..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_openbsd.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -func (h *msghdr) setIov(vs []iovec) { - l := len(vs) - if l == 0 { - return - } - h.Iov = &vs[0] - h.Iovlen = uint32(l) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_solaris_64bit.go b/examples/golang.org/x/net/internal/socket/msghdr_solaris_64bit.go deleted file mode 100644 index 6465b20..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_solaris_64bit.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 -// +build solaris - -package socket - -import "unsafe" - -func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) { - for i := range vs { - vs[i].set(bs[i]) - } - if len(vs) > 0 { - h.Iov = &vs[0] - h.Iovlen = int32(len(vs)) - } - if len(oob) > 0 { - h.Accrights = (*int8)(unsafe.Pointer(&oob[0])) - h.Accrightslen = int32(len(oob)) - } - if sa != nil { - h.Name = (*byte)(unsafe.Pointer(&sa[0])) - h.Namelen = uint32(len(sa)) - } -} - -func (h *msghdr) controllen() int { - return int(h.Accrightslen) -} - -func (h *msghdr) flags() int { - return int(NativeEndian.Uint32(h.Pad_cgo_2[:])) -} diff --git a/examples/golang.org/x/net/internal/socket/msghdr_stub.go b/examples/golang.org/x/net/internal/socket/msghdr_stub.go deleted file mode 100644 index 64e8173..0000000 --- a/examples/golang.org/x/net/internal/socket/msghdr_stub.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris - -package socket - -type msghdr struct{} - -func (h *msghdr) pack(vs []iovec, bs [][]byte, oob []byte, sa []byte) {} -func (h *msghdr) name() []byte { return nil } -func (h *msghdr) controllen() int { return 0 } -func (h *msghdr) flags() int { return 0 } diff --git a/examples/golang.org/x/net/internal/socket/rawconn.go b/examples/golang.org/x/net/internal/socket/rawconn.go deleted file mode 100644 index d6871d5..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 - -package socket - -import ( - "errors" - "net" - "os" - "syscall" -) - -// A Conn represents a raw connection. -type Conn struct { - network string - c syscall.RawConn -} - -// NewConn returns a new raw connection. -func NewConn(c net.Conn) (*Conn, error) { - var err error - var cc Conn - switch c := c.(type) { - case *net.TCPConn: - cc.network = "tcp" - cc.c, err = c.SyscallConn() - case *net.UDPConn: - cc.network = "udp" - cc.c, err = c.SyscallConn() - case *net.IPConn: - cc.network = "ip" - cc.c, err = c.SyscallConn() - default: - return nil, errors.New("unknown connection type") - } - if err != nil { - return nil, err - } - return &cc, nil -} - -func (o *Option) get(c *Conn, b []byte) (int, error) { - var operr error - var n int - fn := func(s uintptr) { - n, operr = getsockopt(s, o.Level, o.Name, b) - } - if err := c.c.Control(fn); err != nil { - return 0, err - } - return n, os.NewSyscallError("getsockopt", operr) -} - -func (o *Option) set(c *Conn, b []byte) error { - var operr error - fn := func(s uintptr) { - operr = setsockopt(s, o.Level, o.Name, b) - } - if err := c.c.Control(fn); err != nil { - return err - } - return os.NewSyscallError("setsockopt", operr) -} diff --git a/examples/golang.org/x/net/internal/socket/rawconn_mmsg.go b/examples/golang.org/x/net/internal/socket/rawconn_mmsg.go deleted file mode 100644 index 499164a..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn_mmsg.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build linux - -package socket - -import ( - "net" - "os" - "syscall" -) - -func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { - hs := make(mmsghdrs, len(ms)) - var parseFn func([]byte, string) (net.Addr, error) - if c.network != "tcp" { - parseFn = parseInetAddr - } - if err := hs.pack(ms, parseFn, nil); err != nil { - return 0, err - } - var operr error - var n int - fn := func(s uintptr) bool { - n, operr = recvmmsg(s, hs, flags) - if operr == syscall.EAGAIN { - return false - } - return true - } - if err := c.c.Read(fn); err != nil { - return n, err - } - if operr != nil { - return n, os.NewSyscallError("recvmmsg", operr) - } - if err := hs[:n].unpack(ms[:n], parseFn, c.network); err != nil { - return n, err - } - return n, nil -} - -func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { - hs := make(mmsghdrs, len(ms)) - var marshalFn func(net.Addr) []byte - if c.network != "tcp" { - marshalFn = marshalInetAddr - } - if err := hs.pack(ms, nil, marshalFn); err != nil { - return 0, err - } - var operr error - var n int - fn := func(s uintptr) bool { - n, operr = sendmmsg(s, hs, flags) - if operr == syscall.EAGAIN { - return false - } - return true - } - if err := c.c.Write(fn); err != nil { - return n, err - } - if operr != nil { - return n, os.NewSyscallError("sendmmsg", operr) - } - if err := hs[:n].unpack(ms[:n], nil, ""); err != nil { - return n, err - } - return n, nil -} diff --git a/examples/golang.org/x/net/internal/socket/rawconn_msg.go b/examples/golang.org/x/net/internal/socket/rawconn_msg.go deleted file mode 100644 index b21d2e6..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn_msg.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package socket - -import ( - "os" - "syscall" -) - -func (c *Conn) recvMsg(m *Message, flags int) error { - var h msghdr - vs := make([]iovec, len(m.Buffers)) - var sa []byte - if c.network != "tcp" { - sa = make([]byte, sizeofSockaddrInet6) - } - h.pack(vs, m.Buffers, m.OOB, sa) - var operr error - var n int - fn := func(s uintptr) bool { - n, operr = recvmsg(s, &h, flags) - if operr == syscall.EAGAIN { - return false - } - return true - } - if err := c.c.Read(fn); err != nil { - return err - } - if operr != nil { - return os.NewSyscallError("recvmsg", operr) - } - if c.network != "tcp" { - var err error - m.Addr, err = parseInetAddr(sa[:], c.network) - if err != nil { - return err - } - } - m.N = n - m.NN = h.controllen() - m.Flags = h.flags() - return nil -} - -func (c *Conn) sendMsg(m *Message, flags int) error { - var h msghdr - vs := make([]iovec, len(m.Buffers)) - var sa []byte - if m.Addr != nil { - sa = marshalInetAddr(m.Addr) - } - h.pack(vs, m.Buffers, m.OOB, sa) - var operr error - var n int - fn := func(s uintptr) bool { - n, operr = sendmsg(s, &h, flags) - if operr == syscall.EAGAIN { - return false - } - return true - } - if err := c.c.Write(fn); err != nil { - return err - } - if operr != nil { - return os.NewSyscallError("sendmsg", operr) - } - m.N = n - m.NN = len(m.OOB) - return nil -} diff --git a/examples/golang.org/x/net/internal/socket/rawconn_nommsg.go b/examples/golang.org/x/net/internal/socket/rawconn_nommsg.go deleted file mode 100644 index f78832a..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn_nommsg.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build !linux - -package socket - -import "errors" - -func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/rawconn_nomsg.go b/examples/golang.org/x/net/internal/socket/rawconn_nomsg.go deleted file mode 100644 index 96733cb..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn_nomsg.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package socket - -import "errors" - -func (c *Conn) recvMsg(m *Message, flags int) error { - return errors.New("not implemented") -} - -func (c *Conn) sendMsg(m *Message, flags int) error { - return errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/rawconn_stub.go b/examples/golang.org/x/net/internal/socket/rawconn_stub.go deleted file mode 100644 index d2add1a..0000000 --- a/examples/golang.org/x/net/internal/socket/rawconn_stub.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.9 - -package socket - -import "errors" - -func (c *Conn) recvMsg(m *Message, flags int) error { - return errors.New("not implemented") -} - -func (c *Conn) sendMsg(m *Message, flags int) error { - return errors.New("not implemented") -} - -func (c *Conn) recvMsgs(ms []Message, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func (c *Conn) sendMsgs(ms []Message, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/reflect.go b/examples/golang.org/x/net/internal/socket/reflect.go deleted file mode 100644 index bb179f1..0000000 --- a/examples/golang.org/x/net/internal/socket/reflect.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.9 - -package socket - -import ( - "errors" - "net" - "os" - "reflect" - "runtime" -) - -// A Conn represents a raw connection. -type Conn struct { - c net.Conn -} - -// NewConn returns a new raw connection. -func NewConn(c net.Conn) (*Conn, error) { - return &Conn{c: c}, nil -} - -func (o *Option) get(c *Conn, b []byte) (int, error) { - s, err := socketOf(c.c) - if err != nil { - return 0, err - } - n, err := getsockopt(s, o.Level, o.Name, b) - return n, os.NewSyscallError("getsockopt", err) -} - -func (o *Option) set(c *Conn, b []byte) error { - s, err := socketOf(c.c) - if err != nil { - return err - } - return os.NewSyscallError("setsockopt", setsockopt(s, o.Level, o.Name, b)) -} - -func socketOf(c net.Conn) (uintptr, error) { - switch c.(type) { - case *net.TCPConn, *net.UDPConn, *net.IPConn: - v := reflect.ValueOf(c) - switch e := v.Elem(); e.Kind() { - case reflect.Struct: - fd := e.FieldByName("conn").FieldByName("fd") - switch e := fd.Elem(); e.Kind() { - case reflect.Struct: - sysfd := e.FieldByName("sysfd") - if runtime.GOOS == "windows" { - return uintptr(sysfd.Uint()), nil - } - return uintptr(sysfd.Int()), nil - } - } - } - return 0, errors.New("invalid type") -} diff --git a/examples/golang.org/x/net/internal/socket/socket.go b/examples/golang.org/x/net/internal/socket/socket.go deleted file mode 100644 index 5f9730e..0000000 --- a/examples/golang.org/x/net/internal/socket/socket.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package socket provides a portable interface for socket system -// calls. -package socket // import "golang.org/x/net/internal/socket" - -import ( - "errors" - "net" - "unsafe" -) - -// An Option represents a sticky socket option. -type Option struct { - Level int // level - Name int // name; must be equal or greater than 1 - Len int // length of value in bytes; must be equal or greater than 1 -} - -// Get reads a value for the option from the kernel. -// It returns the number of bytes written into b. -func (o *Option) Get(c *Conn, b []byte) (int, error) { - if o.Name < 1 || o.Len < 1 { - return 0, errors.New("invalid option") - } - if len(b) < o.Len { - return 0, errors.New("short buffer") - } - return o.get(c, b) -} - -// GetInt returns an integer value for the option. -// -// The Len field of Option must be either 1 or 4. -func (o *Option) GetInt(c *Conn) (int, error) { - if o.Len != 1 && o.Len != 4 { - return 0, errors.New("invalid option") - } - var b []byte - var bb [4]byte - if o.Len == 1 { - b = bb[:1] - } else { - b = bb[:4] - } - n, err := o.get(c, b) - if err != nil { - return 0, err - } - if n != o.Len { - return 0, errors.New("invalid option length") - } - if o.Len == 1 { - return int(b[0]), nil - } - return int(NativeEndian.Uint32(b[:4])), nil -} - -// Set writes the option and value to the kernel. -func (o *Option) Set(c *Conn, b []byte) error { - if o.Name < 1 || o.Len < 1 { - return errors.New("invalid option") - } - if len(b) < o.Len { - return errors.New("short buffer") - } - return o.set(c, b) -} - -// SetInt writes the option and value to the kernel. -// -// The Len field of Option must be either 1 or 4. -func (o *Option) SetInt(c *Conn, v int) error { - if o.Len != 1 && o.Len != 4 { - return errors.New("invalid option") - } - var b []byte - if o.Len == 1 { - b = []byte{byte(v)} - } else { - var bb [4]byte - NativeEndian.PutUint32(bb[:o.Len], uint32(v)) - b = bb[:4] - } - return o.set(c, b) -} - -func controlHeaderLen() int { - return roundup(sizeofCmsghdr) -} - -func controlMessageLen(dataLen int) int { - return roundup(sizeofCmsghdr) + dataLen -} - -// ControlMessageSpace returns the whole length of control message. -func ControlMessageSpace(dataLen int) int { - return roundup(sizeofCmsghdr) + roundup(dataLen) -} - -// A ControlMessage represents the head message in a stream of control -// messages. -// -// A control message comprises of a header, data and a few padding -// fields to conform to the interface to the kernel. -// -// See RFC 3542 for further information. -type ControlMessage []byte - -// Data returns the data field of the control message at the head on -// m. -func (m ControlMessage) Data(dataLen int) []byte { - l := controlHeaderLen() - if len(m) < l || len(m) < l+dataLen { - return nil - } - return m[l : l+dataLen] -} - -// Next returns the control message at the next on m. -// -// Next works only for standard control messages. -func (m ControlMessage) Next(dataLen int) ControlMessage { - l := ControlMessageSpace(dataLen) - if len(m) < l { - return nil - } - return m[l:] -} - -// MarshalHeader marshals the header fields of the control message at -// the head on m. -func (m ControlMessage) MarshalHeader(lvl, typ, dataLen int) error { - if len(m) < controlHeaderLen() { - return errors.New("short message") - } - h := (*cmsghdr)(unsafe.Pointer(&m[0])) - h.set(controlMessageLen(dataLen), lvl, typ) - return nil -} - -// ParseHeader parses and returns the header fields of the control -// message at the head on m. -func (m ControlMessage) ParseHeader() (lvl, typ, dataLen int, err error) { - l := controlHeaderLen() - if len(m) < l { - return 0, 0, 0, errors.New("short message") - } - h := (*cmsghdr)(unsafe.Pointer(&m[0])) - return h.lvl(), h.typ(), int(uint64(h.len()) - uint64(l)), nil -} - -// Marshal marshals the control message at the head on m, and returns -// the next control message. -func (m ControlMessage) Marshal(lvl, typ int, data []byte) (ControlMessage, error) { - l := len(data) - if len(m) < ControlMessageSpace(l) { - return nil, errors.New("short message") - } - h := (*cmsghdr)(unsafe.Pointer(&m[0])) - h.set(controlMessageLen(l), lvl, typ) - if l > 0 { - copy(m.Data(l), data) - } - return m.Next(l), nil -} - -// Parse parses m as a single or multiple control messages. -// -// Parse works for both standard and compatible messages. -func (m ControlMessage) Parse() ([]ControlMessage, error) { - var ms []ControlMessage - for len(m) >= controlHeaderLen() { - h := (*cmsghdr)(unsafe.Pointer(&m[0])) - l := h.len() - if l <= 0 { - return nil, errors.New("invalid header length") - } - if uint64(l) < uint64(controlHeaderLen()) { - return nil, errors.New("invalid message length") - } - if uint64(l) > uint64(len(m)) { - return nil, errors.New("short buffer") - } - // On message reception: - // - // |<- ControlMessageSpace --------------->| - // |<- controlMessageLen ---------->| | - // |<- controlHeaderLen ->| | | - // +---------------+------+---------+------+ - // | Header | PadH | Data | PadD | - // +---------------+------+---------+------+ - // - // On compatible message reception: - // - // | ... |<- controlMessageLen ----------->| - // | ... |<- controlHeaderLen ->| | - // +-----+---------------+------+----------+ - // | ... | Header | PadH | Data | - // +-----+---------------+------+----------+ - ms = append(ms, ControlMessage(m[:l])) - ll := l - controlHeaderLen() - if len(m) >= ControlMessageSpace(ll) { - m = m[ControlMessageSpace(ll):] - } else { - m = m[controlMessageLen(ll):] - } - } - return ms, nil -} - -// NewControlMessage returns a new stream of control messages. -func NewControlMessage(dataLen []int) ControlMessage { - var l int - for i := range dataLen { - l += ControlMessageSpace(dataLen[i]) - } - return make([]byte, l) -} - -// A Message represents an IO message. -type Message struct { - // When writing, the Buffers field must contain at least one - // byte to write. - // When reading, the Buffers field will always contain a byte - // to read. - Buffers [][]byte - - // OOB contains protocol-specific control or miscellaneous - // ancillary data known as out-of-band data. - OOB []byte - - // Addr specifies a destination address when writing. - // It can be nil when the underlying protocol of the raw - // connection uses connection-oriented communication. - // After a successful read, it may contain the source address - // on the received packet. - Addr net.Addr - - N int // # of bytes read or written from/to Buffers - NN int // # of bytes read or written from/to OOB - Flags int // protocol-specific information on the received message -} - -// RecvMsg wraps recvmsg system call. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_PEEK. -func (c *Conn) RecvMsg(m *Message, flags int) error { - return c.recvMsg(m, flags) -} - -// SendMsg wraps sendmsg system call. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_DONTROUTE. -func (c *Conn) SendMsg(m *Message, flags int) error { - return c.sendMsg(m, flags) -} - -// RecvMsgs wraps recvmmsg system call. -// -// It returns the number of processed messages. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_PEEK. -// -// Only Linux supports this. -func (c *Conn) RecvMsgs(ms []Message, flags int) (int, error) { - return c.recvMsgs(ms, flags) -} - -// SendMsgs wraps sendmmsg system call. -// -// It returns the number of processed messages. -// -// The provided flags is a set of platform-dependent flags, such as -// syscall.MSG_DONTROUTE. -// -// Only Linux supports this. -func (c *Conn) SendMsgs(ms []Message, flags int) (int, error) { - return c.sendMsgs(ms, flags) -} diff --git a/examples/golang.org/x/net/internal/socket/socket_go1_9_test.go b/examples/golang.org/x/net/internal/socket/socket_go1_9_test.go deleted file mode 100644 index c4edd4a..0000000 --- a/examples/golang.org/x/net/internal/socket/socket_go1_9_test.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build darwin dragonfly freebsd linux netbsd openbsd solaris - -package socket_test - -import ( - "bytes" - "fmt" - "net" - "runtime" - "testing" - - "golang.org/x/net/internal/nettest" - "golang.org/x/net/internal/socket" -) - -type mockControl struct { - Level int - Type int - Data []byte -} - -func TestControlMessage(t *testing.T) { - for _, tt := range []struct { - cs []mockControl - }{ - { - []mockControl{ - {Level: 1, Type: 1}, - }, - }, - { - []mockControl{ - {Level: 2, Type: 2, Data: []byte{0xfe}}, - }, - }, - { - []mockControl{ - {Level: 3, Type: 3, Data: []byte{0xfe, 0xff, 0xff, 0xfe}}, - }, - }, - { - []mockControl{ - {Level: 4, Type: 4, Data: []byte{0xfe, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xff, 0xfe}}, - }, - }, - { - []mockControl{ - {Level: 4, Type: 4, Data: []byte{0xfe, 0xff, 0xff, 0xfe, 0xfe, 0xff, 0xff, 0xfe}}, - {Level: 2, Type: 2, Data: []byte{0xfe}}, - }, - }, - } { - var w []byte - var tailPadLen int - mm := socket.NewControlMessage([]int{0}) - for i, c := range tt.cs { - m := socket.NewControlMessage([]int{len(c.Data)}) - l := len(m) - len(mm) - if i == len(tt.cs)-1 && l > len(c.Data) { - tailPadLen = l - len(c.Data) - } - w = append(w, m...) - } - - var err error - ww := make([]byte, len(w)) - copy(ww, w) - m := socket.ControlMessage(ww) - for _, c := range tt.cs { - if err = m.MarshalHeader(c.Level, c.Type, len(c.Data)); err != nil { - t.Fatalf("(%v).MarshalHeader() = %v", tt.cs, err) - } - copy(m.Data(len(c.Data)), c.Data) - m = m.Next(len(c.Data)) - } - m = socket.ControlMessage(w) - for _, c := range tt.cs { - m, err = m.Marshal(c.Level, c.Type, c.Data) - if err != nil { - t.Fatalf("(%v).Marshal() = %v", tt.cs, err) - } - } - if !bytes.Equal(ww, w) { - t.Fatalf("got %#v; want %#v", ww, w) - } - - ws := [][]byte{w} - if tailPadLen > 0 { - // Test a message with no tail padding. - nopad := w[:len(w)-tailPadLen] - ws = append(ws, [][]byte{nopad}...) - } - for _, w := range ws { - ms, err := socket.ControlMessage(w).Parse() - if err != nil { - t.Fatalf("(%v).Parse() = %v", tt.cs, err) - } - for i, m := range ms { - lvl, typ, dataLen, err := m.ParseHeader() - if err != nil { - t.Fatalf("(%v).ParseHeader() = %v", tt.cs, err) - } - if lvl != tt.cs[i].Level || typ != tt.cs[i].Type || dataLen != len(tt.cs[i].Data) { - t.Fatalf("%v: got %d, %d, %d; want %d, %d, %d", tt.cs[i], lvl, typ, dataLen, tt.cs[i].Level, tt.cs[i].Type, len(tt.cs[i].Data)) - } - } - } - } -} - -func TestUDP(t *testing.T) { - c, err := nettest.NewLocalPacketListener("udp") - if err != nil { - t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) - } - defer c.Close() - cc, err := socket.NewConn(c.(net.Conn)) - if err != nil { - t.Fatal(err) - } - - t.Run("Message", func(t *testing.T) { - data := []byte("HELLO-R-U-THERE") - wm := socket.Message{ - Buffers: bytes.SplitAfter(data, []byte("-")), - Addr: c.LocalAddr(), - } - if err := cc.SendMsg(&wm, 0); err != nil { - t.Fatal(err) - } - b := make([]byte, 32) - rm := socket.Message{ - Buffers: [][]byte{b[:1], b[1:3], b[3:7], b[7:11], b[11:]}, - } - if err := cc.RecvMsg(&rm, 0); err != nil { - t.Fatal(err) - } - if !bytes.Equal(b[:rm.N], data) { - t.Fatalf("got %#v; want %#v", b[:rm.N], data) - } - }) - switch runtime.GOOS { - case "android", "linux": - t.Run("Messages", func(t *testing.T) { - data := []byte("HELLO-R-U-THERE") - wmbs := bytes.SplitAfter(data, []byte("-")) - wms := []socket.Message{ - {Buffers: wmbs[:1], Addr: c.LocalAddr()}, - {Buffers: wmbs[1:], Addr: c.LocalAddr()}, - } - n, err := cc.SendMsgs(wms, 0) - if err != nil { - t.Fatal(err) - } - if n != len(wms) { - t.Fatalf("got %d; want %d", n, len(wms)) - } - b := make([]byte, 32) - rmbs := [][][]byte{{b[:len(wmbs[0])]}, {b[len(wmbs[0]):]}} - rms := []socket.Message{ - {Buffers: rmbs[0]}, - {Buffers: rmbs[1]}, - } - n, err = cc.RecvMsgs(rms, 0) - if err != nil { - t.Fatal(err) - } - if n != len(rms) { - t.Fatalf("got %d; want %d", n, len(rms)) - } - nn := 0 - for i := 0; i < n; i++ { - nn += rms[i].N - } - if !bytes.Equal(b[:nn], data) { - t.Fatalf("got %#v; want %#v", b[:nn], data) - } - }) - } - - // The behavior of transmission for zero byte paylaod depends - // on each platform implementation. Some may transmit only - // protocol header and options, other may transmit nothing. - // We test only that SendMsg and SendMsgs will not crash with - // empty buffers. - wm := socket.Message{ - Buffers: [][]byte{{}}, - Addr: c.LocalAddr(), - } - cc.SendMsg(&wm, 0) - wms := []socket.Message{ - {Buffers: [][]byte{{}}, Addr: c.LocalAddr()}, - } - cc.SendMsgs(wms, 0) -} - -func BenchmarkUDP(b *testing.B) { - c, err := nettest.NewLocalPacketListener("udp") - if err != nil { - b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) - } - defer c.Close() - cc, err := socket.NewConn(c.(net.Conn)) - if err != nil { - b.Fatal(err) - } - data := []byte("HELLO-R-U-THERE") - wm := socket.Message{ - Buffers: [][]byte{data}, - Addr: c.LocalAddr(), - } - rm := socket.Message{ - Buffers: [][]byte{make([]byte, 128)}, - OOB: make([]byte, 128), - } - - for M := 1; M <= 1<<9; M = M << 1 { - b.Run(fmt.Sprintf("Iter-%d", M), func(b *testing.B) { - for i := 0; i < b.N; i++ { - for j := 0; j < M; j++ { - if err := cc.SendMsg(&wm, 0); err != nil { - b.Fatal(err) - } - if err := cc.RecvMsg(&rm, 0); err != nil { - b.Fatal(err) - } - } - } - }) - switch runtime.GOOS { - case "android", "linux": - wms := make([]socket.Message, M) - for i := range wms { - wms[i].Buffers = [][]byte{data} - wms[i].Addr = c.LocalAddr() - } - rms := make([]socket.Message, M) - for i := range rms { - rms[i].Buffers = [][]byte{make([]byte, 128)} - rms[i].OOB = make([]byte, 128) - } - b.Run(fmt.Sprintf("Batch-%d", M), func(b *testing.B) { - for i := 0; i < b.N; i++ { - if _, err := cc.SendMsgs(wms, 0); err != nil { - b.Fatal(err) - } - if _, err := cc.RecvMsgs(rms, 0); err != nil { - b.Fatal(err) - } - } - }) - } - } -} diff --git a/examples/golang.org/x/net/internal/socket/socket_test.go b/examples/golang.org/x/net/internal/socket/socket_test.go deleted file mode 100644 index bf3751b..0000000 --- a/examples/golang.org/x/net/internal/socket/socket_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package socket_test - -import ( - "net" - "runtime" - "syscall" - "testing" - - "golang.org/x/net/internal/nettest" - "golang.org/x/net/internal/socket" -) - -func TestSocket(t *testing.T) { - t.Run("Option", func(t *testing.T) { - testSocketOption(t, &socket.Option{Level: syscall.SOL_SOCKET, Name: syscall.SO_RCVBUF, Len: 4}) - }) -} - -func testSocketOption(t *testing.T, so *socket.Option) { - c, err := nettest.NewLocalPacketListener("udp") - if err != nil { - t.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) - } - defer c.Close() - cc, err := socket.NewConn(c.(net.Conn)) - if err != nil { - t.Fatal(err) - } - const N = 2048 - if err := so.SetInt(cc, N); err != nil { - t.Fatal(err) - } - n, err := so.GetInt(cc) - if err != nil { - t.Fatal(err) - } - if n < N { - t.Fatalf("got %d; want greater than or equal to %d", n, N) - } -} diff --git a/examples/golang.org/x/net/internal/socket/sys.go b/examples/golang.org/x/net/internal/socket/sys.go deleted file mode 100644 index 4f0eead..0000000 --- a/examples/golang.org/x/net/internal/socket/sys.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "encoding/binary" - "unsafe" -) - -var ( - // NativeEndian is the machine native endian implementation of - // ByteOrder. - NativeEndian binary.ByteOrder - - kernelAlign int -) - -func init() { - i := uint32(1) - b := (*[4]byte)(unsafe.Pointer(&i)) - if b[0] == 1 { - NativeEndian = binary.LittleEndian - } else { - NativeEndian = binary.BigEndian - } - kernelAlign = probeProtocolStack() -} - -func roundup(l int) int { - return (l + kernelAlign - 1) & ^(kernelAlign - 1) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_bsd.go b/examples/golang.org/x/net/internal/socket/sys_bsd.go deleted file mode 100644 index f13e14f..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_bsd.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd openbsd - -package socket - -import "errors" - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/sys_bsdvar.go b/examples/golang.org/x/net/internal/socket/sys_bsdvar.go deleted file mode 100644 index f723fa3..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_bsdvar.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd netbsd openbsd - -package socket - -import "unsafe" - -func probeProtocolStack() int { - var p uintptr - return int(unsafe.Sizeof(p)) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_darwin.go b/examples/golang.org/x/net/internal/socket/sys_darwin.go deleted file mode 100644 index b17d223..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_darwin.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -func probeProtocolStack() int { return 4 } diff --git a/examples/golang.org/x/net/internal/socket/sys_dragonfly.go b/examples/golang.org/x/net/internal/socket/sys_dragonfly.go deleted file mode 100644 index b17d223..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_dragonfly.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -func probeProtocolStack() int { return 4 } diff --git a/examples/golang.org/x/net/internal/socket/sys_linux.go b/examples/golang.org/x/net/internal/socket/sys_linux.go deleted file mode 100644 index 1559521..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux,!s390x,!386 - -package socket - -import ( - "syscall" - "unsafe" -) - -func probeProtocolStack() int { - var p uintptr - return int(unsafe.Sizeof(p)) -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_386.go b/examples/golang.org/x/net/internal/socket/sys_linux_386.go deleted file mode 100644 index 235b2cc..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_386.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "syscall" - "unsafe" -) - -func probeProtocolStack() int { return 4 } - -const ( - sysSETSOCKOPT = 0xe - sysGETSOCKOPT = 0xf - sysSENDMSG = 0x10 - sysRECVMSG = 0x11 - sysRECVMMSG = 0x13 - sysSENDMMSG = 0x14 -) - -func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) -func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - l := uint32(len(b)) - _, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) - return int(l), errnoErr(errno) -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - _, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) - return errnoErr(errno) -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_386.s b/examples/golang.org/x/net/internal/socket/sys_linux_386.s deleted file mode 100644 index 93e7d75..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_386.s +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -TEXT ·socketcall(SB),NOSPLIT,$0-36 - JMP syscall·socketcall(SB) - -TEXT ·rawsocketcall(SB),NOSPLIT,$0-36 - JMP syscall·rawsocketcall(SB) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_amd64.go b/examples/golang.org/x/net/internal/socket/sys_linux_amd64.go deleted file mode 100644 index 9decee2..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_amd64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x12b - sysSENDMMSG = 0x133 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_arm.go b/examples/golang.org/x/net/internal/socket/sys_linux_arm.go deleted file mode 100644 index d753b43..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_arm.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x16d - sysSENDMMSG = 0x176 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_arm64.go b/examples/golang.org/x/net/internal/socket/sys_linux_arm64.go deleted file mode 100644 index b670894..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_arm64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0xf3 - sysSENDMMSG = 0x10d -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_mips.go b/examples/golang.org/x/net/internal/socket/sys_linux_mips.go deleted file mode 100644 index 9c0d740..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_mips.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x10ef - sysSENDMMSG = 0x10f7 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_mips64.go b/examples/golang.org/x/net/internal/socket/sys_linux_mips64.go deleted file mode 100644 index 071a4ab..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_mips64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x14ae - sysSENDMMSG = 0x14b6 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_mips64le.go b/examples/golang.org/x/net/internal/socket/sys_linux_mips64le.go deleted file mode 100644 index 071a4ab..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_mips64le.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x14ae - sysSENDMMSG = 0x14b6 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_mipsle.go b/examples/golang.org/x/net/internal/socket/sys_linux_mipsle.go deleted file mode 100644 index 9c0d740..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_mipsle.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x10ef - sysSENDMMSG = 0x10f7 -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_ppc64.go b/examples/golang.org/x/net/internal/socket/sys_linux_ppc64.go deleted file mode 100644 index 21c1e3f..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_ppc64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x157 - sysSENDMMSG = 0x15d -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_ppc64le.go b/examples/golang.org/x/net/internal/socket/sys_linux_ppc64le.go deleted file mode 100644 index 21c1e3f..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_ppc64le.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -const ( - sysRECVMMSG = 0x157 - sysSENDMMSG = 0x15d -) diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_s390x.go b/examples/golang.org/x/net/internal/socket/sys_linux_s390x.go deleted file mode 100644 index 327979e..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_s390x.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "syscall" - "unsafe" -) - -func probeProtocolStack() int { return 8 } - -const ( - sysSETSOCKOPT = 0xe - sysGETSOCKOPT = 0xf - sysSENDMSG = 0x10 - sysRECVMSG = 0x11 - sysRECVMMSG = 0x13 - sysSENDMMSG = 0x14 -) - -func socketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) -func rawsocketcall(call, a0, a1, a2, a3, a4, a5 uintptr) (uintptr, syscall.Errno) - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - l := uint32(len(b)) - _, errno := socketcall(sysGETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) - return int(l), errnoErr(errno) -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - _, errno := socketcall(sysSETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) - return errnoErr(errno) -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, errno := socketcall(sysRECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, errno := socketcall(sysSENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, errno := socketcall(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, errno := socketcall(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_linux_s390x.s b/examples/golang.org/x/net/internal/socket/sys_linux_s390x.s deleted file mode 100644 index 06d7562..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_linux_s390x.s +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -TEXT ·socketcall(SB),NOSPLIT,$0-72 - JMP syscall·socketcall(SB) - -TEXT ·rawsocketcall(SB),NOSPLIT,$0-72 - JMP syscall·rawsocketcall(SB) diff --git a/examples/golang.org/x/net/internal/socket/sys_netbsd.go b/examples/golang.org/x/net/internal/socket/sys_netbsd.go deleted file mode 100644 index 431851c..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_netbsd.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "syscall" - "unsafe" -) - -const ( - sysRECVMMSG = 0x1db - sysSENDMMSG = 0x1dc -) - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall6(sysRECVMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall6(sysSENDMMSG, s, uintptr(unsafe.Pointer(&hs[0])), uintptr(len(hs)), uintptr(flags), 0, 0) - return int(n), errnoErr(errno) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_posix.go b/examples/golang.org/x/net/internal/socket/sys_posix.go deleted file mode 100644 index dc130c2..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_posix.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.9 -// +build darwin dragonfly freebsd linux netbsd openbsd solaris windows - -package socket - -import ( - "encoding/binary" - "errors" - "net" - "runtime" - "strconv" - "sync" - "time" -) - -func marshalInetAddr(a net.Addr) []byte { - switch a := a.(type) { - case *net.TCPAddr: - return marshalSockaddr(a.IP, a.Port, a.Zone) - case *net.UDPAddr: - return marshalSockaddr(a.IP, a.Port, a.Zone) - case *net.IPAddr: - return marshalSockaddr(a.IP, 0, a.Zone) - default: - return nil - } -} - -func marshalSockaddr(ip net.IP, port int, zone string) []byte { - if ip4 := ip.To4(); ip4 != nil { - b := make([]byte, sizeofSockaddrInet) - switch runtime.GOOS { - case "android", "linux", "solaris", "windows": - NativeEndian.PutUint16(b[:2], uint16(sysAF_INET)) - default: - b[0] = sizeofSockaddrInet - b[1] = sysAF_INET - } - binary.BigEndian.PutUint16(b[2:4], uint16(port)) - copy(b[4:8], ip4) - return b - } - if ip6 := ip.To16(); ip6 != nil && ip.To4() == nil { - b := make([]byte, sizeofSockaddrInet6) - switch runtime.GOOS { - case "android", "linux", "solaris", "windows": - NativeEndian.PutUint16(b[:2], uint16(sysAF_INET6)) - default: - b[0] = sizeofSockaddrInet6 - b[1] = sysAF_INET6 - } - binary.BigEndian.PutUint16(b[2:4], uint16(port)) - copy(b[8:24], ip6) - if zone != "" { - NativeEndian.PutUint32(b[24:28], uint32(zoneCache.index(zone))) - } - return b - } - return nil -} - -func parseInetAddr(b []byte, network string) (net.Addr, error) { - if len(b) < 2 { - return nil, errors.New("invalid address") - } - var af int - switch runtime.GOOS { - case "android", "linux", "solaris", "windows": - af = int(NativeEndian.Uint16(b[:2])) - default: - af = int(b[1]) - } - var ip net.IP - var zone string - if af == sysAF_INET { - if len(b) < sizeofSockaddrInet { - return nil, errors.New("short address") - } - ip = make(net.IP, net.IPv4len) - copy(ip, b[4:8]) - } - if af == sysAF_INET6 { - if len(b) < sizeofSockaddrInet6 { - return nil, errors.New("short address") - } - ip = make(net.IP, net.IPv6len) - copy(ip, b[8:24]) - if id := int(NativeEndian.Uint32(b[24:28])); id > 0 { - zone = zoneCache.name(id) - } - } - switch network { - case "tcp", "tcp4", "tcp6": - return &net.TCPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil - case "udp", "udp4", "udp6": - return &net.UDPAddr{IP: ip, Port: int(binary.BigEndian.Uint16(b[2:4])), Zone: zone}, nil - default: - return &net.IPAddr{IP: ip, Zone: zone}, nil - } -} - -// An ipv6ZoneCache represents a cache holding partial network -// interface information. It is used for reducing the cost of IPv6 -// addressing scope zone resolution. -// -// Multiple names sharing the index are managed by first-come -// first-served basis for consistency. -type ipv6ZoneCache struct { - sync.RWMutex // guard the following - lastFetched time.Time // last time routing information was fetched - toIndex map[string]int // interface name to its index - toName map[int]string // interface index to its name -} - -var zoneCache = ipv6ZoneCache{ - toIndex: make(map[string]int), - toName: make(map[int]string), -} - -func (zc *ipv6ZoneCache) update(ift []net.Interface) { - zc.Lock() - defer zc.Unlock() - now := time.Now() - if zc.lastFetched.After(now.Add(-60 * time.Second)) { - return - } - zc.lastFetched = now - if len(ift) == 0 { - var err error - if ift, err = net.Interfaces(); err != nil { - return - } - } - zc.toIndex = make(map[string]int, len(ift)) - zc.toName = make(map[int]string, len(ift)) - for _, ifi := range ift { - zc.toIndex[ifi.Name] = ifi.Index - if _, ok := zc.toName[ifi.Index]; !ok { - zc.toName[ifi.Index] = ifi.Name - } - } -} - -func (zc *ipv6ZoneCache) name(zone int) string { - zoneCache.update(nil) - zoneCache.RLock() - defer zoneCache.RUnlock() - name, ok := zoneCache.toName[zone] - if !ok { - name = strconv.Itoa(zone) - } - return name -} - -func (zc *ipv6ZoneCache) index(zone string) int { - zoneCache.update(nil) - zoneCache.RLock() - defer zoneCache.RUnlock() - index, ok := zoneCache.toIndex[zone] - if !ok { - index, _ = strconv.Atoi(zone) - } - return index -} diff --git a/examples/golang.org/x/net/internal/socket/sys_solaris.go b/examples/golang.org/x/net/internal/socket/sys_solaris.go deleted file mode 100644 index cced74e..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_solaris.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "errors" - "runtime" - "syscall" - "unsafe" -) - -func probeProtocolStack() int { - switch runtime.GOARCH { - case "amd64": - return 4 - default: - var p uintptr - return int(unsafe.Sizeof(p)) - } -} - -//go:cgo_import_dynamic libc___xnet_getsockopt __xnet_getsockopt "libsocket.so" -//go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" -//go:cgo_import_dynamic libc___xnet_recvmsg __xnet_recvmsg "libsocket.so" -//go:cgo_import_dynamic libc___xnet_sendmsg __xnet_sendmsg "libsocket.so" - -//go:linkname procGetsockopt libc___xnet_getsockopt -//go:linkname procSetsockopt libc_setsockopt -//go:linkname procRecvmsg libc___xnet_recvmsg -//go:linkname procSendmsg libc___xnet_sendmsg - -var ( - procGetsockopt uintptr - procSetsockopt uintptr - procRecvmsg uintptr - procSendmsg uintptr -) - -func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno) -func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (uintptr, uintptr, syscall.Errno) - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - l := uint32(len(b)) - _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procGetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) - return int(l), errnoErr(errno) -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - _, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSetsockopt)), 5, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) - return errnoErr(errno) -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procRecvmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procSendmsg)), 3, s, uintptr(unsafe.Pointer(h)), uintptr(flags), 0, 0, 0) - return int(n), errnoErr(errno) -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/sys_solaris_amd64.s b/examples/golang.org/x/net/internal/socket/sys_solaris_amd64.s deleted file mode 100644 index a18ac5e..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_solaris_amd64.s +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -TEXT ·sysvicall6(SB),NOSPLIT,$0-88 - JMP syscall·sysvicall6(SB) - -TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88 - JMP syscall·rawSysvicall6(SB) diff --git a/examples/golang.org/x/net/internal/socket/sys_stub.go b/examples/golang.org/x/net/internal/socket/sys_stub.go deleted file mode 100644 index d9f06d0..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_stub.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!windows - -package socket - -import ( - "errors" - "net" - "runtime" - "unsafe" -) - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -func probeProtocolStack() int { - switch runtime.GOARCH { - case "amd64p32", "mips64p32": - return 4 - default: - var p uintptr - return int(unsafe.Sizeof(p)) - } -} - -func marshalInetAddr(ip net.IP, port int, zone string) []byte { - return nil -} - -func parseInetAddr(b []byte, network string) (net.Addr, error) { - return nil, errors.New("not implemented") -} - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - return 0, errors.New("not implemented") -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - return errors.New("not implemented") -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/sys_unix.go b/examples/golang.org/x/net/internal/socket/sys_unix.go deleted file mode 100644 index 18eba30..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_unix.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux,!s390x,!386 netbsd openbsd - -package socket - -import ( - "syscall" - "unsafe" -) - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - l := uint32(len(b)) - _, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(unsafe.Pointer(&l)), 0) - return int(l), errnoErr(errno) -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - _, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, s, uintptr(level), uintptr(name), uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), 0) - return errnoErr(errno) -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall(syscall.SYS_RECVMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags)) - return int(n), errnoErr(errno) -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - n, _, errno := syscall.Syscall(syscall.SYS_SENDMSG, s, uintptr(unsafe.Pointer(h)), uintptr(flags)) - return int(n), errnoErr(errno) -} diff --git a/examples/golang.org/x/net/internal/socket/sys_windows.go b/examples/golang.org/x/net/internal/socket/sys_windows.go deleted file mode 100644 index 54a470e..0000000 --- a/examples/golang.org/x/net/internal/socket/sys_windows.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socket - -import ( - "errors" - "syscall" - "unsafe" -) - -func probeProtocolStack() int { - var p uintptr - return int(unsafe.Sizeof(p)) -} - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x17 - - sysSOCK_RAW = 0x3 -) - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) - -func getsockopt(s uintptr, level, name int, b []byte) (int, error) { - l := uint32(len(b)) - err := syscall.Getsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), (*int32)(unsafe.Pointer(&l))) - return int(l), err -} - -func setsockopt(s uintptr, level, name int, b []byte) error { - return syscall.Setsockopt(syscall.Handle(s), int32(level), int32(name), (*byte)(unsafe.Pointer(&b[0])), int32(len(b))) -} - -func recvmsg(s uintptr, h *msghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmsg(s uintptr, h *msghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func recvmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} - -func sendmmsg(s uintptr, hs []mmsghdr, flags int) (int, error) { - return 0, errors.New("not implemented") -} diff --git a/examples/golang.org/x/net/internal/socket/zsys_darwin_386.go b/examples/golang.org/x/net/internal/socket/zsys_darwin_386.go deleted file mode 100644 index 26f8fef..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_darwin_386.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_darwin.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1e - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_darwin_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_darwin_amd64.go deleted file mode 100644 index e2987f7..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_darwin_amd64.go +++ /dev/null @@ -1,61 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_darwin.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1e - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_darwin_arm.go b/examples/golang.org/x/net/internal/socket/zsys_darwin_arm.go deleted file mode 100644 index 26f8fef..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_darwin_arm.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_darwin.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1e - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_darwin_arm64.go b/examples/golang.org/x/net/internal/socket/zsys_darwin_arm64.go deleted file mode 100644 index e2987f7..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_darwin_arm64.go +++ /dev/null @@ -1,61 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_darwin.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1e - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_dragonfly_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_dragonfly_amd64.go deleted file mode 100644 index c582abd..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_dragonfly_amd64.go +++ /dev/null @@ -1,61 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_dragonfly.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1c - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_freebsd_386.go b/examples/golang.org/x/net/internal/socket/zsys_freebsd_386.go deleted file mode 100644 index 04a2488..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_freebsd_386.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1c - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_freebsd_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_freebsd_amd64.go deleted file mode 100644 index 35c7cb9..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_freebsd_amd64.go +++ /dev/null @@ -1,61 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1c - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_freebsd_arm.go b/examples/golang.org/x/net/internal/socket/zsys_freebsd_arm.go deleted file mode 100644 index 04a2488..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_freebsd_arm.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_freebsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1c - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_386.go b/examples/golang.org/x/net/internal/socket/zsys_linux_386.go deleted file mode 100644 index 4302069..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_386.go +++ /dev/null @@ -1,63 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_linux_amd64.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_amd64.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_arm.go b/examples/golang.org/x/net/internal/socket/zsys_linux_arm.go deleted file mode 100644 index 4302069..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_arm.go +++ /dev/null @@ -1,63 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_arm64.go b/examples/golang.org/x/net/internal/socket/zsys_linux_arm64.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_arm64.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_mips.go b/examples/golang.org/x/net/internal/socket/zsys_linux_mips.go deleted file mode 100644 index 4302069..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_mips.go +++ /dev/null @@ -1,63 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_mips64.go b/examples/golang.org/x/net/internal/socket/zsys_linux_mips64.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_mips64.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_mips64le.go b/examples/golang.org/x/net/internal/socket/zsys_linux_mips64le.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_mips64le.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_mipsle.go b/examples/golang.org/x/net/internal/socket/zsys_linux_mipsle.go deleted file mode 100644 index 4302069..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_mipsle.go +++ /dev/null @@ -1,63 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64.go b/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64le.go b/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64le.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_ppc64le.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_linux_s390x.go b/examples/golang.org/x/net/internal/socket/zsys_linux_s390x.go deleted file mode 100644 index 1502f6c..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_linux_s390x.go +++ /dev/null @@ -1,66 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_linux.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0xa - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint64 - Control *byte - Controllen uint64 - Flags int32 - Pad_cgo_1 [4]byte -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint64 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - X__pad [8]uint8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x38 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0x10 - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_netbsd_386.go b/examples/golang.org/x/net/internal/socket/zsys_netbsd_386.go deleted file mode 100644 index db60491..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_netbsd_386.go +++ /dev/null @@ -1,65 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_netbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_netbsd_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_netbsd_amd64.go deleted file mode 100644 index 2a1a799..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_netbsd_amd64.go +++ /dev/null @@ -1,68 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_netbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 - Pad_cgo_0 [4]byte -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofMmsghdr = 0x40 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_netbsd_arm.go b/examples/golang.org/x/net/internal/socket/zsys_netbsd_arm.go deleted file mode 100644 index db60491..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_netbsd_arm.go +++ /dev/null @@ -1,65 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_netbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen int32 - Control *byte - Controllen uint32 - Flags int32 -} - -type mmsghdr struct { - Hdr msghdr - Len uint32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofMmsghdr = 0x20 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_openbsd_386.go b/examples/golang.org/x/net/internal/socket/zsys_openbsd_386.go deleted file mode 100644 index 1c83636..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_openbsd_386.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_openbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_openbsd_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_openbsd_amd64.go deleted file mode 100644 index a6c0bf4..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_openbsd_amd64.go +++ /dev/null @@ -1,61 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_openbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen uint32 - Pad_cgo_1 [4]byte - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_openbsd_arm.go b/examples/golang.org/x/net/internal/socket/zsys_openbsd_arm.go deleted file mode 100644 index 1c83636..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_openbsd_arm.go +++ /dev/null @@ -1,59 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_openbsd.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x18 - - sysSOCK_RAW = 0x3 -) - -type iovec struct { - Base *byte - Len uint32 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Iov *iovec - Iovlen uint32 - Control *byte - Controllen uint32 - Flags int32 -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Len uint8 - Family uint8 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Len uint8 - Family uint8 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 -} - -const ( - sizeofIovec = 0x8 - sizeofMsghdr = 0x1c - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x1c -) diff --git a/examples/golang.org/x/net/internal/socket/zsys_solaris_amd64.go b/examples/golang.org/x/net/internal/socket/zsys_solaris_amd64.go deleted file mode 100644 index 327c632..0000000 --- a/examples/golang.org/x/net/internal/socket/zsys_solaris_amd64.go +++ /dev/null @@ -1,60 +0,0 @@ -// Created by cgo -godefs - DO NOT EDIT -// cgo -godefs defs_solaris.go - -package socket - -const ( - sysAF_UNSPEC = 0x0 - sysAF_INET = 0x2 - sysAF_INET6 = 0x1a - - sysSOCK_RAW = 0x4 -) - -type iovec struct { - Base *int8 - Len uint64 -} - -type msghdr struct { - Name *byte - Namelen uint32 - Pad_cgo_0 [4]byte - Iov *iovec - Iovlen int32 - Pad_cgo_1 [4]byte - Accrights *int8 - Accrightslen int32 - Pad_cgo_2 [4]byte -} - -type cmsghdr struct { - Len uint32 - Level int32 - Type int32 -} - -type sockaddrInet struct { - Family uint16 - Port uint16 - Addr [4]byte /* in_addr */ - Zero [8]int8 -} - -type sockaddrInet6 struct { - Family uint16 - Port uint16 - Flowinfo uint32 - Addr [16]byte /* in6_addr */ - Scope_id uint32 - X__sin6_src_id uint32 -} - -const ( - sizeofIovec = 0x10 - sizeofMsghdr = 0x30 - sizeofCmsghdr = 0xc - - sizeofSockaddrInet = 0x10 - sizeofSockaddrInet6 = 0x20 -) diff --git a/examples/golang.org/x/net/internal/socks/client.go b/examples/golang.org/x/net/internal/socks/client.go deleted file mode 100644 index 3d6f516..0000000 --- a/examples/golang.org/x/net/internal/socks/client.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socks - -import ( - "context" - "errors" - "io" - "net" - "strconv" - "time" -) - -var ( - noDeadline = time.Time{} - aLongTimeAgo = time.Unix(1, 0) -) - -func (d *Dialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error) { - host, port, err := splitHostPort(address) - if err != nil { - return nil, err - } - if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() { - c.SetDeadline(deadline) - defer c.SetDeadline(noDeadline) - } - if ctx != context.Background() { - errCh := make(chan error, 1) - done := make(chan struct{}) - defer func() { - close(done) - if ctxErr == nil { - ctxErr = <-errCh - } - }() - go func() { - select { - case <-ctx.Done(): - c.SetDeadline(aLongTimeAgo) - errCh <- ctx.Err() - case <-done: - errCh <- nil - } - }() - } - - b := make([]byte, 0, 6+len(host)) // the size here is just an estimate - b = append(b, Version5) - if len(d.AuthMethods) == 0 || d.Authenticate == nil { - b = append(b, 1, byte(AuthMethodNotRequired)) - } else { - ams := d.AuthMethods - if len(ams) > 255 { - return nil, errors.New("too many authentication methods") - } - b = append(b, byte(len(ams))) - for _, am := range ams { - b = append(b, byte(am)) - } - } - if _, ctxErr = c.Write(b); ctxErr != nil { - return - } - - if _, ctxErr = io.ReadFull(c, b[:2]); ctxErr != nil { - return - } - if b[0] != Version5 { - return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0]))) - } - am := AuthMethod(b[1]) - if am == AuthMethodNoAcceptableMethods { - return nil, errors.New("no acceptable authentication methods") - } - if d.Authenticate != nil { - if ctxErr = d.Authenticate(ctx, c, am); ctxErr != nil { - return - } - } - - b = b[:0] - b = append(b, Version5, byte(d.cmd), 0) - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - b = append(b, AddrTypeIPv4) - b = append(b, ip4...) - } else if ip6 := ip.To16(); ip6 != nil { - b = append(b, AddrTypeIPv6) - b = append(b, ip6...) - } else { - return nil, errors.New("unknown address type") - } - } else { - if len(host) > 255 { - return nil, errors.New("FQDN too long") - } - b = append(b, AddrTypeFQDN) - b = append(b, byte(len(host))) - b = append(b, host...) - } - b = append(b, byte(port>>8), byte(port)) - if _, ctxErr = c.Write(b); ctxErr != nil { - return - } - - if _, ctxErr = io.ReadFull(c, b[:4]); ctxErr != nil { - return - } - if b[0] != Version5 { - return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0]))) - } - if cmdErr := Reply(b[1]); cmdErr != StatusSucceeded { - return nil, errors.New("unknown error " + cmdErr.String()) - } - if b[2] != 0 { - return nil, errors.New("non-zero reserved field") - } - l := 2 - var a Addr - switch b[3] { - case AddrTypeIPv4: - l += net.IPv4len - a.IP = make(net.IP, net.IPv4len) - case AddrTypeIPv6: - l += net.IPv6len - a.IP = make(net.IP, net.IPv6len) - case AddrTypeFQDN: - if _, err := io.ReadFull(c, b[:1]); err != nil { - return nil, err - } - l += int(b[0]) - default: - return nil, errors.New("unknown address type " + strconv.Itoa(int(b[3]))) - } - if cap(b) < l { - b = make([]byte, l) - } else { - b = b[:l] - } - if _, ctxErr = io.ReadFull(c, b); ctxErr != nil { - return - } - if a.IP != nil { - copy(a.IP, b) - } else { - a.Name = string(b[:len(b)-2]) - } - a.Port = int(b[len(b)-2])<<8 | int(b[len(b)-1]) - return &a, nil -} - -func splitHostPort(address string) (string, int, error) { - host, port, err := net.SplitHostPort(address) - if err != nil { - return "", 0, err - } - portnum, err := strconv.Atoi(port) - if err != nil { - return "", 0, err - } - if 1 > portnum || portnum > 0xffff { - return "", 0, errors.New("port number out of range " + port) - } - return host, portnum, nil -} diff --git a/examples/golang.org/x/net/internal/socks/dial_test.go b/examples/golang.org/x/net/internal/socks/dial_test.go deleted file mode 100644 index 3a7a31b..0000000 --- a/examples/golang.org/x/net/internal/socks/dial_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package socks_test - -import ( - "context" - "io" - "math/rand" - "net" - "os" - "testing" - "time" - - "golang.org/x/net/internal/socks" - "golang.org/x/net/internal/sockstest" -) - -func TestDial(t *testing.T) { - t.Run("Connect", func(t *testing.T) { - ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired) - if err != nil { - t.Fatal(err) - } - defer ss.Close() - d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String()) - d.AuthMethods = []socks.AuthMethod{ - socks.AuthMethodNotRequired, - socks.AuthMethodUsernamePassword, - } - d.Authenticate = (&socks.UsernamePassword{ - Username: "username", - Password: "password", - }).Authenticate - c, err := d.DialContext(context.Background(), ss.TargetAddr().Network(), ss.TargetAddr().String()) - if err != nil { - t.Fatal(err) - } - c.(*socks.Conn).BoundAddr() - c.Close() - }) - t.Run("ConnectWithConn", func(t *testing.T) { - ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired) - if err != nil { - t.Fatal(err) - } - defer ss.Close() - c, err := net.Dial(ss.Addr().Network(), ss.Addr().String()) - if err != nil { - t.Fatal(err) - } - defer c.Close() - d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String()) - d.AuthMethods = []socks.AuthMethod{ - socks.AuthMethodNotRequired, - socks.AuthMethodUsernamePassword, - } - d.Authenticate = (&socks.UsernamePassword{ - Username: "username", - Password: "password", - }).Authenticate - a, err := d.DialWithConn(context.Background(), c, ss.TargetAddr().Network(), ss.TargetAddr().String()) - if err != nil { - t.Fatal(err) - } - if _, ok := a.(*socks.Addr); !ok { - t.Fatalf("got %+v; want socks.Addr", a) - } - }) - t.Run("Cancel", func(t *testing.T) { - ss, err := sockstest.NewServer(sockstest.NoAuthRequired, blackholeCmdFunc) - if err != nil { - t.Fatal(err) - } - defer ss.Close() - d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String()) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - dialErr := make(chan error) - go func() { - c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String()) - if err == nil { - c.Close() - } - dialErr <- err - }() - time.Sleep(100 * time.Millisecond) - cancel() - err = <-dialErr - if perr, nerr := parseDialError(err); perr != context.Canceled && nerr == nil { - t.Fatalf("got %v; want context.Canceled or equivalent", err) - } - }) - t.Run("Deadline", func(t *testing.T) { - ss, err := sockstest.NewServer(sockstest.NoAuthRequired, blackholeCmdFunc) - if err != nil { - t.Fatal(err) - } - defer ss.Close() - d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String()) - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond)) - defer cancel() - c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String()) - if err == nil { - c.Close() - } - if perr, nerr := parseDialError(err); perr != context.DeadlineExceeded && nerr == nil { - t.Fatalf("got %v; want context.DeadlineExceeded or equivalent", err) - } - }) - t.Run("WithRogueServer", func(t *testing.T) { - ss, err := sockstest.NewServer(sockstest.NoAuthRequired, rogueCmdFunc) - if err != nil { - t.Fatal(err) - } - defer ss.Close() - d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String()) - for i := 0; i < 2*len(rogueCmdList); i++ { - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond)) - defer cancel() - c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String()) - if err == nil { - t.Log(c.(*socks.Conn).BoundAddr()) - c.Close() - t.Error("should fail") - } - } - }) -} - -func blackholeCmdFunc(rw io.ReadWriter, b []byte) error { - if _, err := sockstest.ParseCmdRequest(b); err != nil { - return err - } - var bb [1]byte - for { - if _, err := rw.Read(bb[:]); err != nil { - return err - } - } -} - -func rogueCmdFunc(rw io.ReadWriter, b []byte) error { - if _, err := sockstest.ParseCmdRequest(b); err != nil { - return err - } - rw.Write(rogueCmdList[rand.Intn(len(rogueCmdList))]) - return nil -} - -var rogueCmdList = [][]byte{ - {0x05}, - {0x06, 0x00, 0x00, 0x01, 192, 0, 2, 1, 0x17, 0x4b}, - {0x05, 0x00, 0xff, 0x01, 192, 0, 2, 2, 0x17, 0x4b}, - {0x05, 0x00, 0x00, 0x01, 192, 0, 2, 3}, - {0x05, 0x00, 0x00, 0x03, 0x04, 'F', 'Q', 'D', 'N'}, -} - -func parseDialError(err error) (perr, nerr error) { - if e, ok := err.(*net.OpError); ok { - err = e.Err - nerr = e - } - if e, ok := err.(*os.SyscallError); ok { - err = e.Err - } - perr = err - return -} diff --git a/examples/golang.org/x/net/internal/socks/socks.go b/examples/golang.org/x/net/internal/socks/socks.go deleted file mode 100644 index d93e699..0000000 --- a/examples/golang.org/x/net/internal/socks/socks.go +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package socks provides a SOCKS version 5 client implementation. -// -// SOCKS protocol version 5 is defined in RFC 1928. -// Username/Password authentication for SOCKS version 5 is defined in -// RFC 1929. -package socks - -import ( - "context" - "errors" - "io" - "net" - "strconv" -) - -// A Command represents a SOCKS command. -type Command int - -func (cmd Command) String() string { - switch cmd { - case CmdConnect: - return "socks connect" - case cmdBind: - return "socks bind" - default: - return "socks " + strconv.Itoa(int(cmd)) - } -} - -// An AuthMethod represents a SOCKS authentication method. -type AuthMethod int - -// A Reply represents a SOCKS command reply code. -type Reply int - -func (code Reply) String() string { - switch code { - case StatusSucceeded: - return "succeeded" - case 0x01: - return "general SOCKS server failure" - case 0x02: - return "connection not allowed by ruleset" - case 0x03: - return "network unreachable" - case 0x04: - return "host unreachable" - case 0x05: - return "connection refused" - case 0x06: - return "TTL expired" - case 0x07: - return "command not supported" - case 0x08: - return "address type not supported" - default: - return "unknown code: " + strconv.Itoa(int(code)) - } -} - -// Wire protocol constants. -const ( - Version5 = 0x05 - - AddrTypeIPv4 = 0x01 - AddrTypeFQDN = 0x03 - AddrTypeIPv6 = 0x04 - - CmdConnect Command = 0x01 // establishes an active-open forward proxy connection - cmdBind Command = 0x02 // establishes a passive-open forward proxy connection - - AuthMethodNotRequired AuthMethod = 0x00 // no authentication required - AuthMethodUsernamePassword AuthMethod = 0x02 // use username/password - AuthMethodNoAcceptableMethods AuthMethod = 0xff // no acceptable authentication methods - - StatusSucceeded Reply = 0x00 -) - -// An Addr represents a SOCKS-specific address. -// Either Name or IP is used exclusively. -type Addr struct { - Name string // fully-qualified domain name - IP net.IP - Port int -} - -func (a *Addr) Network() string { return "socks" } - -func (a *Addr) String() string { - if a == nil { - return "" - } - port := strconv.Itoa(a.Port) - if a.IP == nil { - return net.JoinHostPort(a.Name, port) - } - return net.JoinHostPort(a.IP.String(), port) -} - -// A Conn represents a forward proxy connection. -type Conn struct { - net.Conn - - boundAddr net.Addr -} - -// BoundAddr returns the address assigned by the proxy server for -// connecting to the command target address from the proxy server. -func (c *Conn) BoundAddr() net.Addr { - if c == nil { - return nil - } - return c.boundAddr -} - -// A Dialer holds SOCKS-specific options. -type Dialer struct { - cmd Command // either CmdConnect or cmdBind - proxyNetwork string // network between a proxy server and a client - proxyAddress string // proxy server address - - // ProxyDial specifies the optional dial function for - // establishing the transport connection. - ProxyDial func(context.Context, string, string) (net.Conn, error) - - // AuthMethods specifies the list of request authention - // methods. - // If empty, SOCKS client requests only AuthMethodNotRequired. - AuthMethods []AuthMethod - - // Authenticate specifies the optional authentication - // function. It must be non-nil when AuthMethods is not empty. - // It must return an error when the authentication is failed. - Authenticate func(context.Context, io.ReadWriter, AuthMethod) error -} - -// DialContext connects to the provided address on the provided -// network. -// -// The returned error value may be a net.OpError. When the Op field of -// net.OpError contains "socks", the Source field contains a proxy -// server address and the Addr field contains a command target -// address. -// -// See func Dial of the net package of standard library for a -// description of the network and address parameters. -func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if ctx == nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")} - } - var err error - var c net.Conn - if d.ProxyDial != nil { - c, err = d.ProxyDial(ctx, d.proxyNetwork, d.proxyAddress) - } else { - var dd net.Dialer - c, err = dd.DialContext(ctx, d.proxyNetwork, d.proxyAddress) - } - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - a, err := d.connect(ctx, c, address) - if err != nil { - c.Close() - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - return &Conn{Conn: c, boundAddr: a}, nil -} - -// DialWithConn initiates a connection from SOCKS server to the target -// network and address using the connection c that is already -// connected to the SOCKS server. -// -// It returns the connection's local address assigned by the SOCKS -// server. -func (d *Dialer) DialWithConn(ctx context.Context, c net.Conn, network, address string) (net.Addr, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if ctx == nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")} - } - a, err := d.connect(ctx, c, address) - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - return a, nil -} - -// Dial connects to the provided address on the provided network. -// -// Unlike DialContext, it returns a raw transport connection instead -// of a forward proxy connection. -// -// Deprecated: Use DialContext or DialWithConn instead. -func (d *Dialer) Dial(network, address string) (net.Conn, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - var err error - var c net.Conn - if d.ProxyDial != nil { - c, err = d.ProxyDial(context.Background(), d.proxyNetwork, d.proxyAddress) - } else { - c, err = net.Dial(d.proxyNetwork, d.proxyAddress) - } - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if _, err := d.DialWithConn(context.Background(), c, network, address); err != nil { - return nil, err - } - return c, nil -} - -func (d *Dialer) validateTarget(network, address string) error { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return errors.New("network not implemented") - } - switch d.cmd { - case CmdConnect, cmdBind: - default: - return errors.New("command not implemented") - } - return nil -} - -func (d *Dialer) pathAddrs(address string) (proxy, dst net.Addr, err error) { - for i, s := range []string{d.proxyAddress, address} { - host, port, err := splitHostPort(s) - if err != nil { - return nil, nil, err - } - a := &Addr{Port: port} - a.IP = net.ParseIP(host) - if a.IP == nil { - a.Name = host - } - if i == 0 { - proxy = a - } else { - dst = a - } - } - return -} - -// NewDialer returns a new Dialer that dials through the provided -// proxy server's network and address. -func NewDialer(network, address string) *Dialer { - return &Dialer{proxyNetwork: network, proxyAddress: address, cmd: CmdConnect} -} - -const ( - authUsernamePasswordVersion = 0x01 - authStatusSucceeded = 0x00 -) - -// UsernamePassword are the credentials for the username/password -// authentication method. -type UsernamePassword struct { - Username string - Password string -} - -// Authenticate authenticates a pair of username and password with the -// proxy server. -func (up *UsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, auth AuthMethod) error { - switch auth { - case AuthMethodNotRequired: - return nil - case AuthMethodUsernamePassword: - if len(up.Username) == 0 || len(up.Username) > 255 || len(up.Password) == 0 || len(up.Password) > 255 { - return errors.New("invalid username/password") - } - b := []byte{authUsernamePasswordVersion} - b = append(b, byte(len(up.Username))) - b = append(b, up.Username...) - b = append(b, byte(len(up.Password))) - b = append(b, up.Password...) - // TODO(mikio): handle IO deadlines and cancelation if - // necessary - if _, err := rw.Write(b); err != nil { - return err - } - if _, err := io.ReadFull(rw, b[:2]); err != nil { - return err - } - if b[0] != authUsernamePasswordVersion { - return errors.New("invalid username/password version") - } - if b[1] != authStatusSucceeded { - return errors.New("username/password authentication failed") - } - return nil - } - return errors.New("unsupported authentication method " + strconv.Itoa(int(auth))) -} diff --git a/examples/golang.org/x/net/internal/sockstest/server.go b/examples/golang.org/x/net/internal/sockstest/server.go deleted file mode 100644 index 3c6e9e9..0000000 --- a/examples/golang.org/x/net/internal/sockstest/server.go +++ /dev/null @@ -1,241 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sockstest provides utilities for SOCKS testing. -package sockstest - -import ( - "errors" - "io" - "net" - - "golang.org/x/net/internal/nettest" - "golang.org/x/net/internal/socks" -) - -// An AuthRequest represents an authentication request. -type AuthRequest struct { - Version int - Methods []socks.AuthMethod -} - -// ParseAuthRequest parses an authentication request. -func ParseAuthRequest(b []byte) (*AuthRequest, error) { - if len(b) < 2 { - return nil, errors.New("short auth request") - } - if b[0] != socks.Version5 { - return nil, errors.New("unexpected protocol version") - } - if len(b)-2 < int(b[1]) { - return nil, errors.New("short auth request") - } - req := &AuthRequest{Version: int(b[0])} - if b[1] > 0 { - req.Methods = make([]socks.AuthMethod, b[1]) - for i, m := range b[2 : 2+b[1]] { - req.Methods[i] = socks.AuthMethod(m) - } - } - return req, nil -} - -// MarshalAuthReply returns an authentication reply in wire format. -func MarshalAuthReply(ver int, m socks.AuthMethod) ([]byte, error) { - return []byte{byte(ver), byte(m)}, nil -} - -// A CmdRequest repesents a command request. -type CmdRequest struct { - Version int - Cmd socks.Command - Addr socks.Addr -} - -// ParseCmdRequest parses a command request. -func ParseCmdRequest(b []byte) (*CmdRequest, error) { - if len(b) < 7 { - return nil, errors.New("short cmd request") - } - if b[0] != socks.Version5 { - return nil, errors.New("unexpected protocol version") - } - if socks.Command(b[1]) != socks.CmdConnect { - return nil, errors.New("unexpected command") - } - if b[2] != 0 { - return nil, errors.New("non-zero reserved field") - } - req := &CmdRequest{Version: int(b[0]), Cmd: socks.Command(b[1])} - l := 2 - off := 4 - switch b[3] { - case socks.AddrTypeIPv4: - l += net.IPv4len - req.Addr.IP = make(net.IP, net.IPv4len) - case socks.AddrTypeIPv6: - l += net.IPv6len - req.Addr.IP = make(net.IP, net.IPv6len) - case socks.AddrTypeFQDN: - l += int(b[4]) - off = 5 - default: - return nil, errors.New("unknown address type") - } - if len(b[off:]) < l { - return nil, errors.New("short cmd request") - } - if req.Addr.IP != nil { - copy(req.Addr.IP, b[off:]) - } else { - req.Addr.Name = string(b[off : off+l-2]) - } - req.Addr.Port = int(b[off+l-2])<<8 | int(b[off+l-1]) - return req, nil -} - -// MarshalCmdReply returns a command reply in wire format. -func MarshalCmdReply(ver int, reply socks.Reply, a *socks.Addr) ([]byte, error) { - b := make([]byte, 4) - b[0] = byte(ver) - b[1] = byte(reply) - if a.Name != "" { - if len(a.Name) > 255 { - return nil, errors.New("fqdn too long") - } - b[3] = socks.AddrTypeFQDN - b = append(b, byte(len(a.Name))) - b = append(b, a.Name...) - } else if ip4 := a.IP.To4(); ip4 != nil { - b[3] = socks.AddrTypeIPv4 - b = append(b, ip4...) - } else if ip6 := a.IP.To16(); ip6 != nil { - b[3] = socks.AddrTypeIPv6 - b = append(b, ip6...) - } else { - return nil, errors.New("unknown address type") - } - b = append(b, byte(a.Port>>8), byte(a.Port)) - return b, nil -} - -// A Server repesents a server for handshake testing. -type Server struct { - ln net.Listener -} - -// Addr rerurns a server address. -func (s *Server) Addr() net.Addr { - return s.ln.Addr() -} - -// TargetAddr returns a fake final destination address. -// -// The returned address is only valid for testing with Server. -func (s *Server) TargetAddr() net.Addr { - a := s.ln.Addr() - switch a := a.(type) { - case *net.TCPAddr: - if a.IP.To4() != nil { - return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 5963} - } - if a.IP.To16() != nil && a.IP.To4() == nil { - return &net.TCPAddr{IP: net.IPv6loopback, Port: 5963} - } - } - return nil -} - -// Close closes the server. -func (s *Server) Close() error { - return s.ln.Close() -} - -func (s *Server) serve(authFunc, cmdFunc func(io.ReadWriter, []byte) error) { - c, err := s.ln.Accept() - if err != nil { - return - } - defer c.Close() - go s.serve(authFunc, cmdFunc) - b := make([]byte, 512) - n, err := c.Read(b) - if err != nil { - return - } - if err := authFunc(c, b[:n]); err != nil { - return - } - n, err = c.Read(b) - if err != nil { - return - } - if err := cmdFunc(c, b[:n]); err != nil { - return - } -} - -// NewServer returns a new server. -// -// The provided authFunc and cmdFunc must parse requests and return -// appropriate replies to clients. -func NewServer(authFunc, cmdFunc func(io.ReadWriter, []byte) error) (*Server, error) { - var err error - s := new(Server) - s.ln, err = nettest.NewLocalListener("tcp") - if err != nil { - return nil, err - } - go s.serve(authFunc, cmdFunc) - return s, nil -} - -// NoAuthRequired handles a no-authentication-required signaling. -func NoAuthRequired(rw io.ReadWriter, b []byte) error { - req, err := ParseAuthRequest(b) - if err != nil { - return err - } - b, err = MarshalAuthReply(req.Version, socks.AuthMethodNotRequired) - if err != nil { - return err - } - n, err := rw.Write(b) - if err != nil { - return err - } - if n != len(b) { - return errors.New("short write") - } - return nil -} - -// NoProxyRequired handles a command signaling without constructing a -// proxy connection to the final destination. -func NoProxyRequired(rw io.ReadWriter, b []byte) error { - req, err := ParseCmdRequest(b) - if err != nil { - return err - } - req.Addr.Port += 1 - if req.Addr.Name != "" { - req.Addr.Name = "boundaddr.doesnotexist" - } else if req.Addr.IP.To4() != nil { - req.Addr.IP = net.IPv4(127, 0, 0, 1) - } else { - req.Addr.IP = net.IPv6loopback - } - b, err = MarshalCmdReply(socks.Version5, socks.StatusSucceeded, &req.Addr) - if err != nil { - return err - } - n, err := rw.Write(b) - if err != nil { - return err - } - if n != len(b) { - return errors.New("short write") - } - return nil -} diff --git a/examples/golang.org/x/net/internal/sockstest/server_test.go b/examples/golang.org/x/net/internal/sockstest/server_test.go deleted file mode 100644 index 2b02d81..0000000 --- a/examples/golang.org/x/net/internal/sockstest/server_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sockstest - -import ( - "net" - "reflect" - "testing" - - "golang.org/x/net/internal/socks" -) - -func TestParseAuthRequest(t *testing.T) { - for i, tt := range []struct { - wire []byte - req *AuthRequest - }{ - { - []byte{0x05, 0x00}, - &AuthRequest{ - socks.Version5, - nil, - }, - }, - { - []byte{0x05, 0x01, 0xff}, - &AuthRequest{ - socks.Version5, - []socks.AuthMethod{ - socks.AuthMethodNoAcceptableMethods, - }, - }, - }, - { - []byte{0x05, 0x02, 0x00, 0xff}, - &AuthRequest{ - socks.Version5, - []socks.AuthMethod{ - socks.AuthMethodNotRequired, - socks.AuthMethodNoAcceptableMethods, - }, - }, - }, - - // corrupted requests - {nil, nil}, - {[]byte{0x00, 0x01}, nil}, - {[]byte{0x06, 0x00}, nil}, - {[]byte{0x05, 0x02, 0x00}, nil}, - } { - req, err := ParseAuthRequest(tt.wire) - if !reflect.DeepEqual(req, tt.req) { - t.Errorf("#%d: got %v, %v; want %v", i, req, err, tt.req) - continue - } - } -} - -func TestParseCmdRequest(t *testing.T) { - for i, tt := range []struct { - wire []byte - req *CmdRequest - }{ - { - []byte{0x05, 0x01, 0x00, 0x01, 192, 0, 2, 1, 0x17, 0x4b}, - &CmdRequest{ - socks.Version5, - socks.CmdConnect, - socks.Addr{ - IP: net.IP{192, 0, 2, 1}, - Port: 5963, - }, - }, - }, - { - []byte{0x05, 0x01, 0x00, 0x03, 0x04, 'F', 'Q', 'D', 'N', 0x17, 0x4b}, - &CmdRequest{ - socks.Version5, - socks.CmdConnect, - socks.Addr{ - Name: "FQDN", - Port: 5963, - }, - }, - }, - - // corrupted requests - {nil, nil}, - {[]byte{0x05}, nil}, - {[]byte{0x06, 0x01, 0x00, 0x01, 192, 0, 2, 2, 0x17, 0x4b}, nil}, - {[]byte{0x05, 0x01, 0xff, 0x01, 192, 0, 2, 3}, nil}, - {[]byte{0x05, 0x01, 0x00, 0x01, 192, 0, 2, 4}, nil}, - {[]byte{0x05, 0x01, 0x00, 0x03, 0x04, 'F', 'Q', 'D', 'N'}, nil}, - } { - req, err := ParseCmdRequest(tt.wire) - if !reflect.DeepEqual(req, tt.req) { - t.Errorf("#%d: got %v, %v; want %v", i, req, err, tt.req) - continue - } - } -} diff --git a/examples/golang.org/x/net/internal/timeseries/timeseries.go b/examples/golang.org/x/net/internal/timeseries/timeseries.go deleted file mode 100644 index 685f0e7..0000000 --- a/examples/golang.org/x/net/internal/timeseries/timeseries.go +++ /dev/null @@ -1,525 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package timeseries implements a time series structure for stats collection. -package timeseries // import "golang.org/x/net/internal/timeseries" - -import ( - "fmt" - "log" - "time" -) - -const ( - timeSeriesNumBuckets = 64 - minuteHourSeriesNumBuckets = 60 -) - -var timeSeriesResolutions = []time.Duration{ - 1 * time.Second, - 10 * time.Second, - 1 * time.Minute, - 10 * time.Minute, - 1 * time.Hour, - 6 * time.Hour, - 24 * time.Hour, // 1 day - 7 * 24 * time.Hour, // 1 week - 4 * 7 * 24 * time.Hour, // 4 weeks - 16 * 7 * 24 * time.Hour, // 16 weeks -} - -var minuteHourSeriesResolutions = []time.Duration{ - 1 * time.Second, - 1 * time.Minute, -} - -// An Observable is a kind of data that can be aggregated in a time series. -type Observable interface { - Multiply(ratio float64) // Multiplies the data in self by a given ratio - Add(other Observable) // Adds the data from a different observation to self - Clear() // Clears the observation so it can be reused. - CopyFrom(other Observable) // Copies the contents of a given observation to self -} - -// Float attaches the methods of Observable to a float64. -type Float float64 - -// NewFloat returns a Float. -func NewFloat() Observable { - f := Float(0) - return &f -} - -// String returns the float as a string. -func (f *Float) String() string { return fmt.Sprintf("%g", f.Value()) } - -// Value returns the float's value. -func (f *Float) Value() float64 { return float64(*f) } - -func (f *Float) Multiply(ratio float64) { *f *= Float(ratio) } - -func (f *Float) Add(other Observable) { - o := other.(*Float) - *f += *o -} - -func (f *Float) Clear() { *f = 0 } - -func (f *Float) CopyFrom(other Observable) { - o := other.(*Float) - *f = *o -} - -// A Clock tells the current time. -type Clock interface { - Time() time.Time -} - -type defaultClock int - -var defaultClockInstance defaultClock - -func (defaultClock) Time() time.Time { return time.Now() } - -// Information kept per level. Each level consists of a circular list of -// observations. The start of the level may be derived from end and the -// len(buckets) * sizeInMillis. -type tsLevel struct { - oldest int // index to oldest bucketed Observable - newest int // index to newest bucketed Observable - end time.Time // end timestamp for this level - size time.Duration // duration of the bucketed Observable - buckets []Observable // collections of observations - provider func() Observable // used for creating new Observable -} - -func (l *tsLevel) Clear() { - l.oldest = 0 - l.newest = len(l.buckets) - 1 - l.end = time.Time{} - for i := range l.buckets { - if l.buckets[i] != nil { - l.buckets[i].Clear() - l.buckets[i] = nil - } - } -} - -func (l *tsLevel) InitLevel(size time.Duration, numBuckets int, f func() Observable) { - l.size = size - l.provider = f - l.buckets = make([]Observable, numBuckets) -} - -// Keeps a sequence of levels. Each level is responsible for storing data at -// a given resolution. For example, the first level stores data at a one -// minute resolution while the second level stores data at a one hour -// resolution. - -// Each level is represented by a sequence of buckets. Each bucket spans an -// interval equal to the resolution of the level. New observations are added -// to the last bucket. -type timeSeries struct { - provider func() Observable // make more Observable - numBuckets int // number of buckets in each level - levels []*tsLevel // levels of bucketed Observable - lastAdd time.Time // time of last Observable tracked - total Observable // convenient aggregation of all Observable - clock Clock // Clock for getting current time - pending Observable // observations not yet bucketed - pendingTime time.Time // what time are we keeping in pending - dirty bool // if there are pending observations -} - -// init initializes a level according to the supplied criteria. -func (ts *timeSeries) init(resolutions []time.Duration, f func() Observable, numBuckets int, clock Clock) { - ts.provider = f - ts.numBuckets = numBuckets - ts.clock = clock - ts.levels = make([]*tsLevel, len(resolutions)) - - for i := range resolutions { - if i > 0 && resolutions[i-1] >= resolutions[i] { - log.Print("timeseries: resolutions must be monotonically increasing") - break - } - newLevel := new(tsLevel) - newLevel.InitLevel(resolutions[i], ts.numBuckets, ts.provider) - ts.levels[i] = newLevel - } - - ts.Clear() -} - -// Clear removes all observations from the time series. -func (ts *timeSeries) Clear() { - ts.lastAdd = time.Time{} - ts.total = ts.resetObservation(ts.total) - ts.pending = ts.resetObservation(ts.pending) - ts.pendingTime = time.Time{} - ts.dirty = false - - for i := range ts.levels { - ts.levels[i].Clear() - } -} - -// Add records an observation at the current time. -func (ts *timeSeries) Add(observation Observable) { - ts.AddWithTime(observation, ts.clock.Time()) -} - -// AddWithTime records an observation at the specified time. -func (ts *timeSeries) AddWithTime(observation Observable, t time.Time) { - - smallBucketDuration := ts.levels[0].size - - if t.After(ts.lastAdd) { - ts.lastAdd = t - } - - if t.After(ts.pendingTime) { - ts.advance(t) - ts.mergePendingUpdates() - ts.pendingTime = ts.levels[0].end - ts.pending.CopyFrom(observation) - ts.dirty = true - } else if t.After(ts.pendingTime.Add(-1 * smallBucketDuration)) { - // The observation is close enough to go into the pending bucket. - // This compensates for clock skewing and small scheduling delays - // by letting the update stay in the fast path. - ts.pending.Add(observation) - ts.dirty = true - } else { - ts.mergeValue(observation, t) - } -} - -// mergeValue inserts the observation at the specified time in the past into all levels. -func (ts *timeSeries) mergeValue(observation Observable, t time.Time) { - for _, level := range ts.levels { - index := (ts.numBuckets - 1) - int(level.end.Sub(t)/level.size) - if 0 <= index && index < ts.numBuckets { - bucketNumber := (level.oldest + index) % ts.numBuckets - if level.buckets[bucketNumber] == nil { - level.buckets[bucketNumber] = level.provider() - } - level.buckets[bucketNumber].Add(observation) - } - } - ts.total.Add(observation) -} - -// mergePendingUpdates applies the pending updates into all levels. -func (ts *timeSeries) mergePendingUpdates() { - if ts.dirty { - ts.mergeValue(ts.pending, ts.pendingTime) - ts.pending = ts.resetObservation(ts.pending) - ts.dirty = false - } -} - -// advance cycles the buckets at each level until the latest bucket in -// each level can hold the time specified. -func (ts *timeSeries) advance(t time.Time) { - if !t.After(ts.levels[0].end) { - return - } - for i := 0; i < len(ts.levels); i++ { - level := ts.levels[i] - if !level.end.Before(t) { - break - } - - // If the time is sufficiently far, just clear the level and advance - // directly. - if !t.Before(level.end.Add(level.size * time.Duration(ts.numBuckets))) { - for _, b := range level.buckets { - ts.resetObservation(b) - } - level.end = time.Unix(0, (t.UnixNano()/level.size.Nanoseconds())*level.size.Nanoseconds()) - } - - for t.After(level.end) { - level.end = level.end.Add(level.size) - level.newest = level.oldest - level.oldest = (level.oldest + 1) % ts.numBuckets - ts.resetObservation(level.buckets[level.newest]) - } - - t = level.end - } -} - -// Latest returns the sum of the num latest buckets from the level. -func (ts *timeSeries) Latest(level, num int) Observable { - now := ts.clock.Time() - if ts.levels[0].end.Before(now) { - ts.advance(now) - } - - ts.mergePendingUpdates() - - result := ts.provider() - l := ts.levels[level] - index := l.newest - - for i := 0; i < num; i++ { - if l.buckets[index] != nil { - result.Add(l.buckets[index]) - } - if index == 0 { - index = ts.numBuckets - } - index-- - } - - return result -} - -// LatestBuckets returns a copy of the num latest buckets from level. -func (ts *timeSeries) LatestBuckets(level, num int) []Observable { - if level < 0 || level > len(ts.levels) { - log.Print("timeseries: bad level argument: ", level) - return nil - } - if num < 0 || num >= ts.numBuckets { - log.Print("timeseries: bad num argument: ", num) - return nil - } - - results := make([]Observable, num) - now := ts.clock.Time() - if ts.levels[0].end.Before(now) { - ts.advance(now) - } - - ts.mergePendingUpdates() - - l := ts.levels[level] - index := l.newest - - for i := 0; i < num; i++ { - result := ts.provider() - results[i] = result - if l.buckets[index] != nil { - result.CopyFrom(l.buckets[index]) - } - - if index == 0 { - index = ts.numBuckets - } - index -= 1 - } - return results -} - -// ScaleBy updates observations by scaling by factor. -func (ts *timeSeries) ScaleBy(factor float64) { - for _, l := range ts.levels { - for i := 0; i < ts.numBuckets; i++ { - l.buckets[i].Multiply(factor) - } - } - - ts.total.Multiply(factor) - ts.pending.Multiply(factor) -} - -// Range returns the sum of observations added over the specified time range. -// If start or finish times don't fall on bucket boundaries of the same -// level, then return values are approximate answers. -func (ts *timeSeries) Range(start, finish time.Time) Observable { - return ts.ComputeRange(start, finish, 1)[0] -} - -// Recent returns the sum of observations from the last delta. -func (ts *timeSeries) Recent(delta time.Duration) Observable { - now := ts.clock.Time() - return ts.Range(now.Add(-delta), now) -} - -// Total returns the total of all observations. -func (ts *timeSeries) Total() Observable { - ts.mergePendingUpdates() - return ts.total -} - -// ComputeRange computes a specified number of values into a slice using -// the observations recorded over the specified time period. The return -// values are approximate if the start or finish times don't fall on the -// bucket boundaries at the same level or if the number of buckets spanning -// the range is not an integral multiple of num. -func (ts *timeSeries) ComputeRange(start, finish time.Time, num int) []Observable { - if start.After(finish) { - log.Printf("timeseries: start > finish, %v>%v", start, finish) - return nil - } - - if num < 0 { - log.Printf("timeseries: num < 0, %v", num) - return nil - } - - results := make([]Observable, num) - - for _, l := range ts.levels { - if !start.Before(l.end.Add(-l.size * time.Duration(ts.numBuckets))) { - ts.extract(l, start, finish, num, results) - return results - } - } - - // Failed to find a level that covers the desired range. So just - // extract from the last level, even if it doesn't cover the entire - // desired range. - ts.extract(ts.levels[len(ts.levels)-1], start, finish, num, results) - - return results -} - -// RecentList returns the specified number of values in slice over the most -// recent time period of the specified range. -func (ts *timeSeries) RecentList(delta time.Duration, num int) []Observable { - if delta < 0 { - return nil - } - now := ts.clock.Time() - return ts.ComputeRange(now.Add(-delta), now, num) -} - -// extract returns a slice of specified number of observations from a given -// level over a given range. -func (ts *timeSeries) extract(l *tsLevel, start, finish time.Time, num int, results []Observable) { - ts.mergePendingUpdates() - - srcInterval := l.size - dstInterval := finish.Sub(start) / time.Duration(num) - dstStart := start - srcStart := l.end.Add(-srcInterval * time.Duration(ts.numBuckets)) - - srcIndex := 0 - - // Where should scanning start? - if dstStart.After(srcStart) { - advance := dstStart.Sub(srcStart) / srcInterval - srcIndex += int(advance) - srcStart = srcStart.Add(advance * srcInterval) - } - - // The i'th value is computed as show below. - // interval = (finish/start)/num - // i'th value = sum of observation in range - // [ start + i * interval, - // start + (i + 1) * interval ) - for i := 0; i < num; i++ { - results[i] = ts.resetObservation(results[i]) - dstEnd := dstStart.Add(dstInterval) - for srcIndex < ts.numBuckets && srcStart.Before(dstEnd) { - srcEnd := srcStart.Add(srcInterval) - if srcEnd.After(ts.lastAdd) { - srcEnd = ts.lastAdd - } - - if !srcEnd.Before(dstStart) { - srcValue := l.buckets[(srcIndex+l.oldest)%ts.numBuckets] - if !srcStart.Before(dstStart) && !srcEnd.After(dstEnd) { - // dst completely contains src. - if srcValue != nil { - results[i].Add(srcValue) - } - } else { - // dst partially overlaps src. - overlapStart := maxTime(srcStart, dstStart) - overlapEnd := minTime(srcEnd, dstEnd) - base := srcEnd.Sub(srcStart) - fraction := overlapEnd.Sub(overlapStart).Seconds() / base.Seconds() - - used := ts.provider() - if srcValue != nil { - used.CopyFrom(srcValue) - } - used.Multiply(fraction) - results[i].Add(used) - } - - if srcEnd.After(dstEnd) { - break - } - } - srcIndex++ - srcStart = srcStart.Add(srcInterval) - } - dstStart = dstStart.Add(dstInterval) - } -} - -// resetObservation clears the content so the struct may be reused. -func (ts *timeSeries) resetObservation(observation Observable) Observable { - if observation == nil { - observation = ts.provider() - } else { - observation.Clear() - } - return observation -} - -// TimeSeries tracks data at granularities from 1 second to 16 weeks. -type TimeSeries struct { - timeSeries -} - -// NewTimeSeries creates a new TimeSeries using the function provided for creating new Observable. -func NewTimeSeries(f func() Observable) *TimeSeries { - return NewTimeSeriesWithClock(f, defaultClockInstance) -} - -// NewTimeSeriesWithClock creates a new TimeSeries using the function provided for creating new Observable and the clock for -// assigning timestamps. -func NewTimeSeriesWithClock(f func() Observable, clock Clock) *TimeSeries { - ts := new(TimeSeries) - ts.timeSeries.init(timeSeriesResolutions, f, timeSeriesNumBuckets, clock) - return ts -} - -// MinuteHourSeries tracks data at granularities of 1 minute and 1 hour. -type MinuteHourSeries struct { - timeSeries -} - -// NewMinuteHourSeries creates a new MinuteHourSeries using the function provided for creating new Observable. -func NewMinuteHourSeries(f func() Observable) *MinuteHourSeries { - return NewMinuteHourSeriesWithClock(f, defaultClockInstance) -} - -// NewMinuteHourSeriesWithClock creates a new MinuteHourSeries using the function provided for creating new Observable and the clock for -// assigning timestamps. -func NewMinuteHourSeriesWithClock(f func() Observable, clock Clock) *MinuteHourSeries { - ts := new(MinuteHourSeries) - ts.timeSeries.init(minuteHourSeriesResolutions, f, - minuteHourSeriesNumBuckets, clock) - return ts -} - -func (ts *MinuteHourSeries) Minute() Observable { - return ts.timeSeries.Latest(0, 60) -} - -func (ts *MinuteHourSeries) Hour() Observable { - return ts.timeSeries.Latest(1, 60) -} - -func minTime(a, b time.Time) time.Time { - if a.Before(b) { - return a - } - return b -} - -func maxTime(a, b time.Time) time.Time { - if a.After(b) { - return a - } - return b -} diff --git a/examples/golang.org/x/net/internal/timeseries/timeseries_test.go b/examples/golang.org/x/net/internal/timeseries/timeseries_test.go deleted file mode 100644 index 66325a9..0000000 --- a/examples/golang.org/x/net/internal/timeseries/timeseries_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package timeseries - -import ( - "math" - "testing" - "time" -) - -func isNear(x *Float, y float64, tolerance float64) bool { - return math.Abs(x.Value()-y) < tolerance -} - -func isApproximate(x *Float, y float64) bool { - return isNear(x, y, 1e-2) -} - -func checkApproximate(t *testing.T, o Observable, y float64) { - x := o.(*Float) - if !isApproximate(x, y) { - t.Errorf("Wanted %g, got %g", y, x.Value()) - } -} - -func checkNear(t *testing.T, o Observable, y, tolerance float64) { - x := o.(*Float) - if !isNear(x, y, tolerance) { - t.Errorf("Wanted %g +- %g, got %g", y, tolerance, x.Value()) - } -} - -var baseTime = time.Date(2013, 1, 1, 0, 0, 0, 0, time.UTC) - -func tu(s int64) time.Time { - return baseTime.Add(time.Duration(s) * time.Second) -} - -func tu2(s int64, ns int64) time.Time { - return baseTime.Add(time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond) -} - -func TestBasicTimeSeries(t *testing.T) { - ts := NewTimeSeries(NewFloat) - fo := new(Float) - *fo = Float(10) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(1)), 40) - checkApproximate(t, ts.Total(), 40) - ts.AddWithTime(fo, tu(3)) - ts.AddWithTime(fo, tu(3)) - ts.AddWithTime(fo, tu(3)) - checkApproximate(t, ts.Range(tu(0), tu(2)), 40) - checkApproximate(t, ts.Range(tu(2), tu(4)), 30) - checkApproximate(t, ts.Total(), 70) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(2)), 60) - checkApproximate(t, ts.Range(tu(2), tu(4)), 30) - checkApproximate(t, ts.Total(), 90) - *fo = Float(100) - ts.AddWithTime(fo, tu(100)) - checkApproximate(t, ts.Range(tu(99), tu(100)), 100) - checkApproximate(t, ts.Range(tu(0), tu(4)), 36) - checkApproximate(t, ts.Total(), 190) - *fo = Float(10) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(4)), 44) - checkApproximate(t, ts.Range(tu(37), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Range(tu(50), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Range(tu(99), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Total(), 210) - - for i, l := range ts.ComputeRange(tu(36), tu(100), 64) { - if i == 63 { - checkApproximate(t, l, 100) - } else { - checkApproximate(t, l, 0) - } - } - - checkApproximate(t, ts.Range(tu(0), tu(100)), 210) - checkApproximate(t, ts.Range(tu(10), tu(100)), 100) - - for i, l := range ts.ComputeRange(tu(0), tu(100), 100) { - if i < 10 { - checkApproximate(t, l, 11) - } else if i >= 90 { - checkApproximate(t, l, 10) - } else { - checkApproximate(t, l, 0) - } - } -} - -func TestFloat(t *testing.T) { - f := Float(1) - if g, w := f.String(), "1"; g != w { - t.Errorf("Float(1).String = %q; want %q", g, w) - } - f2 := Float(2) - var o Observable = &f2 - f.Add(o) - if g, w := f.Value(), 3.0; g != w { - t.Errorf("Float post-add = %v; want %v", g, w) - } - f.Multiply(2) - if g, w := f.Value(), 6.0; g != w { - t.Errorf("Float post-multiply = %v; want %v", g, w) - } - f.Clear() - if g, w := f.Value(), 0.0; g != w { - t.Errorf("Float post-clear = %v; want %v", g, w) - } - f.CopyFrom(&f2) - if g, w := f.Value(), 2.0; g != w { - t.Errorf("Float post-CopyFrom = %v; want %v", g, w) - } -} - -type mockClock struct { - time time.Time -} - -func (m *mockClock) Time() time.Time { return m.time } -func (m *mockClock) Set(t time.Time) { m.time = t } - -const buckets = 6 - -var testResolutions = []time.Duration{ - 10 * time.Second, // level holds one minute of observations - 100 * time.Second, // level holds ten minutes of observations - 10 * time.Minute, // level holds one hour of observations -} - -// TestTimeSeries uses a small number of buckets to force a higher -// error rate on approximations from the timeseries. -type TestTimeSeries struct { - timeSeries -} - -func TestExpectedErrorRate(t *testing.T) { - ts := new(TestTimeSeries) - fake := new(mockClock) - fake.Set(time.Now()) - ts.timeSeries.init(testResolutions, NewFloat, buckets, fake) - for i := 1; i <= 61*61; i++ { - fake.Set(fake.Time().Add(1 * time.Second)) - ob := Float(1) - ts.AddWithTime(&ob, fake.Time()) - - // The results should be accurate within one missing bucket (1/6) of the observations recorded. - checkNear(t, ts.Latest(0, buckets), min(float64(i), 60), 10) - checkNear(t, ts.Latest(1, buckets), min(float64(i), 600), 100) - checkNear(t, ts.Latest(2, buckets), min(float64(i), 3600), 600) - } -} - -func min(a, b float64) float64 { - if a < b { - return a - } - return b -} diff --git a/examples/golang.org/x/net/trace/events.go b/examples/golang.org/x/net/trace/events.go deleted file mode 100644 index c646a69..0000000 --- a/examples/golang.org/x/net/trace/events.go +++ /dev/null @@ -1,532 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -import ( - "bytes" - "fmt" - "html/template" - "io" - "log" - "net/http" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "text/tabwriter" - "time" -) - -const maxEventsPerLog = 100 - -type bucket struct { - MaxErrAge time.Duration - String string -} - -var buckets = []bucket{ - {0, "total"}, - {10 * time.Second, "errs<10s"}, - {1 * time.Minute, "errs<1m"}, - {10 * time.Minute, "errs<10m"}, - {1 * time.Hour, "errs<1h"}, - {10 * time.Hour, "errs<10h"}, - {24000 * time.Hour, "errors"}, -} - -// RenderEvents renders the HTML page typically served at /debug/events. -// It does not do any auth checking. The request may be nil. -// -// Most users will use the Events handler. -func RenderEvents(w http.ResponseWriter, req *http.Request, sensitive bool) { - now := time.Now() - data := &struct { - Families []string // family names - Buckets []bucket - Counts [][]int // eventLog count per family/bucket - - // Set when a bucket has been selected. - Family string - Bucket int - EventLogs eventLogs - Expanded bool - }{ - Buckets: buckets, - } - - data.Families = make([]string, 0, len(families)) - famMu.RLock() - for name := range families { - data.Families = append(data.Families, name) - } - famMu.RUnlock() - sort.Strings(data.Families) - - // Count the number of eventLogs in each family for each error age. - data.Counts = make([][]int, len(data.Families)) - for i, name := range data.Families { - // TODO(sameer): move this loop under the family lock. - f := getEventFamily(name) - data.Counts[i] = make([]int, len(data.Buckets)) - for j, b := range data.Buckets { - data.Counts[i][j] = f.Count(now, b.MaxErrAge) - } - } - - if req != nil { - var ok bool - data.Family, data.Bucket, ok = parseEventsArgs(req) - if !ok { - // No-op - } else { - data.EventLogs = getEventFamily(data.Family).Copy(now, buckets[data.Bucket].MaxErrAge) - } - if data.EventLogs != nil { - defer data.EventLogs.Free() - sort.Sort(data.EventLogs) - } - if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { - data.Expanded = exp - } - } - - famMu.RLock() - defer famMu.RUnlock() - if err := eventsTmpl().Execute(w, data); err != nil { - log.Printf("net/trace: Failed executing template: %v", err) - } -} - -func parseEventsArgs(req *http.Request) (fam string, b int, ok bool) { - fam, bStr := req.FormValue("fam"), req.FormValue("b") - if fam == "" || bStr == "" { - return "", 0, false - } - b, err := strconv.Atoi(bStr) - if err != nil || b < 0 || b >= len(buckets) { - return "", 0, false - } - return fam, b, true -} - -// An EventLog provides a log of events associated with a specific object. -type EventLog interface { - // Printf formats its arguments with fmt.Sprintf and adds the - // result to the event log. - Printf(format string, a ...interface{}) - - // Errorf is like Printf, but it marks this event as an error. - Errorf(format string, a ...interface{}) - - // Finish declares that this event log is complete. - // The event log should not be used after calling this method. - Finish() -} - -// NewEventLog returns a new EventLog with the specified family name -// and title. -func NewEventLog(family, title string) EventLog { - el := newEventLog() - el.ref() - el.Family, el.Title = family, title - el.Start = time.Now() - el.events = make([]logEntry, 0, maxEventsPerLog) - el.stack = make([]uintptr, 32) - n := runtime.Callers(2, el.stack) - el.stack = el.stack[:n] - - getEventFamily(family).add(el) - return el -} - -func (el *eventLog) Finish() { - getEventFamily(el.Family).remove(el) - el.unref() // matches ref in New -} - -var ( - famMu sync.RWMutex - families = make(map[string]*eventFamily) // family name => family -) - -func getEventFamily(fam string) *eventFamily { - famMu.Lock() - defer famMu.Unlock() - f := families[fam] - if f == nil { - f = &eventFamily{} - families[fam] = f - } - return f -} - -type eventFamily struct { - mu sync.RWMutex - eventLogs eventLogs -} - -func (f *eventFamily) add(el *eventLog) { - f.mu.Lock() - f.eventLogs = append(f.eventLogs, el) - f.mu.Unlock() -} - -func (f *eventFamily) remove(el *eventLog) { - f.mu.Lock() - defer f.mu.Unlock() - for i, el0 := range f.eventLogs { - if el == el0 { - copy(f.eventLogs[i:], f.eventLogs[i+1:]) - f.eventLogs = f.eventLogs[:len(f.eventLogs)-1] - return - } - } -} - -func (f *eventFamily) Count(now time.Time, maxErrAge time.Duration) (n int) { - f.mu.RLock() - defer f.mu.RUnlock() - for _, el := range f.eventLogs { - if el.hasRecentError(now, maxErrAge) { - n++ - } - } - return -} - -func (f *eventFamily) Copy(now time.Time, maxErrAge time.Duration) (els eventLogs) { - f.mu.RLock() - defer f.mu.RUnlock() - els = make(eventLogs, 0, len(f.eventLogs)) - for _, el := range f.eventLogs { - if el.hasRecentError(now, maxErrAge) { - el.ref() - els = append(els, el) - } - } - return -} - -type eventLogs []*eventLog - -// Free calls unref on each element of the list. -func (els eventLogs) Free() { - for _, el := range els { - el.unref() - } -} - -// eventLogs may be sorted in reverse chronological order. -func (els eventLogs) Len() int { return len(els) } -func (els eventLogs) Less(i, j int) bool { return els[i].Start.After(els[j].Start) } -func (els eventLogs) Swap(i, j int) { els[i], els[j] = els[j], els[i] } - -// A logEntry is a timestamped log entry in an event log. -type logEntry struct { - When time.Time - Elapsed time.Duration // since previous event in log - NewDay bool // whether this event is on a different day to the previous event - What string - IsErr bool -} - -// WhenString returns a string representation of the elapsed time of the event. -// It will include the date if midnight was crossed. -func (e logEntry) WhenString() string { - if e.NewDay { - return e.When.Format("2006/01/02 15:04:05.000000") - } - return e.When.Format("15:04:05.000000") -} - -// An eventLog represents an active event log. -type eventLog struct { - // Family is the top-level grouping of event logs to which this belongs. - Family string - - // Title is the title of this event log. - Title string - - // Timing information. - Start time.Time - - // Call stack where this event log was created. - stack []uintptr - - // Append-only sequence of events. - // - // TODO(sameer): change this to a ring buffer to avoid the array copy - // when we hit maxEventsPerLog. - mu sync.RWMutex - events []logEntry - LastErrorTime time.Time - discarded int - - refs int32 // how many buckets this is in -} - -func (el *eventLog) reset() { - // Clear all but the mutex. Mutexes may not be copied, even when unlocked. - el.Family = "" - el.Title = "" - el.Start = time.Time{} - el.stack = nil - el.events = nil - el.LastErrorTime = time.Time{} - el.discarded = 0 - el.refs = 0 -} - -func (el *eventLog) hasRecentError(now time.Time, maxErrAge time.Duration) bool { - if maxErrAge == 0 { - return true - } - el.mu.RLock() - defer el.mu.RUnlock() - return now.Sub(el.LastErrorTime) < maxErrAge -} - -// delta returns the elapsed time since the last event or the log start, -// and whether it spans midnight. -// L >= el.mu -func (el *eventLog) delta(t time.Time) (time.Duration, bool) { - if len(el.events) == 0 { - return t.Sub(el.Start), false - } - prev := el.events[len(el.events)-1].When - return t.Sub(prev), prev.Day() != t.Day() - -} - -func (el *eventLog) Printf(format string, a ...interface{}) { - el.printf(false, format, a...) -} - -func (el *eventLog) Errorf(format string, a ...interface{}) { - el.printf(true, format, a...) -} - -func (el *eventLog) printf(isErr bool, format string, a ...interface{}) { - e := logEntry{When: time.Now(), IsErr: isErr, What: fmt.Sprintf(format, a...)} - el.mu.Lock() - e.Elapsed, e.NewDay = el.delta(e.When) - if len(el.events) < maxEventsPerLog { - el.events = append(el.events, e) - } else { - // Discard the oldest event. - if el.discarded == 0 { - // el.discarded starts at two to count for the event it - // is replacing, plus the next one that we are about to - // drop. - el.discarded = 2 - } else { - el.discarded++ - } - // TODO(sameer): if this causes allocations on a critical path, - // change eventLog.What to be a fmt.Stringer, as in trace.go. - el.events[0].What = fmt.Sprintf("(%d events discarded)", el.discarded) - // The timestamp of the discarded meta-event should be - // the time of the last event it is representing. - el.events[0].When = el.events[1].When - copy(el.events[1:], el.events[2:]) - el.events[maxEventsPerLog-1] = e - } - if e.IsErr { - el.LastErrorTime = e.When - } - el.mu.Unlock() -} - -func (el *eventLog) ref() { - atomic.AddInt32(&el.refs, 1) -} - -func (el *eventLog) unref() { - if atomic.AddInt32(&el.refs, -1) == 0 { - freeEventLog(el) - } -} - -func (el *eventLog) When() string { - return el.Start.Format("2006/01/02 15:04:05.000000") -} - -func (el *eventLog) ElapsedTime() string { - elapsed := time.Since(el.Start) - return fmt.Sprintf("%.6f", elapsed.Seconds()) -} - -func (el *eventLog) Stack() string { - buf := new(bytes.Buffer) - tw := tabwriter.NewWriter(buf, 1, 8, 1, '\t', 0) - printStackRecord(tw, el.stack) - tw.Flush() - return buf.String() -} - -// printStackRecord prints the function + source line information -// for a single stack trace. -// Adapted from runtime/pprof/pprof.go. -func printStackRecord(w io.Writer, stk []uintptr) { - for _, pc := range stk { - f := runtime.FuncForPC(pc) - if f == nil { - continue - } - file, line := f.FileLine(pc) - name := f.Name() - // Hide runtime.goexit and any runtime functions at the beginning. - if strings.HasPrefix(name, "runtime.") { - continue - } - fmt.Fprintf(w, "# %s\t%s:%d\n", name, file, line) - } -} - -func (el *eventLog) Events() []logEntry { - el.mu.RLock() - defer el.mu.RUnlock() - return el.events -} - -// freeEventLogs is a freelist of *eventLog -var freeEventLogs = make(chan *eventLog, 1000) - -// newEventLog returns a event log ready to use. -func newEventLog() *eventLog { - select { - case el := <-freeEventLogs: - return el - default: - return new(eventLog) - } -} - -// freeEventLog adds el to freeEventLogs if there's room. -// This is non-blocking. -func freeEventLog(el *eventLog) { - el.reset() - select { - case freeEventLogs <- el: - default: - } -} - -var eventsTmplCache *template.Template -var eventsTmplOnce sync.Once - -func eventsTmpl() *template.Template { - eventsTmplOnce.Do(func() { - eventsTmplCache = template.Must(template.New("events").Funcs(template.FuncMap{ - "elapsed": elapsed, - "trimSpace": strings.TrimSpace, - }).Parse(eventsHTML)) - }) - return eventsTmplCache -} - -const eventsHTML = ` - - - events - - - - -

/debug/events

- - - {{range $i, $fam := .Families}} - - - - {{range $j, $bucket := $.Buckets}} - {{$n := index $.Counts $i $j}} - - {{end}} - - {{end}} -
{{$fam}} - {{if $n}}{{end}} - [{{$n}} {{$bucket.String}}] - {{if $n}}{{end}} -
- -{{if $.EventLogs}} -
-

Family: {{$.Family}}

- -{{if $.Expanded}}{{end}} -[Summary]{{if $.Expanded}}{{end}} - -{{if not $.Expanded}}{{end}} -[Expanded]{{if not $.Expanded}}{{end}} - - - - {{range $el := $.EventLogs}} - - - - - {{if $.Expanded}} - - - - - - {{range $el.Events}} - - - - - - {{end}} - {{end}} - {{end}} -
WhenElapsed
{{$el.When}}{{$el.ElapsedTime}}{{$el.Title}} -
{{$el.Stack|trimSpace}}
{{.WhenString}}{{elapsed .Elapsed}}.{{if .IsErr}}E{{else}}.{{end}}. {{.What}}
-{{end}} - - -` diff --git a/examples/golang.org/x/net/trace/histogram.go b/examples/golang.org/x/net/trace/histogram.go deleted file mode 100644 index 9bf4286..0000000 --- a/examples/golang.org/x/net/trace/histogram.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -// This file implements histogramming for RPC statistics collection. - -import ( - "bytes" - "fmt" - "html/template" - "log" - "math" - "sync" - - "golang.org/x/net/internal/timeseries" -) - -const ( - bucketCount = 38 -) - -// histogram keeps counts of values in buckets that are spaced -// out in powers of 2: 0-1, 2-3, 4-7... -// histogram implements timeseries.Observable -type histogram struct { - sum int64 // running total of measurements - sumOfSquares float64 // square of running total - buckets []int64 // bucketed values for histogram - value int // holds a single value as an optimization - valueCount int64 // number of values recorded for single value -} - -// AddMeasurement records a value measurement observation to the histogram. -func (h *histogram) addMeasurement(value int64) { - // TODO: assert invariant - h.sum += value - h.sumOfSquares += float64(value) * float64(value) - - bucketIndex := getBucket(value) - - if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) { - h.value = bucketIndex - h.valueCount++ - } else { - h.allocateBuckets() - h.buckets[bucketIndex]++ - } -} - -func (h *histogram) allocateBuckets() { - if h.buckets == nil { - h.buckets = make([]int64, bucketCount) - h.buckets[h.value] = h.valueCount - h.value = 0 - h.valueCount = -1 - } -} - -func log2(i int64) int { - n := 0 - for ; i >= 0x100; i >>= 8 { - n += 8 - } - for ; i > 0; i >>= 1 { - n += 1 - } - return n -} - -func getBucket(i int64) (index int) { - index = log2(i) - 1 - if index < 0 { - index = 0 - } - if index >= bucketCount { - index = bucketCount - 1 - } - return -} - -// Total returns the number of recorded observations. -func (h *histogram) total() (total int64) { - if h.valueCount >= 0 { - total = h.valueCount - } - for _, val := range h.buckets { - total += int64(val) - } - return -} - -// Average returns the average value of recorded observations. -func (h *histogram) average() float64 { - t := h.total() - if t == 0 { - return 0 - } - return float64(h.sum) / float64(t) -} - -// Variance returns the variance of recorded observations. -func (h *histogram) variance() float64 { - t := float64(h.total()) - if t == 0 { - return 0 - } - s := float64(h.sum) / t - return h.sumOfSquares/t - s*s -} - -// StandardDeviation returns the standard deviation of recorded observations. -func (h *histogram) standardDeviation() float64 { - return math.Sqrt(h.variance()) -} - -// PercentileBoundary estimates the value that the given fraction of recorded -// observations are less than. -func (h *histogram) percentileBoundary(percentile float64) int64 { - total := h.total() - - // Corner cases (make sure result is strictly less than Total()) - if total == 0 { - return 0 - } else if total == 1 { - return int64(h.average()) - } - - percentOfTotal := round(float64(total) * percentile) - var runningTotal int64 - - for i := range h.buckets { - value := h.buckets[i] - runningTotal += value - if runningTotal == percentOfTotal { - // We hit an exact bucket boundary. If the next bucket has data, it is a - // good estimate of the value. If the bucket is empty, we interpolate the - // midpoint between the next bucket's boundary and the next non-zero - // bucket. If the remaining buckets are all empty, then we use the - // boundary for the next bucket as the estimate. - j := uint8(i + 1) - min := bucketBoundary(j) - if runningTotal < total { - for h.buckets[j] == 0 { - j++ - } - } - max := bucketBoundary(j) - return min + round(float64(max-min)/2) - } else if runningTotal > percentOfTotal { - // The value is in this bucket. Interpolate the value. - delta := runningTotal - percentOfTotal - percentBucket := float64(value-delta) / float64(value) - bucketMin := bucketBoundary(uint8(i)) - nextBucketMin := bucketBoundary(uint8(i + 1)) - bucketSize := nextBucketMin - bucketMin - return bucketMin + round(percentBucket*float64(bucketSize)) - } - } - return bucketBoundary(bucketCount - 1) -} - -// Median returns the estimated median of the observed values. -func (h *histogram) median() int64 { - return h.percentileBoundary(0.5) -} - -// Add adds other to h. -func (h *histogram) Add(other timeseries.Observable) { - o := other.(*histogram) - if o.valueCount == 0 { - // Other histogram is empty - } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value { - // Both have a single bucketed value, aggregate them - h.valueCount += o.valueCount - } else { - // Two different values necessitate buckets in this histogram - h.allocateBuckets() - if o.valueCount >= 0 { - h.buckets[o.value] += o.valueCount - } else { - for i := range h.buckets { - h.buckets[i] += o.buckets[i] - } - } - } - h.sumOfSquares += o.sumOfSquares - h.sum += o.sum -} - -// Clear resets the histogram to an empty state, removing all observed values. -func (h *histogram) Clear() { - h.buckets = nil - h.value = 0 - h.valueCount = 0 - h.sum = 0 - h.sumOfSquares = 0 -} - -// CopyFrom copies from other, which must be a *histogram, into h. -func (h *histogram) CopyFrom(other timeseries.Observable) { - o := other.(*histogram) - if o.valueCount == -1 { - h.allocateBuckets() - copy(h.buckets, o.buckets) - } - h.sum = o.sum - h.sumOfSquares = o.sumOfSquares - h.value = o.value - h.valueCount = o.valueCount -} - -// Multiply scales the histogram by the specified ratio. -func (h *histogram) Multiply(ratio float64) { - if h.valueCount == -1 { - for i := range h.buckets { - h.buckets[i] = int64(float64(h.buckets[i]) * ratio) - } - } else { - h.valueCount = int64(float64(h.valueCount) * ratio) - } - h.sum = int64(float64(h.sum) * ratio) - h.sumOfSquares = h.sumOfSquares * ratio -} - -// New creates a new histogram. -func (h *histogram) New() timeseries.Observable { - r := new(histogram) - r.Clear() - return r -} - -func (h *histogram) String() string { - return fmt.Sprintf("%d, %f, %d, %d, %v", - h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets) -} - -// round returns the closest int64 to the argument -func round(in float64) int64 { - return int64(math.Floor(in + 0.5)) -} - -// bucketBoundary returns the first value in the bucket. -func bucketBoundary(bucket uint8) int64 { - if bucket == 0 { - return 0 - } - return 1 << bucket -} - -// bucketData holds data about a specific bucket for use in distTmpl. -type bucketData struct { - Lower, Upper int64 - N int64 - Pct, CumulativePct float64 - GraphWidth int -} - -// data holds data about a Distribution for use in distTmpl. -type data struct { - Buckets []*bucketData - Count, Median int64 - Mean, StandardDeviation float64 -} - -// maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets. -const maxHTMLBarWidth = 350.0 - -// newData returns data representing h for use in distTmpl. -func (h *histogram) newData() *data { - // Force the allocation of buckets to simplify the rendering implementation - h.allocateBuckets() - // We scale the bars on the right so that the largest bar is - // maxHTMLBarWidth pixels in width. - maxBucket := int64(0) - for _, n := range h.buckets { - if n > maxBucket { - maxBucket = n - } - } - total := h.total() - barsizeMult := maxHTMLBarWidth / float64(maxBucket) - var pctMult float64 - if total == 0 { - pctMult = 1.0 - } else { - pctMult = 100.0 / float64(total) - } - - buckets := make([]*bucketData, len(h.buckets)) - runningTotal := int64(0) - for i, n := range h.buckets { - if n == 0 { - continue - } - runningTotal += n - var upperBound int64 - if i < bucketCount-1 { - upperBound = bucketBoundary(uint8(i + 1)) - } else { - upperBound = math.MaxInt64 - } - buckets[i] = &bucketData{ - Lower: bucketBoundary(uint8(i)), - Upper: upperBound, - N: n, - Pct: float64(n) * pctMult, - CumulativePct: float64(runningTotal) * pctMult, - GraphWidth: int(float64(n) * barsizeMult), - } - } - return &data{ - Buckets: buckets, - Count: total, - Median: h.median(), - Mean: h.average(), - StandardDeviation: h.standardDeviation(), - } -} - -func (h *histogram) html() template.HTML { - buf := new(bytes.Buffer) - if err := distTmpl().Execute(buf, h.newData()); err != nil { - buf.Reset() - log.Printf("net/trace: couldn't execute template: %v", err) - } - return template.HTML(buf.String()) -} - -var distTmplCache *template.Template -var distTmplOnce sync.Once - -func distTmpl() *template.Template { - distTmplOnce.Do(func() { - // Input: data - distTmplCache = template.Must(template.New("distTmpl").Parse(` - - - - - - - -
Count: {{.Count}}Mean: {{printf "%.0f" .Mean}}StdDev: {{printf "%.0f" .StandardDeviation}}Median: {{.Median}}
-
- -{{range $b := .Buckets}} -{{if $b}} - - - - - - - - - -{{end}} -{{end}} -
[{{.Lower}},{{.Upper}}){{.N}}{{printf "%#.3f" .Pct}}%{{printf "%#.3f" .CumulativePct}}%
-`)) - }) - return distTmplCache -} diff --git a/examples/golang.org/x/net/trace/histogram_test.go b/examples/golang.org/x/net/trace/histogram_test.go deleted file mode 100644 index d384b93..0000000 --- a/examples/golang.org/x/net/trace/histogram_test.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -import ( - "math" - "testing" -) - -type sumTest struct { - value int64 - sum int64 - sumOfSquares float64 - total int64 -} - -var sumTests = []sumTest{ - {100, 100, 10000, 1}, - {50, 150, 12500, 2}, - {50, 200, 15000, 3}, - {50, 250, 17500, 4}, -} - -type bucketingTest struct { - in int64 - log int - bucket int -} - -var bucketingTests = []bucketingTest{ - {0, 0, 0}, - {1, 1, 0}, - {2, 2, 1}, - {3, 2, 1}, - {4, 3, 2}, - {1000, 10, 9}, - {1023, 10, 9}, - {1024, 11, 10}, - {1000000, 20, 19}, -} - -type multiplyTest struct { - in int64 - ratio float64 - expectedSum int64 - expectedTotal int64 - expectedSumOfSquares float64 -} - -var multiplyTests = []multiplyTest{ - {15, 2.5, 37, 2, 562.5}, - {128, 4.6, 758, 13, 77953.9}, -} - -type percentileTest struct { - fraction float64 - expected int64 -} - -var percentileTests = []percentileTest{ - {0.25, 48}, - {0.5, 96}, - {0.6, 109}, - {0.75, 128}, - {0.90, 205}, - {0.95, 230}, - {0.99, 256}, -} - -func TestSum(t *testing.T) { - var h histogram - - for _, test := range sumTests { - h.addMeasurement(test.value) - sum := h.sum - if sum != test.sum { - t.Errorf("h.Sum = %v WANT: %v", sum, test.sum) - } - - sumOfSquares := h.sumOfSquares - if sumOfSquares != test.sumOfSquares { - t.Errorf("h.SumOfSquares = %v WANT: %v", sumOfSquares, test.sumOfSquares) - } - - total := h.total() - if total != test.total { - t.Errorf("h.Total = %v WANT: %v", total, test.total) - } - } -} - -func TestMultiply(t *testing.T) { - var h histogram - for i, test := range multiplyTests { - h.addMeasurement(test.in) - h.Multiply(test.ratio) - if h.sum != test.expectedSum { - t.Errorf("#%v: h.sum = %v WANT: %v", i, h.sum, test.expectedSum) - } - if h.total() != test.expectedTotal { - t.Errorf("#%v: h.total = %v WANT: %v", i, h.total(), test.expectedTotal) - } - if h.sumOfSquares != test.expectedSumOfSquares { - t.Errorf("#%v: h.SumOfSquares = %v WANT: %v", i, test.expectedSumOfSquares, h.sumOfSquares) - } - } -} - -func TestBucketingFunctions(t *testing.T) { - for _, test := range bucketingTests { - log := log2(test.in) - if log != test.log { - t.Errorf("log2 = %v WANT: %v", log, test.log) - } - - bucket := getBucket(test.in) - if bucket != test.bucket { - t.Errorf("getBucket = %v WANT: %v", bucket, test.bucket) - } - } -} - -func TestAverage(t *testing.T) { - a := new(histogram) - average := a.average() - if average != 0 { - t.Errorf("Average of empty histogram was %v WANT: 0", average) - } - - a.addMeasurement(1) - a.addMeasurement(1) - a.addMeasurement(3) - const expected = float64(5) / float64(3) - average = a.average() - - if !isApproximate(average, expected) { - t.Errorf("Average = %g WANT: %v", average, expected) - } -} - -func TestStandardDeviation(t *testing.T) { - a := new(histogram) - add(a, 10, 1<<4) - add(a, 10, 1<<5) - add(a, 10, 1<<6) - stdDev := a.standardDeviation() - const expected = 19.95 - - if !isApproximate(stdDev, expected) { - t.Errorf("StandardDeviation = %v WANT: %v", stdDev, expected) - } - - // No values - a = new(histogram) - stdDev = a.standardDeviation() - - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } - - add(a, 1, 1<<4) - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } - - add(a, 10, 1<<4) - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } -} - -func TestPercentileBoundary(t *testing.T) { - a := new(histogram) - add(a, 5, 1<<4) - add(a, 10, 1<<6) - add(a, 5, 1<<7) - - for _, test := range percentileTests { - percentile := a.percentileBoundary(test.fraction) - if percentile != test.expected { - t.Errorf("h.PercentileBoundary (fraction=%v) = %v WANT: %v", test.fraction, percentile, test.expected) - } - } -} - -func TestCopyFrom(t *testing.T) { - a := histogram{5, 25, []int64{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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} - b := histogram{6, 36, []int64{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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39}, 5, -1} - - a.CopyFrom(&b) - - if a.String() != b.String() { - t.Errorf("a.String = %s WANT: %s", a.String(), b.String()) - } -} - -func TestClear(t *testing.T) { - a := histogram{5, 25, []int64{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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} - - a.Clear() - - expected := "0, 0.000000, 0, 0, []" - if a.String() != expected { - t.Errorf("a.String = %s WANT %s", a.String(), expected) - } -} - -func TestNew(t *testing.T) { - a := histogram{5, 25, []int64{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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} - b := a.New() - - expected := "0, 0.000000, 0, 0, []" - if b.(*histogram).String() != expected { - t.Errorf("b.(*histogram).String = %s WANT: %s", b.(*histogram).String(), expected) - } -} - -func TestAdd(t *testing.T) { - // The tests here depend on the associativity of addMeasurement and Add. - // Add empty observation - a := histogram{5, 25, []int64{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, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38}, 4, -1} - b := a.New() - - expected := a.String() - a.Add(b) - if a.String() != expected { - t.Errorf("a.String = %s WANT: %s", a.String(), expected) - } - - // Add same bucketed value, no new buckets - c := new(histogram) - d := new(histogram) - e := new(histogram) - c.addMeasurement(12) - d.addMeasurement(11) - e.addMeasurement(12) - e.addMeasurement(11) - c.Add(d) - if c.String() != e.String() { - t.Errorf("c.String = %s WANT: %s", c.String(), e.String()) - } - - // Add bucketed values - f := new(histogram) - g := new(histogram) - h := new(histogram) - f.addMeasurement(4) - f.addMeasurement(12) - f.addMeasurement(100) - g.addMeasurement(18) - g.addMeasurement(36) - g.addMeasurement(255) - h.addMeasurement(4) - h.addMeasurement(12) - h.addMeasurement(100) - h.addMeasurement(18) - h.addMeasurement(36) - h.addMeasurement(255) - f.Add(g) - if f.String() != h.String() { - t.Errorf("f.String = %q WANT: %q", f.String(), h.String()) - } - - // add buckets to no buckets - i := new(histogram) - j := new(histogram) - k := new(histogram) - j.addMeasurement(18) - j.addMeasurement(36) - j.addMeasurement(255) - k.addMeasurement(18) - k.addMeasurement(36) - k.addMeasurement(255) - i.Add(j) - if i.String() != k.String() { - t.Errorf("i.String = %q WANT: %q", i.String(), k.String()) - } - - // add buckets to single value (no overlap) - l := new(histogram) - m := new(histogram) - n := new(histogram) - l.addMeasurement(0) - m.addMeasurement(18) - m.addMeasurement(36) - m.addMeasurement(255) - n.addMeasurement(0) - n.addMeasurement(18) - n.addMeasurement(36) - n.addMeasurement(255) - l.Add(m) - if l.String() != n.String() { - t.Errorf("l.String = %q WANT: %q", l.String(), n.String()) - } - - // mixed order - o := new(histogram) - p := new(histogram) - o.addMeasurement(0) - o.addMeasurement(2) - o.addMeasurement(0) - p.addMeasurement(0) - p.addMeasurement(0) - p.addMeasurement(2) - if o.String() != p.String() { - t.Errorf("o.String = %q WANT: %q", o.String(), p.String()) - } -} - -func add(h *histogram, times int, val int64) { - for i := 0; i < times; i++ { - h.addMeasurement(val) - } -} - -func isApproximate(x, y float64) bool { - return math.Abs(x-y) < 1e-2 -} diff --git a/examples/golang.org/x/net/trace/trace.go b/examples/golang.org/x/net/trace/trace.go deleted file mode 100644 index a46ee0e..0000000 --- a/examples/golang.org/x/net/trace/trace.go +++ /dev/null @@ -1,1103 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package trace implements tracing of requests and long-lived objects. -It exports HTTP interfaces on /debug/requests and /debug/events. - -A trace.Trace provides tracing for short-lived objects, usually requests. -A request handler might be implemented like this: - - func fooHandler(w http.ResponseWriter, req *http.Request) { - tr := trace.New("mypkg.Foo", req.URL.Path) - defer tr.Finish() - ... - tr.LazyPrintf("some event %q happened", str) - ... - if err := somethingImportant(); err != nil { - tr.LazyPrintf("somethingImportant failed: %v", err) - tr.SetError() - } - } - -The /debug/requests HTTP endpoint organizes the traces by family, -errors, and duration. It also provides histogram of request duration -for each family. - -A trace.EventLog provides tracing for long-lived objects, such as RPC -connections. - - // A Fetcher fetches URL paths for a single domain. - type Fetcher struct { - domain string - events trace.EventLog - } - - func NewFetcher(domain string) *Fetcher { - return &Fetcher{ - domain, - trace.NewEventLog("mypkg.Fetcher", domain), - } - } - - func (f *Fetcher) Fetch(path string) (string, error) { - resp, err := http.Get("http://" + f.domain + "/" + path) - if err != nil { - f.events.Errorf("Get(%q) = %v", path, err) - return "", err - } - f.events.Printf("Get(%q) = %s", path, resp.Status) - ... - } - - func (f *Fetcher) Close() error { - f.events.Finish() - return nil - } - -The /debug/events HTTP endpoint organizes the event logs by family and -by time since the last error. The expanded view displays recent log -entries and the log's call stack. -*/ -package trace // import "golang.org/x/net/trace" - -import ( - "bytes" - "fmt" - "html/template" - "io" - "log" - "net" - "net/http" - "runtime" - "sort" - "strconv" - "sync" - "sync/atomic" - "time" - - "golang.org/x/net/internal/timeseries" -) - -// DebugUseAfterFinish controls whether to debug uses of Trace values after finishing. -// FOR DEBUGGING ONLY. This will slow down the program. -var DebugUseAfterFinish = false - -// AuthRequest determines whether a specific request is permitted to load the -// /debug/requests or /debug/events pages. -// -// It returns two bools; the first indicates whether the page may be viewed at all, -// and the second indicates whether sensitive events will be shown. -// -// AuthRequest may be replaced by a program to customize its authorization requirements. -// -// The default AuthRequest function returns (true, true) if and only if the request -// comes from localhost/127.0.0.1/[::1]. -var AuthRequest = func(req *http.Request) (any, sensitive bool) { - // RemoteAddr is commonly in the form "IP" or "IP:port". - // If it is in the form "IP:port", split off the port. - host, _, err := net.SplitHostPort(req.RemoteAddr) - if err != nil { - host = req.RemoteAddr - } - switch host { - case "localhost", "127.0.0.1", "::1": - return true, true - default: - return false, false - } -} - -func init() { - // TODO(jbd): Serve Traces from /debug/traces in the future? - // There is no requirement for a request to be present to have traces. - http.HandleFunc("/debug/requests", Traces) - http.HandleFunc("/debug/events", Events) -} - -// Traces responds with traces from the program. -// The package initialization registers it in http.DefaultServeMux -// at /debug/requests. -// -// It performs authorization by running AuthRequest. -func Traces(w http.ResponseWriter, req *http.Request) { - any, sensitive := AuthRequest(req) - if !any { - http.Error(w, "not allowed", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - Render(w, req, sensitive) -} - -// Events responds with a page of events collected by EventLogs. -// The package initialization registers it in http.DefaultServeMux -// at /debug/events. -// -// It performs authorization by running AuthRequest. -func Events(w http.ResponseWriter, req *http.Request) { - any, sensitive := AuthRequest(req) - if !any { - http.Error(w, "not allowed", http.StatusUnauthorized) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - RenderEvents(w, req, sensitive) -} - -// Render renders the HTML page typically served at /debug/requests. -// It does not do any auth checking. The request may be nil. -// -// Most users will use the Traces handler. -func Render(w io.Writer, req *http.Request, sensitive bool) { - data := &struct { - Families []string - ActiveTraceCount map[string]int - CompletedTraces map[string]*family - - // Set when a bucket has been selected. - Traces traceList - Family string - Bucket int - Expanded bool - Traced bool - Active bool - ShowSensitive bool // whether to show sensitive events - - Histogram template.HTML - HistogramWindow string // e.g. "last minute", "last hour", "all time" - - // If non-zero, the set of traces is a partial set, - // and this is the total number. - Total int - }{ - CompletedTraces: completedTraces, - } - - data.ShowSensitive = sensitive - if req != nil { - // Allow show_sensitive=0 to force hiding of sensitive data for testing. - // This only goes one way; you can't use show_sensitive=1 to see things. - if req.FormValue("show_sensitive") == "0" { - data.ShowSensitive = false - } - - if exp, err := strconv.ParseBool(req.FormValue("exp")); err == nil { - data.Expanded = exp - } - if exp, err := strconv.ParseBool(req.FormValue("rtraced")); err == nil { - data.Traced = exp - } - } - - completedMu.RLock() - data.Families = make([]string, 0, len(completedTraces)) - for fam := range completedTraces { - data.Families = append(data.Families, fam) - } - completedMu.RUnlock() - sort.Strings(data.Families) - - // We are careful here to minimize the time spent locking activeMu, - // since that lock is required every time an RPC starts and finishes. - data.ActiveTraceCount = make(map[string]int, len(data.Families)) - activeMu.RLock() - for fam, s := range activeTraces { - data.ActiveTraceCount[fam] = s.Len() - } - activeMu.RUnlock() - - var ok bool - data.Family, data.Bucket, ok = parseArgs(req) - switch { - case !ok: - // No-op - case data.Bucket == -1: - data.Active = true - n := data.ActiveTraceCount[data.Family] - data.Traces = getActiveTraces(data.Family) - if len(data.Traces) < n { - data.Total = n - } - case data.Bucket < bucketsPerFamily: - if b := lookupBucket(data.Family, data.Bucket); b != nil { - data.Traces = b.Copy(data.Traced) - } - default: - if f := getFamily(data.Family, false); f != nil { - var obs timeseries.Observable - f.LatencyMu.RLock() - switch o := data.Bucket - bucketsPerFamily; o { - case 0: - obs = f.Latency.Minute() - data.HistogramWindow = "last minute" - case 1: - obs = f.Latency.Hour() - data.HistogramWindow = "last hour" - case 2: - obs = f.Latency.Total() - data.HistogramWindow = "all time" - } - f.LatencyMu.RUnlock() - if obs != nil { - data.Histogram = obs.(*histogram).html() - } - } - } - - if data.Traces != nil { - defer data.Traces.Free() - sort.Sort(data.Traces) - } - - completedMu.RLock() - defer completedMu.RUnlock() - if err := pageTmpl().ExecuteTemplate(w, "Page", data); err != nil { - log.Printf("net/trace: Failed executing template: %v", err) - } -} - -func parseArgs(req *http.Request) (fam string, b int, ok bool) { - if req == nil { - return "", 0, false - } - fam, bStr := req.FormValue("fam"), req.FormValue("b") - if fam == "" || bStr == "" { - return "", 0, false - } - b, err := strconv.Atoi(bStr) - if err != nil || b < -1 { - return "", 0, false - } - - return fam, b, true -} - -func lookupBucket(fam string, b int) *traceBucket { - f := getFamily(fam, false) - if f == nil || b < 0 || b >= len(f.Buckets) { - return nil - } - return f.Buckets[b] -} - -type contextKeyT string - -var contextKey = contextKeyT("golang.org/x/net/trace.Trace") - -// Trace represents an active request. -type Trace interface { - // LazyLog adds x to the event log. It will be evaluated each time the - // /debug/requests page is rendered. Any memory referenced by x will be - // pinned until the trace is finished and later discarded. - LazyLog(x fmt.Stringer, sensitive bool) - - // LazyPrintf evaluates its arguments with fmt.Sprintf each time the - // /debug/requests page is rendered. Any memory referenced by a will be - // pinned until the trace is finished and later discarded. - LazyPrintf(format string, a ...interface{}) - - // SetError declares that this trace resulted in an error. - SetError() - - // SetRecycler sets a recycler for the trace. - // f will be called for each event passed to LazyLog at a time when - // it is no longer required, whether while the trace is still active - // and the event is discarded, or when a completed trace is discarded. - SetRecycler(f func(interface{})) - - // SetTraceInfo sets the trace info for the trace. - // This is currently unused. - SetTraceInfo(traceID, spanID uint64) - - // SetMaxEvents sets the maximum number of events that will be stored - // in the trace. This has no effect if any events have already been - // added to the trace. - SetMaxEvents(m int) - - // Finish declares that this trace is complete. - // The trace should not be used after calling this method. - Finish() -} - -type lazySprintf struct { - format string - a []interface{} -} - -func (l *lazySprintf) String() string { - return fmt.Sprintf(l.format, l.a...) -} - -// New returns a new Trace with the specified family and title. -func New(family, title string) Trace { - tr := newTrace() - tr.ref() - tr.Family, tr.Title = family, title - tr.Start = time.Now() - tr.maxEvents = maxEventsPerTrace - tr.events = tr.eventsBuf[:0] - - activeMu.RLock() - s := activeTraces[tr.Family] - activeMu.RUnlock() - if s == nil { - activeMu.Lock() - s = activeTraces[tr.Family] // check again - if s == nil { - s = new(traceSet) - activeTraces[tr.Family] = s - } - activeMu.Unlock() - } - s.Add(tr) - - // Trigger allocation of the completed trace structure for this family. - // This will cause the family to be present in the request page during - // the first trace of this family. We don't care about the return value, - // nor is there any need for this to run inline, so we execute it in its - // own goroutine, but only if the family isn't allocated yet. - completedMu.RLock() - if _, ok := completedTraces[tr.Family]; !ok { - go allocFamily(tr.Family) - } - completedMu.RUnlock() - - return tr -} - -func (tr *trace) Finish() { - elapsed := time.Now().Sub(tr.Start) - tr.mu.Lock() - tr.Elapsed = elapsed - tr.mu.Unlock() - - if DebugUseAfterFinish { - buf := make([]byte, 4<<10) // 4 KB should be enough - n := runtime.Stack(buf, false) - tr.finishStack = buf[:n] - } - - activeMu.RLock() - m := activeTraces[tr.Family] - activeMu.RUnlock() - m.Remove(tr) - - f := getFamily(tr.Family, true) - tr.mu.RLock() // protects tr fields in Cond.match calls - for _, b := range f.Buckets { - if b.Cond.match(tr) { - b.Add(tr) - } - } - tr.mu.RUnlock() - - // Add a sample of elapsed time as microseconds to the family's timeseries - h := new(histogram) - h.addMeasurement(elapsed.Nanoseconds() / 1e3) - f.LatencyMu.Lock() - f.Latency.Add(h) - f.LatencyMu.Unlock() - - tr.unref() // matches ref in New -} - -const ( - bucketsPerFamily = 9 - tracesPerBucket = 10 - maxActiveTraces = 20 // Maximum number of active traces to show. - maxEventsPerTrace = 10 - numHistogramBuckets = 38 -) - -var ( - // The active traces. - activeMu sync.RWMutex - activeTraces = make(map[string]*traceSet) // family -> traces - - // Families of completed traces. - completedMu sync.RWMutex - completedTraces = make(map[string]*family) // family -> traces -) - -type traceSet struct { - mu sync.RWMutex - m map[*trace]bool - - // We could avoid the entire map scan in FirstN by having a slice of all the traces - // ordered by start time, and an index into that from the trace struct, with a periodic - // repack of the slice after enough traces finish; we could also use a skip list or similar. - // However, that would shift some of the expense from /debug/requests time to RPC time, - // which is probably the wrong trade-off. -} - -func (ts *traceSet) Len() int { - ts.mu.RLock() - defer ts.mu.RUnlock() - return len(ts.m) -} - -func (ts *traceSet) Add(tr *trace) { - ts.mu.Lock() - if ts.m == nil { - ts.m = make(map[*trace]bool) - } - ts.m[tr] = true - ts.mu.Unlock() -} - -func (ts *traceSet) Remove(tr *trace) { - ts.mu.Lock() - delete(ts.m, tr) - ts.mu.Unlock() -} - -// FirstN returns the first n traces ordered by time. -func (ts *traceSet) FirstN(n int) traceList { - ts.mu.RLock() - defer ts.mu.RUnlock() - - if n > len(ts.m) { - n = len(ts.m) - } - trl := make(traceList, 0, n) - - // Fast path for when no selectivity is needed. - if n == len(ts.m) { - for tr := range ts.m { - tr.ref() - trl = append(trl, tr) - } - sort.Sort(trl) - return trl - } - - // Pick the oldest n traces. - // This is inefficient. See the comment in the traceSet struct. - for tr := range ts.m { - // Put the first n traces into trl in the order they occur. - // When we have n, sort trl, and thereafter maintain its order. - if len(trl) < n { - tr.ref() - trl = append(trl, tr) - if len(trl) == n { - // This is guaranteed to happen exactly once during this loop. - sort.Sort(trl) - } - continue - } - if tr.Start.After(trl[n-1].Start) { - continue - } - - // Find where to insert this one. - tr.ref() - i := sort.Search(n, func(i int) bool { return trl[i].Start.After(tr.Start) }) - trl[n-1].unref() - copy(trl[i+1:], trl[i:]) - trl[i] = tr - } - - return trl -} - -func getActiveTraces(fam string) traceList { - activeMu.RLock() - s := activeTraces[fam] - activeMu.RUnlock() - if s == nil { - return nil - } - return s.FirstN(maxActiveTraces) -} - -func getFamily(fam string, allocNew bool) *family { - completedMu.RLock() - f := completedTraces[fam] - completedMu.RUnlock() - if f == nil && allocNew { - f = allocFamily(fam) - } - return f -} - -func allocFamily(fam string) *family { - completedMu.Lock() - defer completedMu.Unlock() - f := completedTraces[fam] - if f == nil { - f = newFamily() - completedTraces[fam] = f - } - return f -} - -// family represents a set of trace buckets and associated latency information. -type family struct { - // traces may occur in multiple buckets. - Buckets [bucketsPerFamily]*traceBucket - - // latency time series - LatencyMu sync.RWMutex - Latency *timeseries.MinuteHourSeries -} - -func newFamily() *family { - return &family{ - Buckets: [bucketsPerFamily]*traceBucket{ - {Cond: minCond(0)}, - {Cond: minCond(50 * time.Millisecond)}, - {Cond: minCond(100 * time.Millisecond)}, - {Cond: minCond(200 * time.Millisecond)}, - {Cond: minCond(500 * time.Millisecond)}, - {Cond: minCond(1 * time.Second)}, - {Cond: minCond(10 * time.Second)}, - {Cond: minCond(100 * time.Second)}, - {Cond: errorCond{}}, - }, - Latency: timeseries.NewMinuteHourSeries(func() timeseries.Observable { return new(histogram) }), - } -} - -// traceBucket represents a size-capped bucket of historic traces, -// along with a condition for a trace to belong to the bucket. -type traceBucket struct { - Cond cond - - // Ring buffer implementation of a fixed-size FIFO queue. - mu sync.RWMutex - buf [tracesPerBucket]*trace - start int // < tracesPerBucket - length int // <= tracesPerBucket -} - -func (b *traceBucket) Add(tr *trace) { - b.mu.Lock() - defer b.mu.Unlock() - - i := b.start + b.length - if i >= tracesPerBucket { - i -= tracesPerBucket - } - if b.length == tracesPerBucket { - // "Remove" an element from the bucket. - b.buf[i].unref() - b.start++ - if b.start == tracesPerBucket { - b.start = 0 - } - } - b.buf[i] = tr - if b.length < tracesPerBucket { - b.length++ - } - tr.ref() -} - -// Copy returns a copy of the traces in the bucket. -// If tracedOnly is true, only the traces with trace information will be returned. -// The logs will be ref'd before returning; the caller should call -// the Free method when it is done with them. -// TODO(dsymonds): keep track of traced requests in separate buckets. -func (b *traceBucket) Copy(tracedOnly bool) traceList { - b.mu.RLock() - defer b.mu.RUnlock() - - trl := make(traceList, 0, b.length) - for i, x := 0, b.start; i < b.length; i++ { - tr := b.buf[x] - if !tracedOnly || tr.spanID != 0 { - tr.ref() - trl = append(trl, tr) - } - x++ - if x == b.length { - x = 0 - } - } - return trl -} - -func (b *traceBucket) Empty() bool { - b.mu.RLock() - defer b.mu.RUnlock() - return b.length == 0 -} - -// cond represents a condition on a trace. -type cond interface { - match(t *trace) bool - String() string -} - -type minCond time.Duration - -func (m minCond) match(t *trace) bool { return t.Elapsed >= time.Duration(m) } -func (m minCond) String() string { return fmt.Sprintf("≥%gs", time.Duration(m).Seconds()) } - -type errorCond struct{} - -func (e errorCond) match(t *trace) bool { return t.IsError } -func (e errorCond) String() string { return "errors" } - -type traceList []*trace - -// Free calls unref on each element of the list. -func (trl traceList) Free() { - for _, t := range trl { - t.unref() - } -} - -// traceList may be sorted in reverse chronological order. -func (trl traceList) Len() int { return len(trl) } -func (trl traceList) Less(i, j int) bool { return trl[i].Start.After(trl[j].Start) } -func (trl traceList) Swap(i, j int) { trl[i], trl[j] = trl[j], trl[i] } - -// An event is a timestamped log entry in a trace. -type event struct { - When time.Time - Elapsed time.Duration // since previous event in trace - NewDay bool // whether this event is on a different day to the previous event - Recyclable bool // whether this event was passed via LazyLog - Sensitive bool // whether this event contains sensitive information - What interface{} // string or fmt.Stringer -} - -// WhenString returns a string representation of the elapsed time of the event. -// It will include the date if midnight was crossed. -func (e event) WhenString() string { - if e.NewDay { - return e.When.Format("2006/01/02 15:04:05.000000") - } - return e.When.Format("15:04:05.000000") -} - -// discarded represents a number of discarded events. -// It is stored as *discarded to make it easier to update in-place. -type discarded int - -func (d *discarded) String() string { - return fmt.Sprintf("(%d events discarded)", int(*d)) -} - -// trace represents an active or complete request, -// either sent or received by this program. -type trace struct { - // Family is the top-level grouping of traces to which this belongs. - Family string - - // Title is the title of this trace. - Title string - - // Start time of the this trace. - Start time.Time - - mu sync.RWMutex - events []event // Append-only sequence of events (modulo discards). - maxEvents int - recycler func(interface{}) - IsError bool // Whether this trace resulted in an error. - Elapsed time.Duration // Elapsed time for this trace, zero while active. - traceID uint64 // Trace information if non-zero. - spanID uint64 - - refs int32 // how many buckets this is in - disc discarded // scratch space to avoid allocation - - finishStack []byte // where finish was called, if DebugUseAfterFinish is set - - eventsBuf [4]event // preallocated buffer in case we only log a few events -} - -func (tr *trace) reset() { - // Clear all but the mutex. Mutexes may not be copied, even when unlocked. - tr.Family = "" - tr.Title = "" - tr.Start = time.Time{} - - tr.mu.Lock() - tr.Elapsed = 0 - tr.traceID = 0 - tr.spanID = 0 - tr.IsError = false - tr.maxEvents = 0 - tr.events = nil - tr.recycler = nil - tr.mu.Unlock() - - tr.refs = 0 - tr.disc = 0 - tr.finishStack = nil - for i := range tr.eventsBuf { - tr.eventsBuf[i] = event{} - } -} - -// delta returns the elapsed time since the last event or the trace start, -// and whether it spans midnight. -// L >= tr.mu -func (tr *trace) delta(t time.Time) (time.Duration, bool) { - if len(tr.events) == 0 { - return t.Sub(tr.Start), false - } - prev := tr.events[len(tr.events)-1].When - return t.Sub(prev), prev.Day() != t.Day() -} - -func (tr *trace) addEvent(x interface{}, recyclable, sensitive bool) { - if DebugUseAfterFinish && tr.finishStack != nil { - buf := make([]byte, 4<<10) // 4 KB should be enough - n := runtime.Stack(buf, false) - log.Printf("net/trace: trace used after finish:\nFinished at:\n%s\nUsed at:\n%s", tr.finishStack, buf[:n]) - } - - /* - NOTE TO DEBUGGERS - - If you are here because your program panicked in this code, - it is almost definitely the fault of code using this package, - and very unlikely to be the fault of this code. - - The most likely scenario is that some code elsewhere is using - a trace.Trace after its Finish method is called. - You can temporarily set the DebugUseAfterFinish var - to help discover where that is; do not leave that var set, - since it makes this package much less efficient. - */ - - e := event{When: time.Now(), What: x, Recyclable: recyclable, Sensitive: sensitive} - tr.mu.Lock() - e.Elapsed, e.NewDay = tr.delta(e.When) - if len(tr.events) < tr.maxEvents { - tr.events = append(tr.events, e) - } else { - // Discard the middle events. - di := int((tr.maxEvents - 1) / 2) - if d, ok := tr.events[di].What.(*discarded); ok { - (*d)++ - } else { - // disc starts at two to count for the event it is replacing, - // plus the next one that we are about to drop. - tr.disc = 2 - if tr.recycler != nil && tr.events[di].Recyclable { - go tr.recycler(tr.events[di].What) - } - tr.events[di].What = &tr.disc - } - // The timestamp of the discarded meta-event should be - // the time of the last event it is representing. - tr.events[di].When = tr.events[di+1].When - - if tr.recycler != nil && tr.events[di+1].Recyclable { - go tr.recycler(tr.events[di+1].What) - } - copy(tr.events[di+1:], tr.events[di+2:]) - tr.events[tr.maxEvents-1] = e - } - tr.mu.Unlock() -} - -func (tr *trace) LazyLog(x fmt.Stringer, sensitive bool) { - tr.addEvent(x, true, sensitive) -} - -func (tr *trace) LazyPrintf(format string, a ...interface{}) { - tr.addEvent(&lazySprintf{format, a}, false, false) -} - -func (tr *trace) SetError() { - tr.mu.Lock() - tr.IsError = true - tr.mu.Unlock() -} - -func (tr *trace) SetRecycler(f func(interface{})) { - tr.mu.Lock() - tr.recycler = f - tr.mu.Unlock() -} - -func (tr *trace) SetTraceInfo(traceID, spanID uint64) { - tr.mu.Lock() - tr.traceID, tr.spanID = traceID, spanID - tr.mu.Unlock() -} - -func (tr *trace) SetMaxEvents(m int) { - tr.mu.Lock() - // Always keep at least three events: first, discarded count, last. - if len(tr.events) == 0 && m > 3 { - tr.maxEvents = m - } - tr.mu.Unlock() -} - -func (tr *trace) ref() { - atomic.AddInt32(&tr.refs, 1) -} - -func (tr *trace) unref() { - if atomic.AddInt32(&tr.refs, -1) == 0 { - tr.mu.RLock() - if tr.recycler != nil { - // freeTrace clears tr, so we hold tr.recycler and tr.events here. - go func(f func(interface{}), es []event) { - for _, e := range es { - if e.Recyclable { - f(e.What) - } - } - }(tr.recycler, tr.events) - } - tr.mu.RUnlock() - - freeTrace(tr) - } -} - -func (tr *trace) When() string { - return tr.Start.Format("2006/01/02 15:04:05.000000") -} - -func (tr *trace) ElapsedTime() string { - tr.mu.RLock() - t := tr.Elapsed - tr.mu.RUnlock() - - if t == 0 { - // Active trace. - t = time.Since(tr.Start) - } - return fmt.Sprintf("%.6f", t.Seconds()) -} - -func (tr *trace) Events() []event { - tr.mu.RLock() - defer tr.mu.RUnlock() - return tr.events -} - -var traceFreeList = make(chan *trace, 1000) // TODO(dsymonds): Use sync.Pool? - -// newTrace returns a trace ready to use. -func newTrace() *trace { - select { - case tr := <-traceFreeList: - return tr - default: - return new(trace) - } -} - -// freeTrace adds tr to traceFreeList if there's room. -// This is non-blocking. -func freeTrace(tr *trace) { - if DebugUseAfterFinish { - return // never reuse - } - tr.reset() - select { - case traceFreeList <- tr: - default: - } -} - -func elapsed(d time.Duration) string { - b := []byte(fmt.Sprintf("%.6f", d.Seconds())) - - // For subsecond durations, blank all zeros before decimal point, - // and all zeros between the decimal point and the first non-zero digit. - if d < time.Second { - dot := bytes.IndexByte(b, '.') - for i := 0; i < dot; i++ { - b[i] = ' ' - } - for i := dot + 1; i < len(b); i++ { - if b[i] == '0' { - b[i] = ' ' - } else { - break - } - } - } - - return string(b) -} - -var pageTmplCache *template.Template -var pageTmplOnce sync.Once - -func pageTmpl() *template.Template { - pageTmplOnce.Do(func() { - pageTmplCache = template.Must(template.New("Page").Funcs(template.FuncMap{ - "elapsed": elapsed, - "add": func(a, b int) int { return a + b }, - }).Parse(pageHTML)) - }) - return pageTmplCache -} - -const pageHTML = ` -{{template "Prolog" .}} -{{template "StatusTable" .}} -{{template "Epilog" .}} - -{{define "Prolog"}} - - - /debug/requests - - - - -

/debug/requests

-{{end}} {{/* end of Prolog */}} - -{{define "StatusTable"}} - - {{range $fam := .Families}} - - - - {{$n := index $.ActiveTraceCount $fam}} - - - {{$f := index $.CompletedTraces $fam}} - {{range $i, $b := $f.Buckets}} - {{$empty := $b.Empty}} - - {{end}} - - {{$nb := len $f.Buckets}} - - - - - - {{end}} -
{{$fam}} - {{if $n}}{{end}} - [{{$n}} active] - {{if $n}}{{end}} - - {{if not $empty}}{{end}} - [{{.Cond}}] - {{if not $empty}}{{end}} - - [minute] - - [hour] - - [total] -
-{{end}} {{/* end of StatusTable */}} - -{{define "Epilog"}} -{{if $.Traces}} -
-

Family: {{$.Family}}

- -{{if or $.Expanded $.Traced}} - [Normal/Summary] -{{else}} - [Normal/Summary] -{{end}} - -{{if or (not $.Expanded) $.Traced}} - [Normal/Expanded] -{{else}} - [Normal/Expanded] -{{end}} - -{{if not $.Active}} - {{if or $.Expanded (not $.Traced)}} - [Traced/Summary] - {{else}} - [Traced/Summary] - {{end}} - {{if or (not $.Expanded) (not $.Traced)}} - [Traced/Expanded] - {{else}} - [Traced/Expanded] - {{end}} -{{end}} - -{{if $.Total}} -

Showing {{len $.Traces}} of {{$.Total}} traces.

-{{end}} - - - - - {{range $tr := $.Traces}} - - - - - {{/* TODO: include traceID/spanID */}} - - {{if $.Expanded}} - {{range $tr.Events}} - - - - - - {{end}} - {{end}} - {{end}} -
- {{if $.Active}}Active{{else}}Completed{{end}} Requests -
WhenElapsed (s)
{{$tr.When}}{{$tr.ElapsedTime}}{{$tr.Title}}
{{.WhenString}}{{elapsed .Elapsed}}{{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}[redacted]{{end}}
-{{end}} {{/* if $.Traces */}} - -{{if $.Histogram}} -

Latency (µs) of {{$.Family}} over {{$.HistogramWindow}}

-{{$.Histogram}} -{{end}} {{/* if $.Histogram */}} - - - -{{end}} {{/* end of Epilog */}} -` diff --git a/examples/golang.org/x/net/trace/trace_go16.go b/examples/golang.org/x/net/trace/trace_go16.go deleted file mode 100644 index d608191..0000000 --- a/examples/golang.org/x/net/trace/trace_go16.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package trace - -import "golang.org/x/net/context" - -// NewContext returns a copy of the parent context -// and associates it with a Trace. -func NewContext(ctx context.Context, tr Trace) context.Context { - return context.WithValue(ctx, contextKey, tr) -} - -// FromContext returns the Trace bound to the context, if any. -func FromContext(ctx context.Context) (tr Trace, ok bool) { - tr, ok = ctx.Value(contextKey).(Trace) - return -} diff --git a/examples/golang.org/x/net/trace/trace_go17.go b/examples/golang.org/x/net/trace/trace_go17.go deleted file mode 100644 index df6e1fb..0000000 --- a/examples/golang.org/x/net/trace/trace_go17.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.7 - -package trace - -import "context" - -// NewContext returns a copy of the parent context -// and associates it with a Trace. -func NewContext(ctx context.Context, tr Trace) context.Context { - return context.WithValue(ctx, contextKey, tr) -} - -// FromContext returns the Trace bound to the context, if any. -func FromContext(ctx context.Context) (tr Trace, ok bool) { - tr, ok = ctx.Value(contextKey).(Trace) - return -} diff --git a/examples/golang.org/x/net/trace/trace_test.go b/examples/golang.org/x/net/trace/trace_test.go deleted file mode 100644 index bfd9dfe..0000000 --- a/examples/golang.org/x/net/trace/trace_test.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package trace - -import ( - "net/http" - "reflect" - "testing" -) - -type s struct{} - -func (s) String() string { return "lazy string" } - -// TestReset checks whether all the fields are zeroed after reset. -func TestReset(t *testing.T) { - tr := New("foo", "bar") - tr.LazyLog(s{}, false) - tr.LazyPrintf("%d", 1) - tr.SetRecycler(func(_ interface{}) {}) - tr.SetTraceInfo(3, 4) - tr.SetMaxEvents(100) - tr.SetError() - tr.Finish() - - tr.(*trace).reset() - - if !reflect.DeepEqual(tr, new(trace)) { - t.Errorf("reset didn't clear all fields: %+v", tr) - } -} - -// TestResetLog checks whether all the fields are zeroed after reset. -func TestResetLog(t *testing.T) { - el := NewEventLog("foo", "bar") - el.Printf("message") - el.Errorf("error") - el.Finish() - - el.(*eventLog).reset() - - if !reflect.DeepEqual(el, new(eventLog)) { - t.Errorf("reset didn't clear all fields: %+v", el) - } -} - -func TestAuthRequest(t *testing.T) { - testCases := []struct { - host string - want bool - }{ - {host: "192.168.23.1", want: false}, - {host: "192.168.23.1:8080", want: false}, - {host: "malformed remote addr", want: false}, - {host: "localhost", want: true}, - {host: "localhost:8080", want: true}, - {host: "127.0.0.1", want: true}, - {host: "127.0.0.1:8080", want: true}, - {host: "::1", want: true}, - {host: "[::1]:8080", want: true}, - } - for _, tt := range testCases { - req := &http.Request{RemoteAddr: tt.host} - any, sensitive := AuthRequest(req) - if any != tt.want || sensitive != tt.want { - t.Errorf("AuthRequest(%q) = %t, %t; want %t, %t", tt.host, any, sensitive, tt.want, tt.want) - } - } -} - -// TestParseTemplate checks that all templates used by this package are valid -// as they are parsed on first usage -func TestParseTemplate(t *testing.T) { - if tmpl := distTmpl(); tmpl == nil { - t.Error("invalid template returned from distTmpl()") - } - if tmpl := pageTmpl(); tmpl == nil { - t.Error("invalid template returned from pageTmpl()") - } - if tmpl := eventsTmpl(); tmpl == nil { - t.Error("invalid template returned from eventsTmpl()") - } -} - -func benchmarkTrace(b *testing.B, maxEvents, numEvents int) { - numSpans := (b.N + numEvents + 1) / numEvents - - for i := 0; i < numSpans; i++ { - tr := New("test", "test") - tr.SetMaxEvents(maxEvents) - for j := 0; j < numEvents; j++ { - tr.LazyPrintf("%d", j) - } - tr.Finish() - } -} - -func BenchmarkTrace_Default_2(b *testing.B) { - benchmarkTrace(b, 0, 2) -} - -func BenchmarkTrace_Default_10(b *testing.B) { - benchmarkTrace(b, 0, 10) -} - -func BenchmarkTrace_Default_100(b *testing.B) { - benchmarkTrace(b, 0, 100) -} - -func BenchmarkTrace_Default_1000(b *testing.B) { - benchmarkTrace(b, 0, 1000) -} - -func BenchmarkTrace_Default_10000(b *testing.B) { - benchmarkTrace(b, 0, 10000) -} - -func BenchmarkTrace_10_2(b *testing.B) { - benchmarkTrace(b, 10, 2) -} - -func BenchmarkTrace_10_10(b *testing.B) { - benchmarkTrace(b, 10, 10) -} - -func BenchmarkTrace_10_100(b *testing.B) { - benchmarkTrace(b, 10, 100) -} - -func BenchmarkTrace_10_1000(b *testing.B) { - benchmarkTrace(b, 10, 1000) -} - -func BenchmarkTrace_10_10000(b *testing.B) { - benchmarkTrace(b, 10, 10000) -} - -func BenchmarkTrace_100_2(b *testing.B) { - benchmarkTrace(b, 100, 2) -} - -func BenchmarkTrace_100_10(b *testing.B) { - benchmarkTrace(b, 100, 10) -} - -func BenchmarkTrace_100_100(b *testing.B) { - benchmarkTrace(b, 100, 100) -} - -func BenchmarkTrace_100_1000(b *testing.B) { - benchmarkTrace(b, 100, 1000) -} - -func BenchmarkTrace_100_10000(b *testing.B) { - benchmarkTrace(b, 100, 10000) -} - -func BenchmarkTrace_1000_2(b *testing.B) { - benchmarkTrace(b, 1000, 2) -} - -func BenchmarkTrace_1000_10(b *testing.B) { - benchmarkTrace(b, 1000, 10) -} - -func BenchmarkTrace_1000_100(b *testing.B) { - benchmarkTrace(b, 1000, 100) -} - -func BenchmarkTrace_1000_1000(b *testing.B) { - benchmarkTrace(b, 1000, 1000) -} - -func BenchmarkTrace_1000_10000(b *testing.B) { - benchmarkTrace(b, 1000, 10000) -} diff --git a/examples/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go b/examples/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go deleted file mode 100644 index c5a54b3..0000000 --- a/examples/google.golang.org/genproto/googleapis/api/annotations/annotations.pb.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/api/annotations.proto - -package annotations // import "google.golang.org/genproto/googleapis/api/annotations" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -var E_Http = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MethodOptions)(nil), - ExtensionType: (*HttpRule)(nil), - Field: 72295728, - Name: "google.api.http", - Tag: "bytes,72295728,opt,name=http", - Filename: "google/api/annotations.proto", -} - -func init() { - proto.RegisterExtension(E_Http) -} - -func init() { - proto.RegisterFile("google/api/annotations.proto", fileDescriptor_annotations_7782c41cc734273a) -} - -var fileDescriptor_annotations_7782c41cc734273a = []byte{ - // 208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc, - 0xcf, 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0xc8, 0xea, 0x25, 0x16, 0x64, - 0x4a, 0x89, 0x22, 0xa9, 0xcc, 0x28, 0x29, 0x29, 0x80, 0x28, 0x91, 0x52, 0x80, 0x0a, 0x83, 0x79, - 0x49, 0xa5, 0x69, 0xfa, 0x29, 0xa9, 0xc5, 0xc9, 0x45, 0x99, 0x05, 0x25, 0xf9, 0x45, 0x10, 0x15, - 0x56, 0xde, 0x5c, 0x2c, 0x20, 0xf5, 0x42, 0x72, 0x7a, 0x50, 0xd3, 0x60, 0x4a, 0xf5, 0x7c, 0x53, - 0x4b, 0x32, 0xf2, 0x53, 0xfc, 0x0b, 0xc0, 0x56, 0x4a, 0x6c, 0x38, 0xb5, 0x47, 0x49, 0x81, 0x51, - 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x61, 0xad, 0x9e, 0x47, 0x49, 0x49, 0x41, 0x50, 0x69, 0x4e, 0x6a, - 0x10, 0xd8, 0x10, 0xa7, 0x3c, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x24, 0x05, 0x4e, 0x02, 0x8e, 0x08, - 0x67, 0x07, 0x80, 0x4c, 0x0e, 0x60, 0x8c, 0x72, 0x84, 0xca, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, - 0xeb, 0xe5, 0x17, 0xa5, 0xeb, 0xa7, 0xa7, 0xe6, 0x81, 0xed, 0xd5, 0x87, 0x48, 0x25, 0x16, 0x64, - 0x16, 0xa3, 0x7b, 0xda, 0x1a, 0x89, 0xbd, 0x88, 0x89, 0xc5, 0xdd, 0x31, 0xc0, 0x33, 0x89, 0x0d, - 0xac, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xe3, 0x29, 0x19, 0x62, 0x28, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/examples/google.golang.org/genproto/googleapis/api/annotations/http.pb.go deleted file mode 100644 index 9d57e05..0000000 --- a/examples/google.golang.org/genproto/googleapis/api/annotations/http.pb.go +++ /dev/null @@ -1,666 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/api/http.proto - -package annotations // import "google.golang.org/genproto/googleapis/api/annotations" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Defines the HTTP configuration for an API service. It contains a list of -// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method -// to one or more HTTP REST API methods. -type Http struct { - // A list of HTTP configuration rules that apply to individual API methods. - // - // **NOTE:** All service configuration rules follow "last one wins" order. - Rules []*HttpRule `protobuf:"bytes,1,rep,name=rules,proto3" json:"rules,omitempty"` - // When set to true, URL path parmeters will be fully URI-decoded except in - // cases of single segment matches in reserved expansion, where "%2F" will be - // left encoded. - // - // The default behavior is to not decode RFC 6570 reserved characters in multi - // segment matches. - FullyDecodeReservedExpansion bool `protobuf:"varint,2,opt,name=fully_decode_reserved_expansion,json=fullyDecodeReservedExpansion,proto3" json:"fully_decode_reserved_expansion,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Http) Reset() { *m = Http{} } -func (m *Http) String() string { return proto.CompactTextString(m) } -func (*Http) ProtoMessage() {} -func (*Http) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{0} -} -func (m *Http) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Http.Unmarshal(m, b) -} -func (m *Http) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Http.Marshal(b, m, deterministic) -} -func (dst *Http) XXX_Merge(src proto.Message) { - xxx_messageInfo_Http.Merge(dst, src) -} -func (m *Http) XXX_Size() int { - return xxx_messageInfo_Http.Size(m) -} -func (m *Http) XXX_DiscardUnknown() { - xxx_messageInfo_Http.DiscardUnknown(m) -} - -var xxx_messageInfo_Http proto.InternalMessageInfo - -func (m *Http) GetRules() []*HttpRule { - if m != nil { - return m.Rules - } - return nil -} - -func (m *Http) GetFullyDecodeReservedExpansion() bool { - if m != nil { - return m.FullyDecodeReservedExpansion - } - return false -} - -// `HttpRule` defines the mapping of an RPC method to one or more HTTP -// REST API methods. The mapping specifies how different portions of the RPC -// request message are mapped to URL path, URL query parameters, and -// HTTP request body. The mapping is typically specified as an -// `google.api.http` annotation on the RPC method, -// see "google/api/annotations.proto" for details. -// -// The mapping consists of a field specifying the path template and -// method kind. The path template can refer to fields in the request -// message, as in the example below which describes a REST GET -// operation on a resource collection of messages: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// SubMessage sub = 2; // `sub.subfield` is url-mapped -// } -// message Message { -// string text = 1; // content of the resource -// } -// -// The same http annotation can alternatively be expressed inside the -// `GRPC API Configuration` YAML file. -// -// http: -// rules: -// - selector: .Messaging.GetMessage -// get: /v1/messages/{message_id}/{sub.subfield} -// -// This definition enables an automatic, bidrectional mapping of HTTP -// JSON to RPC. Example: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` -// -// In general, not only fields but also field paths can be referenced -// from a path pattern. Fields mapped to the path pattern cannot be -// repeated and must have a primitive (non-message) type. -// -// Any fields in the request message which are not bound by the path -// pattern automatically become (optional) HTTP query -// parameters. Assume the following definition of the request message: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// int64 revision = 2; // becomes a parameter -// SubMessage sub = 3; // `sub.subfield` becomes a parameter -// } -// -// -// This enables a HTTP JSON to RPC mapping as below: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` -// -// Note that fields which are mapped to HTTP parameters must have a -// primitive type or a repeated primitive type. Message types are not -// allowed. In the case of a repeated type, the parameter can be -// repeated in the URL, as in `...?param=A¶m=B`. -// -// For HTTP method kinds which allow a request body, the `body` field -// specifies the mapping. Consider a REST update method on the -// message resource collection: -// -// -// service Messaging { -// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "message" -// }; -// } -// } -// message UpdateMessageRequest { -// string message_id = 1; // mapped to the URL -// Message message = 2; // mapped to the body -// } -// -// -// The following HTTP JSON to RPC mapping is enabled, where the -// representation of the JSON in the request body is determined by -// protos JSON encoding: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` -// -// The special name `*` can be used in the body mapping to define that -// every field not bound by the path template should be mapped to the -// request body. This enables the following alternative definition of -// the update method: -// -// service Messaging { -// rpc UpdateMessage(Message) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "*" -// }; -// } -// } -// message Message { -// string message_id = 1; -// string text = 2; -// } -// -// -// The following HTTP JSON to RPC mapping is enabled: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` -// -// Note that when using `*` in the body mapping, it is not possible to -// have HTTP parameters, as all fields not bound by the path end in -// the body. This makes this option more rarely used in practice of -// defining REST APIs. The common usage of `*` is in custom methods -// which don't use the URL at all for transferring data. -// -// It is possible to define multiple HTTP methods for one RPC by using -// the `additional_bindings` option. Example: -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http) = { -// get: "/v1/messages/{message_id}" -// additional_bindings { -// get: "/v1/users/{user_id}/messages/{message_id}" -// } -// }; -// } -// } -// message GetMessageRequest { -// string message_id = 1; -// string user_id = 2; -// } -// -// -// This enables the following two alternative HTTP JSON to RPC -// mappings: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` -// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` -// -// # Rules for HTTP mapping -// -// The rules for mapping HTTP path, query parameters, and body fields -// to the request message are as follows: -// -// 1. The `body` field specifies either `*` or a field path, or is -// omitted. If omitted, it indicates there is no HTTP request body. -// 2. Leaf fields (recursive expansion of nested messages in the -// request) can be classified into three types: -// (a) Matched in the URL template. -// (b) Covered by body (if body is `*`, everything except (a) fields; -// else everything under the body field) -// (c) All other fields. -// 3. URL query parameters found in the HTTP request are mapped to (c) fields. -// 4. Any body sent with an HTTP request can contain only (b) fields. -// -// The syntax of the path template is as follows: -// -// Template = "/" Segments [ Verb ] ; -// Segments = Segment { "/" Segment } ; -// Segment = "*" | "**" | LITERAL | Variable ; -// Variable = "{" FieldPath [ "=" Segments ] "}" ; -// FieldPath = IDENT { "." IDENT } ; -// Verb = ":" LITERAL ; -// -// The syntax `*` matches a single path segment. The syntax `**` matches zero -// or more path segments, which must be the last part of the path except the -// `Verb`. The syntax `LITERAL` matches literal text in the path. -// -// The syntax `Variable` matches part of the URL path as specified by its -// template. A variable template must not contain other variables. If a variable -// matches a single path segment, its template may be omitted, e.g. `{var}` -// is equivalent to `{var=*}`. -// -// If a variable contains exactly one path segment, such as `"{var}"` or -// `"{var=*}"`, when such a variable is expanded into a URL path, all characters -// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the -// Discovery Document as `{var}`. -// -// If a variable contains one or more path segments, such as `"{var=foo/*}"` -// or `"{var=**}"`, when such a variable is expanded into a URL path, all -// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables -// show up in the Discovery Document as `{+var}`. -// -// NOTE: While the single segment variable matches the semantics of -// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 -// Simple String Expansion, the multi segment variable **does not** match -// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion -// does not expand special characters like `?` and `#`, which would lead -// to invalid URLs. -// -// NOTE: the field paths in variables and in the `body` must not refer to -// repeated fields or map fields. -type HttpRule struct { - // Selects methods to which this rule applies. - // - // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. - Selector string `protobuf:"bytes,1,opt,name=selector,proto3" json:"selector,omitempty"` - // Determines the URL pattern is matched by this rules. This pattern can be - // used with any of the {get|put|post|delete|patch} methods. A custom method - // can be defined using the 'custom' field. - // - // Types that are valid to be assigned to Pattern: - // *HttpRule_Get - // *HttpRule_Put - // *HttpRule_Post - // *HttpRule_Delete - // *HttpRule_Patch - // *HttpRule_Custom - Pattern isHttpRule_Pattern `protobuf_oneof:"pattern"` - // The name of the request field whose value is mapped to the HTTP body, or - // `*` for mapping all fields not captured by the path pattern to the HTTP - // body. NOTE: the referred field must not be a repeated field and must be - // present at the top-level of request message type. - Body string `protobuf:"bytes,7,opt,name=body,proto3" json:"body,omitempty"` - // Additional HTTP bindings for the selector. Nested bindings must - // not contain an `additional_bindings` field themselves (that is, - // the nesting may only be one level deep). - AdditionalBindings []*HttpRule `protobuf:"bytes,11,rep,name=additional_bindings,json=additionalBindings,proto3" json:"additional_bindings,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HttpRule) Reset() { *m = HttpRule{} } -func (m *HttpRule) String() string { return proto.CompactTextString(m) } -func (*HttpRule) ProtoMessage() {} -func (*HttpRule) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{1} -} -func (m *HttpRule) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HttpRule.Unmarshal(m, b) -} -func (m *HttpRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HttpRule.Marshal(b, m, deterministic) -} -func (dst *HttpRule) XXX_Merge(src proto.Message) { - xxx_messageInfo_HttpRule.Merge(dst, src) -} -func (m *HttpRule) XXX_Size() int { - return xxx_messageInfo_HttpRule.Size(m) -} -func (m *HttpRule) XXX_DiscardUnknown() { - xxx_messageInfo_HttpRule.DiscardUnknown(m) -} - -var xxx_messageInfo_HttpRule proto.InternalMessageInfo - -type isHttpRule_Pattern interface { - isHttpRule_Pattern() -} - -type HttpRule_Get struct { - Get string `protobuf:"bytes,2,opt,name=get,proto3,oneof"` -} -type HttpRule_Put struct { - Put string `protobuf:"bytes,3,opt,name=put,proto3,oneof"` -} -type HttpRule_Post struct { - Post string `protobuf:"bytes,4,opt,name=post,proto3,oneof"` -} -type HttpRule_Delete struct { - Delete string `protobuf:"bytes,5,opt,name=delete,proto3,oneof"` -} -type HttpRule_Patch struct { - Patch string `protobuf:"bytes,6,opt,name=patch,proto3,oneof"` -} -type HttpRule_Custom struct { - Custom *CustomHttpPattern `protobuf:"bytes,8,opt,name=custom,proto3,oneof"` -} - -func (*HttpRule_Get) isHttpRule_Pattern() {} -func (*HttpRule_Put) isHttpRule_Pattern() {} -func (*HttpRule_Post) isHttpRule_Pattern() {} -func (*HttpRule_Delete) isHttpRule_Pattern() {} -func (*HttpRule_Patch) isHttpRule_Pattern() {} -func (*HttpRule_Custom) isHttpRule_Pattern() {} - -func (m *HttpRule) GetPattern() isHttpRule_Pattern { - if m != nil { - return m.Pattern - } - return nil -} - -func (m *HttpRule) GetSelector() string { - if m != nil { - return m.Selector - } - return "" -} - -func (m *HttpRule) GetGet() string { - if x, ok := m.GetPattern().(*HttpRule_Get); ok { - return x.Get - } - return "" -} - -func (m *HttpRule) GetPut() string { - if x, ok := m.GetPattern().(*HttpRule_Put); ok { - return x.Put - } - return "" -} - -func (m *HttpRule) GetPost() string { - if x, ok := m.GetPattern().(*HttpRule_Post); ok { - return x.Post - } - return "" -} - -func (m *HttpRule) GetDelete() string { - if x, ok := m.GetPattern().(*HttpRule_Delete); ok { - return x.Delete - } - return "" -} - -func (m *HttpRule) GetPatch() string { - if x, ok := m.GetPattern().(*HttpRule_Patch); ok { - return x.Patch - } - return "" -} - -func (m *HttpRule) GetCustom() *CustomHttpPattern { - if x, ok := m.GetPattern().(*HttpRule_Custom); ok { - return x.Custom - } - return nil -} - -func (m *HttpRule) GetBody() string { - if m != nil { - return m.Body - } - return "" -} - -func (m *HttpRule) GetAdditionalBindings() []*HttpRule { - if m != nil { - return m.AdditionalBindings - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*HttpRule) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _HttpRule_OneofMarshaler, _HttpRule_OneofUnmarshaler, _HttpRule_OneofSizer, []interface{}{ - (*HttpRule_Get)(nil), - (*HttpRule_Put)(nil), - (*HttpRule_Post)(nil), - (*HttpRule_Delete)(nil), - (*HttpRule_Patch)(nil), - (*HttpRule_Custom)(nil), - } -} - -func _HttpRule_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*HttpRule) - // pattern - switch x := m.Pattern.(type) { - case *HttpRule_Get: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Get) - case *HttpRule_Put: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Put) - case *HttpRule_Post: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Post) - case *HttpRule_Delete: - b.EncodeVarint(5<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Delete) - case *HttpRule_Patch: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Patch) - case *HttpRule_Custom: - b.EncodeVarint(8<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Custom); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("HttpRule.Pattern has unexpected type %T", x) - } - return nil -} - -func _HttpRule_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*HttpRule) - switch tag { - case 2: // pattern.get - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Get{x} - return true, err - case 3: // pattern.put - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Put{x} - return true, err - case 4: // pattern.post - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Post{x} - return true, err - case 5: // pattern.delete - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Delete{x} - return true, err - case 6: // pattern.patch - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Pattern = &HttpRule_Patch{x} - return true, err - case 8: // pattern.custom - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(CustomHttpPattern) - err := b.DecodeMessage(msg) - m.Pattern = &HttpRule_Custom{msg} - return true, err - default: - return false, nil - } -} - -func _HttpRule_OneofSizer(msg proto.Message) (n int) { - m := msg.(*HttpRule) - // pattern - switch x := m.Pattern.(type) { - case *HttpRule_Get: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Get))) - n += len(x.Get) - case *HttpRule_Put: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Put))) - n += len(x.Put) - case *HttpRule_Post: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Post))) - n += len(x.Post) - case *HttpRule_Delete: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Delete))) - n += len(x.Delete) - case *HttpRule_Patch: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Patch))) - n += len(x.Patch) - case *HttpRule_Custom: - s := proto.Size(x.Custom) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// A custom pattern is used for defining custom HTTP verb. -type CustomHttpPattern struct { - // The name of this custom HTTP verb. - Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` - // The path matched by this custom verb. - Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CustomHttpPattern) Reset() { *m = CustomHttpPattern{} } -func (m *CustomHttpPattern) String() string { return proto.CompactTextString(m) } -func (*CustomHttpPattern) ProtoMessage() {} -func (*CustomHttpPattern) Descriptor() ([]byte, []int) { - return fileDescriptor_http_9c97bbd8b94894d4, []int{2} -} -func (m *CustomHttpPattern) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CustomHttpPattern.Unmarshal(m, b) -} -func (m *CustomHttpPattern) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CustomHttpPattern.Marshal(b, m, deterministic) -} -func (dst *CustomHttpPattern) XXX_Merge(src proto.Message) { - xxx_messageInfo_CustomHttpPattern.Merge(dst, src) -} -func (m *CustomHttpPattern) XXX_Size() int { - return xxx_messageInfo_CustomHttpPattern.Size(m) -} -func (m *CustomHttpPattern) XXX_DiscardUnknown() { - xxx_messageInfo_CustomHttpPattern.DiscardUnknown(m) -} - -var xxx_messageInfo_CustomHttpPattern proto.InternalMessageInfo - -func (m *CustomHttpPattern) GetKind() string { - if m != nil { - return m.Kind - } - return "" -} - -func (m *CustomHttpPattern) GetPath() string { - if m != nil { - return m.Path - } - return "" -} - -func init() { - proto.RegisterType((*Http)(nil), "google.api.Http") - proto.RegisterType((*HttpRule)(nil), "google.api.HttpRule") - proto.RegisterType((*CustomHttpPattern)(nil), "google.api.CustomHttpPattern") -} - -func init() { proto.RegisterFile("google/api/http.proto", fileDescriptor_http_9c97bbd8b94894d4) } - -var fileDescriptor_http_9c97bbd8b94894d4 = []byte{ - // 401 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0xab, 0x13, 0x31, - 0x10, 0xc7, 0xdd, 0x76, 0xdb, 0xd7, 0x4e, 0x41, 0x30, 0x3e, 0x25, 0x88, 0x62, 0xe9, 0xa9, 0x78, - 0xd8, 0xc2, 0xf3, 0xe0, 0xe1, 0x9d, 0x5e, 0xb5, 0xf8, 0xbc, 0x95, 0x3d, 0x7a, 0x29, 0xe9, 0x66, - 0x4c, 0xa3, 0x79, 0x49, 0xd8, 0xcc, 0x8a, 0xfd, 0x3a, 0x7e, 0x07, 0xbf, 0x9b, 0x47, 0x49, 0x36, - 0xb5, 0x05, 0xc1, 0xdb, 0xfc, 0xff, 0xf3, 0xcb, 0xcc, 0x64, 0x18, 0x78, 0xa6, 0x9c, 0x53, 0x06, - 0x57, 0xc2, 0xeb, 0xd5, 0x81, 0xc8, 0x57, 0xbe, 0x75, 0xe4, 0x18, 0xf4, 0x76, 0x25, 0xbc, 0x5e, - 0x1c, 0xa1, 0xbc, 0x27, 0xf2, 0xec, 0x0d, 0x8c, 0xda, 0xce, 0x60, 0xe0, 0xc5, 0x7c, 0xb8, 0x9c, - 0xdd, 0x5c, 0x57, 0x67, 0xa6, 0x8a, 0x40, 0xdd, 0x19, 0xac, 0x7b, 0x84, 0x6d, 0xe0, 0xf5, 0x97, - 0xce, 0x98, 0xe3, 0x4e, 0x62, 0xe3, 0x24, 0xee, 0x5a, 0x0c, 0xd8, 0x7e, 0x47, 0xb9, 0xc3, 0x1f, - 0x5e, 0xd8, 0xa0, 0x9d, 0xe5, 0x83, 0x79, 0xb1, 0x9c, 0xd4, 0x2f, 0x13, 0xf6, 0x21, 0x51, 0x75, - 0x86, 0x36, 0x27, 0x66, 0xf1, 0x6b, 0x00, 0x93, 0x53, 0x69, 0xf6, 0x02, 0x26, 0x01, 0x0d, 0x36, - 0xe4, 0x5a, 0x5e, 0xcc, 0x8b, 0xe5, 0xb4, 0xfe, 0xab, 0x19, 0x83, 0xa1, 0x42, 0x4a, 0x35, 0xa7, - 0xf7, 0x8f, 0xea, 0x28, 0xa2, 0xe7, 0x3b, 0xe2, 0xc3, 0x93, 0xe7, 0x3b, 0x62, 0xd7, 0x50, 0x7a, - 0x17, 0x88, 0x97, 0xd9, 0x4c, 0x8a, 0x71, 0x18, 0x4b, 0x34, 0x48, 0xc8, 0x47, 0xd9, 0xcf, 0x9a, - 0x3d, 0x87, 0x91, 0x17, 0xd4, 0x1c, 0xf8, 0x38, 0x27, 0x7a, 0xc9, 0xde, 0xc1, 0xb8, 0xe9, 0x02, - 0xb9, 0x07, 0x3e, 0x99, 0x17, 0xcb, 0xd9, 0xcd, 0xab, 0xcb, 0x65, 0xbc, 0x4f, 0x99, 0x38, 0xf7, - 0x56, 0x10, 0x61, 0x6b, 0x63, 0xc1, 0x1e, 0x67, 0x0c, 0xca, 0xbd, 0x93, 0x47, 0x7e, 0x95, 0x3e, - 0x90, 0x62, 0xb6, 0x81, 0xa7, 0x42, 0x4a, 0x4d, 0xda, 0x59, 0x61, 0x76, 0x7b, 0x6d, 0xa5, 0xb6, - 0x2a, 0xf0, 0xd9, 0x7f, 0xd6, 0xcc, 0xce, 0x0f, 0xd6, 0x99, 0x5f, 0x4f, 0xe1, 0xca, 0xf7, 0xfd, - 0x16, 0xb7, 0xf0, 0xe4, 0x9f, 0x21, 0x62, 0xeb, 0x6f, 0xda, 0xca, 0xbc, 0xbb, 0x14, 0x47, 0xcf, - 0x0b, 0x3a, 0xf4, 0x8b, 0xab, 0x53, 0xbc, 0xfe, 0x0a, 0x8f, 0x1b, 0xf7, 0x70, 0xd1, 0x76, 0x3d, - 0x4d, 0x65, 0xe2, 0x61, 0x6c, 0x8b, 0xcf, 0x77, 0x39, 0xa1, 0x9c, 0x11, 0x56, 0x55, 0xae, 0x55, - 0x2b, 0x85, 0x36, 0x9d, 0xcd, 0xaa, 0x4f, 0x09, 0xaf, 0x43, 0x3a, 0x28, 0x61, 0xad, 0x23, 0x11, - 0xc7, 0x0c, 0xb7, 0x17, 0xf1, 0xef, 0xa2, 0xf8, 0x39, 0x28, 0x3f, 0xde, 0x6d, 0x3f, 0xed, 0xc7, - 0xe9, 0xdd, 0xdb, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x73, 0x2c, 0xed, 0xfb, 0x87, 0x02, 0x00, - 0x00, -} diff --git a/examples/google.golang.org/genproto/googleapis/rpc/code/code.pb.go b/examples/google.golang.org/genproto/googleapis/rpc/code/code.pb.go deleted file mode 100644 index 80315f9..0000000 --- a/examples/google.golang.org/genproto/googleapis/rpc/code/code.pb.go +++ /dev/null @@ -1,246 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/rpc/code.proto - -/* -Package code is a generated protocol buffer package. - -It is generated from these files: - google/rpc/code.proto - -It has these top-level messages: -*/ -package code - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The canonical error codes for Google APIs. -// -// -// Sometimes multiple error codes may apply. Services should return -// the most specific error code that applies. For example, prefer -// `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply. -// Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`. -type Code int32 - -const ( - // Not an error; returned on success - // - // HTTP Mapping: 200 OK - Code_OK Code = 0 - // The operation was cancelled, typically by the caller. - // - // HTTP Mapping: 499 Client Closed Request - Code_CANCELLED Code = 1 - // Unknown error. For example, this error may be returned when - // a `Status` value received from another address space belongs to - // an error space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - // - // HTTP Mapping: 500 Internal Server Error - Code_UNKNOWN Code = 2 - // The client specified an invalid argument. Note that this differs - // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - // - // HTTP Mapping: 400 Bad Request - Code_INVALID_ARGUMENT Code = 3 - // The deadline expired before the operation could complete. For operations - // that change the state of the system, this error may be returned - // even if the operation has completed successfully. For example, a - // successful response from a server could have been delayed long - // enough for the deadline to expire. - // - // HTTP Mapping: 504 Gateway Timeout - Code_DEADLINE_EXCEEDED Code = 4 - // Some requested entity (e.g., file or directory) was not found. - // For privacy reasons, this code *may* be returned when the client - // does not have the access rights to the entity, though such usage is - // discouraged. - // - // HTTP Mapping: 404 Not Found - Code_NOT_FOUND Code = 5 - // The entity that a client attempted to create (e.g., file or directory) - // already exists. - // - // HTTP Mapping: 409 Conflict - Code_ALREADY_EXISTS Code = 6 - // The caller does not have permission to execute the specified - // operation. `PERMISSION_DENIED` must not be used for rejections - // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` - // instead for those errors). `PERMISSION_DENIED` must not be - // used if the caller can not be identified (use `UNAUTHENTICATED` - // instead for those errors). - // - // HTTP Mapping: 403 Forbidden - Code_PERMISSION_DENIED Code = 7 - // The request does not have valid authentication credentials for the - // operation. - // - // HTTP Mapping: 401 Unauthorized - Code_UNAUTHENTICATED Code = 16 - // Some resource has been exhausted, perhaps a per-user quota, or - // perhaps the entire file system is out of space. - // - // HTTP Mapping: 429 Too Many Requests - Code_RESOURCE_EXHAUSTED Code = 8 - // The operation was rejected because the system is not in a state - // required for the operation's execution. For example, the directory - // to be deleted is non-empty, an rmdir operation is applied to - // a non-directory, etc. - // - // Service implementors can use the following guidelines to decide - // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: - // (a) Use `UNAVAILABLE` if the client can retry just the failing call. - // (b) Use `ABORTED` if the client should retry at a higher level - // (e.g., restarting a read-modify-write sequence). - // (c) Use `FAILED_PRECONDITION` if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, `FAILED_PRECONDITION` - // should be returned since the client should not retry unless - // the files are deleted from the directory. - // - // HTTP Mapping: 400 Bad Request - Code_FAILED_PRECONDITION Code = 9 - // The operation was aborted, typically due to a concurrency issue such as - // a sequencer check failure or transaction abort. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 409 Conflict - Code_ABORTED Code = 10 - // The operation was attempted past the valid range. E.g., seeking or - // reading past end-of-file. - // - // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate `INVALID_ARGUMENT` if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // `OUT_OF_RANGE` if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between `FAILED_PRECONDITION` and - // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an `OUT_OF_RANGE` error to detect when - // they are done. - // - // HTTP Mapping: 400 Bad Request - Code_OUT_OF_RANGE Code = 11 - // The operation is not implemented or is not supported/enabled in this - // service. - // - // HTTP Mapping: 501 Not Implemented - Code_UNIMPLEMENTED Code = 12 - // Internal errors. This means that some invariants expected by the - // underlying system have been broken. This error code is reserved - // for serious errors. - // - // HTTP Mapping: 500 Internal Server Error - Code_INTERNAL Code = 13 - // The service is currently unavailable. This is most likely a - // transient condition, which can be corrected by retrying with - // a backoff. - // - // See the guidelines above for deciding between `FAILED_PRECONDITION`, - // `ABORTED`, and `UNAVAILABLE`. - // - // HTTP Mapping: 503 Service Unavailable - Code_UNAVAILABLE Code = 14 - // Unrecoverable data loss or corruption. - // - // HTTP Mapping: 500 Internal Server Error - Code_DATA_LOSS Code = 15 -) - -var Code_name = map[int32]string{ - 0: "OK", - 1: "CANCELLED", - 2: "UNKNOWN", - 3: "INVALID_ARGUMENT", - 4: "DEADLINE_EXCEEDED", - 5: "NOT_FOUND", - 6: "ALREADY_EXISTS", - 7: "PERMISSION_DENIED", - 16: "UNAUTHENTICATED", - 8: "RESOURCE_EXHAUSTED", - 9: "FAILED_PRECONDITION", - 10: "ABORTED", - 11: "OUT_OF_RANGE", - 12: "UNIMPLEMENTED", - 13: "INTERNAL", - 14: "UNAVAILABLE", - 15: "DATA_LOSS", -} -var Code_value = map[string]int32{ - "OK": 0, - "CANCELLED": 1, - "UNKNOWN": 2, - "INVALID_ARGUMENT": 3, - "DEADLINE_EXCEEDED": 4, - "NOT_FOUND": 5, - "ALREADY_EXISTS": 6, - "PERMISSION_DENIED": 7, - "UNAUTHENTICATED": 16, - "RESOURCE_EXHAUSTED": 8, - "FAILED_PRECONDITION": 9, - "ABORTED": 10, - "OUT_OF_RANGE": 11, - "UNIMPLEMENTED": 12, - "INTERNAL": 13, - "UNAVAILABLE": 14, - "DATA_LOSS": 15, -} - -func (x Code) String() string { - return proto.EnumName(Code_name, int32(x)) -} -func (Code) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func init() { - proto.RegisterEnum("google.rpc.Code", Code_name, Code_value) -} - -func init() { proto.RegisterFile("google/rpc/code.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 362 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x51, 0xcd, 0x6e, 0x93, 0x31, - 0x10, 0xa4, 0x69, 0x49, 0x9b, 0xcd, 0xdf, 0xd6, 0xa5, 0xf0, 0x0e, 0x1c, 0x92, 0x43, 0x8f, 0x9c, - 0x36, 0x9f, 0x37, 0xad, 0x55, 0x67, 0xfd, 0xc9, 0x3f, 0x25, 0x70, 0xb1, 0x4a, 0x1a, 0x7d, 0x42, - 0x2a, 0x75, 0xf4, 0xc1, 0x13, 0xf1, 0x12, 0xbc, 0x1e, 0x72, 0x8b, 0xe8, 0xc5, 0x87, 0x99, 0xf1, - 0xee, 0xce, 0x0c, 0x5c, 0x76, 0xa5, 0x74, 0x8f, 0xfb, 0x65, 0x7f, 0xd8, 0x2d, 0x77, 0xe5, 0x61, - 0xbf, 0x38, 0xf4, 0xe5, 0x57, 0x51, 0xf0, 0x02, 0x2f, 0xfa, 0xc3, 0xee, 0xe3, 0x9f, 0x01, 0x9c, - 0x34, 0xe5, 0x61, 0xaf, 0x86, 0x30, 0x70, 0xb7, 0xf8, 0x46, 0x4d, 0x61, 0xd4, 0x90, 0x34, 0x6c, - 0x2d, 0x6b, 0x3c, 0x52, 0x63, 0x38, 0x4d, 0x72, 0x2b, 0xee, 0xb3, 0xe0, 0x40, 0xbd, 0x03, 0x34, - 0x72, 0x47, 0xd6, 0xe8, 0x4c, 0xfe, 0x3a, 0x6d, 0x58, 0x22, 0x1e, 0xab, 0x4b, 0x38, 0xd7, 0x4c, - 0xda, 0x1a, 0xe1, 0xcc, 0xdb, 0x86, 0x59, 0xb3, 0xc6, 0x93, 0x3a, 0x48, 0x5c, 0xcc, 0x6b, 0x97, - 0x44, 0xe3, 0x5b, 0xa5, 0x60, 0x46, 0xd6, 0x33, 0xe9, 0x2f, 0x99, 0xb7, 0x26, 0xc4, 0x80, 0xc3, - 0xfa, 0xb3, 0x65, 0xbf, 0x31, 0x21, 0x18, 0x27, 0x59, 0xb3, 0x18, 0xd6, 0x78, 0xaa, 0x2e, 0x60, - 0x9e, 0x84, 0x52, 0xbc, 0x61, 0x89, 0xa6, 0xa1, 0xc8, 0x1a, 0x51, 0xbd, 0x07, 0xe5, 0x39, 0xb8, - 0xe4, 0x9b, 0xba, 0xe5, 0x86, 0x52, 0xa8, 0xf8, 0x99, 0xfa, 0x00, 0x17, 0x6b, 0x32, 0x96, 0x75, - 0x6e, 0x3d, 0x37, 0x4e, 0xb4, 0x89, 0xc6, 0x09, 0x8e, 0xea, 0xe5, 0xb4, 0x72, 0xbe, 0xaa, 0x40, - 0x21, 0x4c, 0x5c, 0x8a, 0xd9, 0xad, 0xb3, 0x27, 0xb9, 0x66, 0x1c, 0xab, 0x73, 0x98, 0x26, 0x31, - 0x9b, 0xd6, 0x72, 0xb5, 0xc1, 0x1a, 0x27, 0x6a, 0x02, 0x67, 0x46, 0x22, 0x7b, 0x21, 0x8b, 0x53, - 0x35, 0x87, 0x71, 0x12, 0xba, 0x23, 0x63, 0x69, 0x65, 0x19, 0x67, 0xd5, 0x90, 0xa6, 0x48, 0xd9, - 0xba, 0x10, 0x70, 0xbe, 0xda, 0xc2, 0x6c, 0x57, 0x7e, 0x2c, 0x5e, 0xb3, 0x5c, 0x8d, 0x6a, 0x90, - 0x6d, 0x8d, 0xb8, 0x3d, 0xfa, 0x7a, 0xf5, 0x8f, 0xe8, 0xca, 0xe3, 0xfd, 0x53, 0xb7, 0x28, 0x7d, - 0xb7, 0xec, 0xf6, 0x4f, 0xcf, 0x05, 0x2c, 0x5f, 0xa8, 0xfb, 0xc3, 0xf7, 0x9f, 0xff, 0xab, 0xf9, - 0x54, 0x9f, 0xdf, 0x83, 0x63, 0xdf, 0x36, 0xdf, 0x86, 0xcf, 0xaa, 0xab, 0xbf, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x8e, 0x97, 0x77, 0xc2, 0xbf, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/genproto/googleapis/rpc/errdetails/error_details.pb.go b/examples/google.golang.org/genproto/googleapis/rpc/errdetails/error_details.pb.go deleted file mode 100644 index 37d202f..0000000 --- a/examples/google.golang.org/genproto/googleapis/rpc/errdetails/error_details.pb.go +++ /dev/null @@ -1,422 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/rpc/error_details.proto - -/* -Package errdetails is a generated protocol buffer package. - -It is generated from these files: - google/rpc/error_details.proto - -It has these top-level messages: - RetryInfo - DebugInfo - QuotaFailure - BadRequest - RequestInfo - ResourceInfo - Help - LocalizedMessage -*/ -package errdetails - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/duration" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Describes when the clients can retry a failed request. Clients could ignore -// the recommendation here or retry when this information is missing from error -// responses. -// -// It's always recommended that clients should use exponential backoff when -// retrying. -// -// Clients should wait until `retry_delay` amount of time has passed since -// receiving the error response before retrying. If retrying requests also -// fail, clients should use an exponential backoff scheme to gradually increase -// the delay between retries based on `retry_delay`, until either a maximum -// number of retires have been reached or a maximum retry delay cap has been -// reached. -type RetryInfo struct { - // Clients should wait at least this long between retrying the same request. - RetryDelay *google_protobuf.Duration `protobuf:"bytes,1,opt,name=retry_delay,json=retryDelay" json:"retry_delay,omitempty"` -} - -func (m *RetryInfo) Reset() { *m = RetryInfo{} } -func (m *RetryInfo) String() string { return proto.CompactTextString(m) } -func (*RetryInfo) ProtoMessage() {} -func (*RetryInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *RetryInfo) GetRetryDelay() *google_protobuf.Duration { - if m != nil { - return m.RetryDelay - } - return nil -} - -// Describes additional debugging info. -type DebugInfo struct { - // The stack trace entries indicating where the error occurred. - StackEntries []string `protobuf:"bytes,1,rep,name=stack_entries,json=stackEntries" json:"stack_entries,omitempty"` - // Additional debugging information provided by the server. - Detail string `protobuf:"bytes,2,opt,name=detail" json:"detail,omitempty"` -} - -func (m *DebugInfo) Reset() { *m = DebugInfo{} } -func (m *DebugInfo) String() string { return proto.CompactTextString(m) } -func (*DebugInfo) ProtoMessage() {} -func (*DebugInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *DebugInfo) GetStackEntries() []string { - if m != nil { - return m.StackEntries - } - return nil -} - -func (m *DebugInfo) GetDetail() string { - if m != nil { - return m.Detail - } - return "" -} - -// Describes how a quota check failed. -// -// For example if a daily limit was exceeded for the calling project, -// a service could respond with a QuotaFailure detail containing the project -// id and the description of the quota limit that was exceeded. If the -// calling project hasn't enabled the service in the developer console, then -// a service could respond with the project id and set `service_disabled` -// to true. -// -// Also see RetryDetail and Help types for other details about handling a -// quota failure. -type QuotaFailure struct { - // Describes all quota violations. - Violations []*QuotaFailure_Violation `protobuf:"bytes,1,rep,name=violations" json:"violations,omitempty"` -} - -func (m *QuotaFailure) Reset() { *m = QuotaFailure{} } -func (m *QuotaFailure) String() string { return proto.CompactTextString(m) } -func (*QuotaFailure) ProtoMessage() {} -func (*QuotaFailure) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *QuotaFailure) GetViolations() []*QuotaFailure_Violation { - if m != nil { - return m.Violations - } - return nil -} - -// A message type used to describe a single quota violation. For example, a -// daily quota or a custom quota that was exceeded. -type QuotaFailure_Violation struct { - // The subject on which the quota check failed. - // For example, "clientip:" or "project:". - Subject string `protobuf:"bytes,1,opt,name=subject" json:"subject,omitempty"` - // A description of how the quota check failed. Clients can use this - // description to find more about the quota configuration in the service's - // public documentation, or find the relevant quota limit to adjust through - // developer console. - // - // For example: "Service disabled" or "Daily Limit for read operations - // exceeded". - Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` -} - -func (m *QuotaFailure_Violation) Reset() { *m = QuotaFailure_Violation{} } -func (m *QuotaFailure_Violation) String() string { return proto.CompactTextString(m) } -func (*QuotaFailure_Violation) ProtoMessage() {} -func (*QuotaFailure_Violation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } - -func (m *QuotaFailure_Violation) GetSubject() string { - if m != nil { - return m.Subject - } - return "" -} - -func (m *QuotaFailure_Violation) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -// Describes violations in a client request. This error type focuses on the -// syntactic aspects of the request. -type BadRequest struct { - // Describes all violations in a client request. - FieldViolations []*BadRequest_FieldViolation `protobuf:"bytes,1,rep,name=field_violations,json=fieldViolations" json:"field_violations,omitempty"` -} - -func (m *BadRequest) Reset() { *m = BadRequest{} } -func (m *BadRequest) String() string { return proto.CompactTextString(m) } -func (*BadRequest) ProtoMessage() {} -func (*BadRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } - -func (m *BadRequest) GetFieldViolations() []*BadRequest_FieldViolation { - if m != nil { - return m.FieldViolations - } - return nil -} - -// A message type used to describe a single bad request field. -type BadRequest_FieldViolation struct { - // A path leading to a field in the request body. The value will be a - // sequence of dot-separated identifiers that identify a protocol buffer - // field. E.g., "field_violations.field" would identify this field. - Field string `protobuf:"bytes,1,opt,name=field" json:"field,omitempty"` - // A description of why the request element is bad. - Description string `protobuf:"bytes,2,opt,name=description" json:"description,omitempty"` -} - -func (m *BadRequest_FieldViolation) Reset() { *m = BadRequest_FieldViolation{} } -func (m *BadRequest_FieldViolation) String() string { return proto.CompactTextString(m) } -func (*BadRequest_FieldViolation) ProtoMessage() {} -func (*BadRequest_FieldViolation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3, 0} } - -func (m *BadRequest_FieldViolation) GetField() string { - if m != nil { - return m.Field - } - return "" -} - -func (m *BadRequest_FieldViolation) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -// Contains metadata about the request that clients can attach when filing a bug -// or providing other forms of feedback. -type RequestInfo struct { - // An opaque string that should only be interpreted by the service generating - // it. For example, it can be used to identify requests in the service's logs. - RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId" json:"request_id,omitempty"` - // Any data that was used to serve this request. For example, an encrypted - // stack trace that can be sent back to the service provider for debugging. - ServingData string `protobuf:"bytes,2,opt,name=serving_data,json=servingData" json:"serving_data,omitempty"` -} - -func (m *RequestInfo) Reset() { *m = RequestInfo{} } -func (m *RequestInfo) String() string { return proto.CompactTextString(m) } -func (*RequestInfo) ProtoMessage() {} -func (*RequestInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } - -func (m *RequestInfo) GetRequestId() string { - if m != nil { - return m.RequestId - } - return "" -} - -func (m *RequestInfo) GetServingData() string { - if m != nil { - return m.ServingData - } - return "" -} - -// Describes the resource that is being accessed. -type ResourceInfo struct { - // A name for the type of resource being accessed, e.g. "sql table", - // "cloud storage bucket", "file", "Google calendar"; or the type URL - // of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic". - ResourceType string `protobuf:"bytes,1,opt,name=resource_type,json=resourceType" json:"resource_type,omitempty"` - // The name of the resource being accessed. For example, a shared calendar - // name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current - // error is [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. - ResourceName string `protobuf:"bytes,2,opt,name=resource_name,json=resourceName" json:"resource_name,omitempty"` - // The owner of the resource (optional). - // For example, "user:" or "project:". - Owner string `protobuf:"bytes,3,opt,name=owner" json:"owner,omitempty"` - // Describes what error is encountered when accessing this resource. - // For example, updating a cloud project may require the `writer` permission - // on the developer console project. - Description string `protobuf:"bytes,4,opt,name=description" json:"description,omitempty"` -} - -func (m *ResourceInfo) Reset() { *m = ResourceInfo{} } -func (m *ResourceInfo) String() string { return proto.CompactTextString(m) } -func (*ResourceInfo) ProtoMessage() {} -func (*ResourceInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } - -func (m *ResourceInfo) GetResourceType() string { - if m != nil { - return m.ResourceType - } - return "" -} - -func (m *ResourceInfo) GetResourceName() string { - if m != nil { - return m.ResourceName - } - return "" -} - -func (m *ResourceInfo) GetOwner() string { - if m != nil { - return m.Owner - } - return "" -} - -func (m *ResourceInfo) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -// Provides links to documentation or for performing an out of band action. -// -// For example, if a quota check failed with an error indicating the calling -// project hasn't enabled the accessed service, this can contain a URL pointing -// directly to the right place in the developer console to flip the bit. -type Help struct { - // URL(s) pointing to additional information on handling the current error. - Links []*Help_Link `protobuf:"bytes,1,rep,name=links" json:"links,omitempty"` -} - -func (m *Help) Reset() { *m = Help{} } -func (m *Help) String() string { return proto.CompactTextString(m) } -func (*Help) ProtoMessage() {} -func (*Help) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } - -func (m *Help) GetLinks() []*Help_Link { - if m != nil { - return m.Links - } - return nil -} - -// Describes a URL link. -type Help_Link struct { - // Describes what the link offers. - Description string `protobuf:"bytes,1,opt,name=description" json:"description,omitempty"` - // The URL of the link. - Url string `protobuf:"bytes,2,opt,name=url" json:"url,omitempty"` -} - -func (m *Help_Link) Reset() { *m = Help_Link{} } -func (m *Help_Link) String() string { return proto.CompactTextString(m) } -func (*Help_Link) ProtoMessage() {} -func (*Help_Link) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6, 0} } - -func (m *Help_Link) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *Help_Link) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -// Provides a localized error message that is safe to return to the user -// which can be attached to an RPC error. -type LocalizedMessage struct { - // The locale used following the specification defined at - // http://www.rfc-editor.org/rfc/bcp/bcp47.txt. - // Examples are: "en-US", "fr-CH", "es-MX" - Locale string `protobuf:"bytes,1,opt,name=locale" json:"locale,omitempty"` - // The localized error message in the above locale. - Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` -} - -func (m *LocalizedMessage) Reset() { *m = LocalizedMessage{} } -func (m *LocalizedMessage) String() string { return proto.CompactTextString(m) } -func (*LocalizedMessage) ProtoMessage() {} -func (*LocalizedMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } - -func (m *LocalizedMessage) GetLocale() string { - if m != nil { - return m.Locale - } - return "" -} - -func (m *LocalizedMessage) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func init() { - proto.RegisterType((*RetryInfo)(nil), "google.rpc.RetryInfo") - proto.RegisterType((*DebugInfo)(nil), "google.rpc.DebugInfo") - proto.RegisterType((*QuotaFailure)(nil), "google.rpc.QuotaFailure") - proto.RegisterType((*QuotaFailure_Violation)(nil), "google.rpc.QuotaFailure.Violation") - proto.RegisterType((*BadRequest)(nil), "google.rpc.BadRequest") - proto.RegisterType((*BadRequest_FieldViolation)(nil), "google.rpc.BadRequest.FieldViolation") - proto.RegisterType((*RequestInfo)(nil), "google.rpc.RequestInfo") - proto.RegisterType((*ResourceInfo)(nil), "google.rpc.ResourceInfo") - proto.RegisterType((*Help)(nil), "google.rpc.Help") - proto.RegisterType((*Help_Link)(nil), "google.rpc.Help.Link") - proto.RegisterType((*LocalizedMessage)(nil), "google.rpc.LocalizedMessage") -} - -func init() { proto.RegisterFile("google/rpc/error_details.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 551 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x94, 0xc1, 0x6f, 0xd3, 0x3e, - 0x14, 0xc7, 0x95, 0x75, 0xdb, 0x4f, 0x79, 0xed, 0x6f, 0x94, 0x08, 0x50, 0xa9, 0x04, 0x2a, 0x41, - 0x48, 0x95, 0x90, 0x52, 0x69, 0xdc, 0xc6, 0x01, 0xa9, 0x64, 0x5b, 0x27, 0x0d, 0x28, 0x11, 0xe2, - 0xc0, 0x25, 0x72, 0x93, 0xd7, 0xc8, 0xd4, 0x8d, 0x83, 0xed, 0x0c, 0x95, 0xbf, 0x82, 0x3b, 0x37, - 0x4e, 0xfc, 0x99, 0xc8, 0xb1, 0xbd, 0xa6, 0xeb, 0x85, 0x5b, 0xbe, 0xcf, 0x1f, 0x7f, 0xf3, 0x7d, - 0x89, 0x9f, 0xe1, 0x69, 0xc1, 0x79, 0xc1, 0x70, 0x22, 0xaa, 0x6c, 0x82, 0x42, 0x70, 0x91, 0xe6, - 0xa8, 0x08, 0x65, 0x32, 0xaa, 0x04, 0x57, 0x3c, 0x00, 0xb3, 0x1e, 0x89, 0x2a, 0x1b, 0x3a, 0xb6, - 0x59, 0x59, 0xd4, 0xcb, 0x49, 0x5e, 0x0b, 0xa2, 0x28, 0x2f, 0x0d, 0x1b, 0x5e, 0x82, 0x9f, 0xa0, - 0x12, 0x9b, 0xab, 0x72, 0xc9, 0x83, 0x33, 0xe8, 0x0a, 0x2d, 0xd2, 0x1c, 0x19, 0xd9, 0x0c, 0xbc, - 0x91, 0x37, 0xee, 0x9e, 0x3e, 0x8e, 0xac, 0x9d, 0xb3, 0x88, 0x62, 0x6b, 0x91, 0x40, 0x43, 0xc7, - 0x1a, 0x0e, 0x67, 0xe0, 0xc7, 0xb8, 0xa8, 0x8b, 0xc6, 0xe8, 0x39, 0xfc, 0x2f, 0x15, 0xc9, 0x56, - 0x29, 0x96, 0x4a, 0x50, 0x94, 0x03, 0x6f, 0xd4, 0x19, 0xfb, 0x49, 0xaf, 0x29, 0x9e, 0x9b, 0x5a, - 0xf0, 0x08, 0x8e, 0x4d, 0xee, 0xc1, 0xc1, 0xc8, 0x1b, 0xfb, 0x89, 0x55, 0xe1, 0x2f, 0x0f, 0x7a, - 0x1f, 0x6b, 0xae, 0xc8, 0x05, 0xa1, 0xac, 0x16, 0x18, 0x4c, 0x01, 0x6e, 0x28, 0x67, 0xcd, 0x3b, - 0x8d, 0x55, 0xf7, 0x34, 0x8c, 0xb6, 0x4d, 0x46, 0x6d, 0x3a, 0xfa, 0xec, 0xd0, 0xa4, 0xb5, 0x6b, - 0x78, 0x09, 0xfe, 0xed, 0x42, 0x30, 0x80, 0xff, 0x64, 0xbd, 0xf8, 0x8a, 0x99, 0x6a, 0x7a, 0xf4, - 0x13, 0x27, 0x83, 0x11, 0x74, 0x73, 0x94, 0x99, 0xa0, 0x95, 0x06, 0x6d, 0xb0, 0x76, 0x29, 0xfc, - 0xe3, 0x01, 0x4c, 0x49, 0x9e, 0xe0, 0xb7, 0x1a, 0xa5, 0x0a, 0xe6, 0xd0, 0x5f, 0x52, 0x64, 0x79, - 0xba, 0x97, 0xf0, 0x45, 0x3b, 0xe1, 0x76, 0x47, 0x74, 0xa1, 0xf1, 0x6d, 0xc8, 0x7b, 0xcb, 0x1d, - 0x2d, 0x87, 0x33, 0x38, 0xd9, 0x45, 0x82, 0x07, 0x70, 0xd4, 0x40, 0x36, 0xac, 0x11, 0xff, 0x10, - 0xf5, 0x03, 0x74, 0xed, 0x4b, 0x9b, 0x9f, 0xf2, 0x04, 0x40, 0x18, 0x99, 0x52, 0xe7, 0xe5, 0xdb, - 0xca, 0x55, 0x1e, 0x3c, 0x83, 0x9e, 0x44, 0x71, 0x43, 0xcb, 0x22, 0xcd, 0x89, 0x22, 0xce, 0xd0, - 0xd6, 0x62, 0xa2, 0x48, 0xf8, 0xd3, 0x83, 0x5e, 0x82, 0x92, 0xd7, 0x22, 0x43, 0xf7, 0x9f, 0x85, - 0xd5, 0xa9, 0xda, 0x54, 0x68, 0x5d, 0x7b, 0xae, 0xf8, 0x69, 0x53, 0xe1, 0x0e, 0x54, 0x92, 0x35, - 0x5a, 0xe7, 0x5b, 0xe8, 0x3d, 0x59, 0xa3, 0xee, 0x91, 0x7f, 0x2f, 0x51, 0x0c, 0x3a, 0xa6, 0xc7, - 0x46, 0xdc, 0xed, 0xf1, 0x70, 0xbf, 0x47, 0x0e, 0x87, 0x33, 0x64, 0x55, 0xf0, 0x12, 0x8e, 0x18, - 0x2d, 0x57, 0xee, 0xe3, 0x3f, 0x6c, 0x7f, 0x7c, 0x0d, 0x44, 0xd7, 0xb4, 0x5c, 0x25, 0x86, 0x19, - 0x9e, 0xc1, 0xa1, 0x96, 0x77, 0xed, 0xbd, 0x3d, 0xfb, 0xa0, 0x0f, 0x9d, 0x5a, 0xb8, 0x03, 0xaa, - 0x1f, 0xc3, 0x18, 0xfa, 0xd7, 0x3c, 0x23, 0x8c, 0xfe, 0xc0, 0xfc, 0x1d, 0x4a, 0x49, 0x0a, 0xd4, - 0x27, 0x99, 0xe9, 0x9a, 0xeb, 0xdf, 0x2a, 0x7d, 0xce, 0xd6, 0x06, 0xb1, 0x0e, 0x4e, 0x4e, 0x19, - 0x9c, 0x64, 0x7c, 0xdd, 0x0a, 0x39, 0xbd, 0x7f, 0xae, 0x27, 0x39, 0x36, 0x83, 0x3c, 0xd7, 0xa3, - 0x36, 0xf7, 0xbe, 0xbc, 0xb1, 0x40, 0xc1, 0x19, 0x29, 0x8b, 0x88, 0x8b, 0x62, 0x52, 0x60, 0xd9, - 0x0c, 0xe2, 0xc4, 0x2c, 0x91, 0x8a, 0x4a, 0x77, 0x11, 0xd8, 0x5b, 0xe0, 0xf5, 0xf6, 0xf1, 0xf7, - 0x41, 0x27, 0x99, 0xbf, 0x5d, 0x1c, 0x37, 0x3b, 0x5e, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xc0, - 0x5e, 0xc6, 0x6f, 0x39, 0x04, 0x00, 0x00, -} diff --git a/examples/google.golang.org/genproto/googleapis/rpc/status/status.pb.go b/examples/google.golang.org/genproto/googleapis/rpc/status/status.pb.go deleted file mode 100644 index 40e7937..0000000 --- a/examples/google.golang.org/genproto/googleapis/rpc/status/status.pb.go +++ /dev/null @@ -1,143 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/rpc/status.proto - -/* -Package status is a generated protocol buffer package. - -It is generated from these files: - google/rpc/status.proto - -It has these top-level messages: - Status -*/ -package status - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/any" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// 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. -type Status struct { - // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. - Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` - // 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. - Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` - // A list of messages that carry the error details. There will be a - // common set of message types for APIs to use. - Details []*google_protobuf.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"` -} - -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} -func (*Status) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *Status) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *Status) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func (m *Status) GetDetails() []*google_protobuf.Any { - if m != nil { - return m.Details - } - return nil -} - -func init() { - proto.RegisterType((*Status)(nil), "google.rpc.Status") -} - -func init() { proto.RegisterFile("google/rpc/status.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 209 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x2a, 0x48, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x2b, 0x28, - 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0x48, 0xe8, 0x15, 0x15, 0x24, 0x4b, 0x49, 0x42, 0x15, 0x81, - 0x65, 0x92, 0x4a, 0xd3, 0xf4, 0x13, 0xf3, 0x2a, 0x21, 0xca, 0x94, 0xd2, 0xb8, 0xd8, 0x82, 0xc1, - 0xda, 0x84, 0x84, 0xb8, 0x58, 0x92, 0xf3, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83, - 0xc0, 0x6c, 0x21, 0x09, 0x2e, 0xf6, 0xdc, 0xd4, 0xe2, 0xe2, 0xc4, 0xf4, 0x54, 0x09, 0x26, 0x05, - 0x46, 0x0d, 0xce, 0x20, 0x18, 0x57, 0x48, 0x8f, 0x8b, 0x3d, 0x25, 0xb5, 0x24, 0x31, 0x33, 0xa7, - 0x58, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x6a, 0x21, 0xcc, 0x12, 0x3d, 0xc7, - 0xbc, 0xca, 0x20, 0x98, 0x22, 0xa7, 0x38, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x3d, 0x84, 0xa3, 0x9c, - 0xb8, 0x21, 0xf6, 0x06, 0x80, 0x94, 0x07, 0x30, 0x46, 0x99, 0x43, 0xa5, 0xd2, 0xf3, 0x73, 0x12, - 0xf3, 0xd2, 0xf5, 0xf2, 0x8b, 0xd2, 0xf5, 0xd3, 0x53, 0xf3, 0xc0, 0x86, 0xe9, 0x43, 0xa4, 0x12, - 0x0b, 0x32, 0x8b, 0x91, 0xfc, 0x69, 0x0d, 0xa1, 0x16, 0x31, 0x31, 0x07, 0x05, 0x38, 0x27, 0xb1, - 0x81, 0x55, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xa4, 0x53, 0xf0, 0x7c, 0x10, 0x01, 0x00, - 0x00, -} diff --git a/examples/google.golang.org/grpc/.github/ISSUE_TEMPLATE b/examples/google.golang.org/grpc/.github/ISSUE_TEMPLATE deleted file mode 100755 index 642f85a..0000000 --- a/examples/google.golang.org/grpc/.github/ISSUE_TEMPLATE +++ /dev/null @@ -1,14 +0,0 @@ -Please answer these questions before submitting your issue. - -### What version of gRPC are you using? - -### What version of Go are you using (`go version`)? - -### What operating system (Linux, Windows, …) and version? - -### What did you do? -If possible, provide a recipe for reproducing the error. - -### What did you expect to see? - -### What did you see instead? diff --git a/examples/google.golang.org/grpc/.travis.yml b/examples/google.golang.org/grpc/.travis.yml deleted file mode 100755 index 3c2621a..0000000 --- a/examples/google.golang.org/grpc/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: go - -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - -matrix: - include: - - go: 1.10.x - env: RUN386=1 - -go_import_path: google.golang.org/grpc - -before_install: - - if [[ -n "$RUN386" ]]; then export GOARCH=386; fi - - if [[ "$TRAVIS_GO_VERSION" = 1.10* && "$GOARCH" != "386" ]]; then ./vet.sh -install || exit 1; fi - -script: - - if [[ "$TRAVIS_GO_VERSION" = 1.10* && "$GOARCH" != "386" ]]; then ./vet.sh || exit 1; fi - - make test || exit 1 - - if [[ "$GOARCH" != "386" ]]; then make testrace; fi diff --git a/examples/google.golang.org/grpc/AUTHORS b/examples/google.golang.org/grpc/AUTHORS deleted file mode 100755 index e491a9e..0000000 --- a/examples/google.golang.org/grpc/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Google Inc. diff --git a/examples/google.golang.org/grpc/CONTRIBUTING.md b/examples/google.golang.org/grpc/CONTRIBUTING.md deleted file mode 100755 index 0863eb2..0000000 --- a/examples/google.golang.org/grpc/CONTRIBUTING.md +++ /dev/null @@ -1,36 +0,0 @@ -# How to contribute - -We definitely welcome your patches and contributions to gRPC! - -If you are new to github, please start by reading [Pull Request howto](https://help.github.com/articles/about-pull-requests/) - -## Legal requirements - -In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://identity.linuxfoundation.org/projects/cncf). - -## Guidelines for Pull Requests -How to get your contributions merged smoothly and quickly. - -- Create **small PRs** that are narrowly focused on **addressing a single concern**. We often times receive PRs that are trying to fix several things at a time, but only one fix is considered acceptable, nothing gets merged and both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy. - -- For speculative changes, consider opening an issue and discussing it first. If you are suggesting a behavioral or API change, consider starting with a [gRFC proposal](https://github.com/grpc/proposal). - -- Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists. - -- Don't fix code style and formatting unless you are already changing that line to address an issue. PRs with irrelevant changes won't be merged. If you do want to fix formatting or style, do that in a separate PR. - -- Unless your PR is trivial, you should expect there will be reviewer comments that you'll need to address before merging. We expect you to be reasonably responsive to those comments, otherwise the PR will be closed after 2-3 weeks of inactivity. - -- Maintain **clean commit history** and use **meaningful commit messages**. PRs with messy commit history are difficult to review and won't be merged. Use `rebase -i upstream/master` to curate your commit history and/or to bring in latest changes from master (but avoid rebasing in the middle of a code review). - -- Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change). - -- **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. - - `make all` to test everything, OR - - `make vet` to catch vet errors - - `make test` to run the tests - - `make testrace` to run tests in race mode - -- Exceptions to the rules can be made if there's a compelling reason for doing so. - diff --git a/examples/google.golang.org/grpc/Documentation/compression.md b/examples/google.golang.org/grpc/Documentation/compression.md deleted file mode 100755 index 204f880..0000000 --- a/examples/google.golang.org/grpc/Documentation/compression.md +++ /dev/null @@ -1,80 +0,0 @@ -# Compression - -The preferred method for configuring message compression on both clients and -servers is to use -[`encoding.RegisterCompressor`](https://godoc.org/google.golang.org/grpc/encoding#RegisterCompressor) -to register an implementation of a compression algorithm. See -`grpc/encoding/gzip/gzip.go` for an example of how to implement one. - -Once a compressor has been registered on the client-side, RPCs may be sent using -it via the -[`UseCompressor`](https://godoc.org/google.golang.org/grpc#UseCompressor) -`CallOption`. Remember that `CallOption`s may be turned into defaults for all -calls from a `ClientConn` by using the -[`WithDefaultCallOptions`](https://godoc.org/google.golang.org/grpc#WithDefaultCallOptions) -`DialOption`. If `UseCompressor` is used and the corresponding compressor has -not been installed, an `Internal` error will be returned to the application -before the RPC is sent. - -Server-side, registered compressors will be used automatically to decode request -messages and encode the responses. Servers currently always respond using the -same compression method specified by the client. If the corresponding -compressor has not been registered, an `Unimplemented` status will be returned -to the client. - -## Deprecated API - -There is a deprecated API for setting compression as well. It is not -recommended for use. However, if you were previously using it, the following -section may be helpful in understanding how it works in combination with the new -API. - -### Client-Side - -There are two legacy functions and one new function to configure compression: - -```go -func WithCompressor(grpc.Compressor) DialOption {} -func WithDecompressor(grpc.Decompressor) DialOption {} -func UseCompressor(name) CallOption {} -``` - -For outgoing requests, the following rules are applied in order: -1. If `UseCompressor` is used, messages will be compressed using the compressor - named. - * If the compressor named is not registered, an Internal error is returned - back to the client before sending the RPC. - * If UseCompressor("identity"), no compressor will be used, but "identity" - will be sent in the header to the server. -1. If `WithCompressor` is used, messages will be compressed using that - compressor implementation. -1. Otherwise, outbound messages will be uncompressed. - -For incoming responses, the following rules are applied in order: -1. If `WithDecompressor` is used and it matches the message's encoding, it will - be used. -1. If a registered compressor matches the response's encoding, it will be used. -1. Otherwise, the stream will be closed and an `Unimplemented` status error will - be returned to the application. - -### Server-Side - -There are two legacy functions to configure compression: -```go -func RPCCompressor(grpc.Compressor) ServerOption {} -func RPCDecompressor(grpc.Decompressor) ServerOption {} -``` - -For incoming requests, the following rules are applied in order: -1. If `RPCDecompressor` is used and that decompressor matches the request's - encoding: it will be used. -1. If a registered compressor matches the request's encoding, it will be used. -1. Otherwise, an `Unimplemented` status will be returned to the client. - -For outgoing responses, the following rules are applied in order: -1. If `RPCCompressor` is used, that compressor will be used to compress all - response messages. -1. If compression was used for the incoming request and a registered compressor - supports it, that same compression method will be used for the outgoing - response. -1. Otherwise, no compression will be used for the outgoing response. diff --git a/examples/google.golang.org/grpc/Documentation/concurrency.md b/examples/google.golang.org/grpc/Documentation/concurrency.md deleted file mode 100755 index d0c1142..0000000 --- a/examples/google.golang.org/grpc/Documentation/concurrency.md +++ /dev/null @@ -1,33 +0,0 @@ -# Concurrency - -In general, gRPC-go provides a concurrency-friendly API. What follows are some -guidelines. - -## Clients - -A [ClientConn][client-conn] can safely be accessed concurrently. Using -[helloworld][helloworld] as an example, one could share the `ClientConn` across -multiple goroutines to create multiple `GreeterClient` types. In this case, RPCs -would be sent in parallel. - -## Streams - -When using streams, one must take care to avoid calling either `SendMsg` or -`RecvMsg` multiple times against the same [Stream][stream] from different -goroutines. In other words, it's safe to have a goroutine calling `SendMsg` and -another goroutine calling `RecvMsg` on the same stream at the same time. But it -is not safe to call `SendMsg` on the same stream in different goroutines, or to -call `RecvMsg` on the same stream in different goroutines. - -## Servers - -Each RPC handler attached to a registered server will be invoked in its own -goroutine. For example, [SayHello][say-hello] will be invoked in its own -goroutine. The same is true for service handlers for streaming RPCs, as seen -in the route guide example [here][route-guide-stream]. - -[helloworld]: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_client/main.go#L43 -[client-conn]: https://godoc.org/google.golang.org/grpc#ClientConn -[stream]: https://godoc.org/google.golang.org/grpc#Stream -[say-hello]: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_server/main.go#L41 -[route-guide-stream]: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/server/server.go#L126 diff --git a/examples/google.golang.org/grpc/Documentation/encoding.md b/examples/google.golang.org/grpc/Documentation/encoding.md deleted file mode 100755 index 3143660..0000000 --- a/examples/google.golang.org/grpc/Documentation/encoding.md +++ /dev/null @@ -1,146 +0,0 @@ -# Encoding - -The gRPC API for sending and receiving is based upon *messages*. However, -messages cannot be transmitted directly over a network; they must first be -converted into *bytes*. This document describes how gRPC-Go converts messages -into bytes and vice-versa for the purposes of network transmission. - -## Codecs (Serialization and Deserialization) - -A `Codec` contains code to serialize a message into a byte slice (`Marshal`) and -deserialize a byte slice back into a message (`Unmarshal`). `Codec`s are -registered by name into a global registry maintained in the `encoding` package. - -### Implementing a `Codec` - -A typical `Codec` will be implemented in its own package with an `init` function -that registers itself, and is imported anonymously. For example: - -```go -package proto - -import "google.golang.org/grpc/encoding" - -func init() { - encoding.RegisterCodec(protoCodec{}) -} - -// ... implementation of protoCodec ... -``` - -For an example, gRPC's implementation of the `proto` codec can be found in -[`encoding/proto`](https://godoc.org/google.golang.org/grpc/encoding/proto). - -### Using a `Codec` - -By default, gRPC registers and uses the "proto" codec, so it is not necessary to -do this in your own code to send and receive proto messages. To use another -`Codec` from a client or server: - -```go -package myclient - -import _ "path/to/another/codec" -``` - -`Codec`s, by definition, must be symmetric, so the same desired `Codec` should -be registered in both client and server binaries. - -On the client-side, to specify a `Codec` to use for message transmission, the -`CallOption` `CallContentSubtype` should be used as follows: - -```go - response, err := myclient.MyCall(ctx, request, grpc.CallContentSubtype("mycodec")) -``` - -As a reminder, all `CallOption`s may be converted into `DialOption`s that become -the default for all RPCs sent through a client using `grpc.WithDefaultCallOptions`: - -```go - myclient := grpc.Dial(ctx, target, grpc.WithDefaultCallOptions(grpc.CallContentSubtype("mycodec"))) -``` - -When specified in either of these ways, messages will be encoded using this -codec and sent along with headers indicating the codec (`content-type` set to -`application/grpc+`). - -On the server-side, using a `Codec` is as simple as registering it into the -global registry (i.e. `import`ing it). If a message is encoded with the content -sub-type supported by a registered `Codec`, it will be used automatically for -decoding the request and encoding the response. Otherwise, for -backward-compatibility reasons, gRPC will attempt to use the "proto" codec. In -an upcoming change (tracked in [this -issue](https://github.com/grpc/grpc-go/issues/1824)), such requests will be -rejected with status code `Unimplemented` instead. - -## Compressors (Compression and Decompression) - -Sometimes, the resulting serialization of a message is not space-efficient, and -it may be beneficial to compress this byte stream before transmitting it over -the network. To facilitate this operation, gRPC supports a mechanism for -performing compression and decompression. - -A `Compressor` contains code to compress and decompress by wrapping `io.Writer`s -and `io.Reader`s, respectively. (The form of `Compress` and `Decompress` were -chosen to most closely match Go's standard package -[implementations](https://golang.org/pkg/compress/) of compressors. Like -`Codec`s, `Compressor`s are registered by name into a global registry maintained -in the `encoding` package. - -### Implementing a `Compressor` - -A typical `Compressor` will be implemented in its own package with an `init` -function that registers itself, and is imported anonymously. For example: - -```go -package gzip - -import "google.golang.org/grpc/encoding" - -func init() { - encoding.RegisterCompressor(compressor{}) -} - -// ... implementation of compressor ... -``` - -An implementation of a `gzip` compressor can be found in -[`encoding/gzip`](https://godoc.org/google.golang.org/grpc/encoding/gzip). - -### Using a `Compressor` - -By default, gRPC does not register or use any compressors. To use a -`Compressor` from a client or server: - -```go -package myclient - -import _ "google.golang.org/grpc/encoding/gzip" -``` - -`Compressor`s, by definition, must be symmetric, so the same desired -`Compressor` should be registered in both client and server binaries. - -On the client-side, to specify a `Compressor` to use for message transmission, -the `CallOption` `UseCompressor` should be used as follows: - -```go - response, err := myclient.MyCall(ctx, request, grpc.UseCompressor("gzip")) -``` - -As a reminder, all `CallOption`s may be converted into `DialOption`s that become -the default for all RPCs sent through a client using `grpc.WithDefaultCallOptions`: - -```go - myclient := grpc.Dial(ctx, target, grpc.WithDefaultCallOptions(grpc.UseCompresor("gzip"))) -``` - -When specified in either of these ways, messages will be compressed using this -compressor and sent along with headers indicating the compressor -(`content-coding` set to ``). - -On the server-side, using a `Compressor` is as simple as registering it into the -global registry (i.e. `import`ing it). If a message is compressed with the -content coding supported by a registered `Compressor`, it will be used -automatically for decompressing the request and compressing the response. -Otherwise, the request will be rejected with status code `Unimplemented`. diff --git a/examples/google.golang.org/grpc/Documentation/gomock-example.md b/examples/google.golang.org/grpc/Documentation/gomock-example.md deleted file mode 100755 index 54743e8..0000000 --- a/examples/google.golang.org/grpc/Documentation/gomock-example.md +++ /dev/null @@ -1,182 +0,0 @@ -# Mocking Service for gRPC - -[Example code unary RPC](https://github.com/grpc/grpc-go/tree/master/examples/helloworld/mock_helloworld) - -[Example code streaming RPC](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/mock_routeguide) - -## Why? - -To test client-side logic without the overhead of connecting to a real server. Mocking enables users to write light-weight unit tests to check functionalities on client-side without invoking RPC calls to a server. - -## Idea: Mock the client stub that connects to the server. - -We use Gomock to mock the client interface (in the generated code) and programmatically set its methods to expect and return pre-determined values. This enables users to write tests around the client logic and use this mocked stub while making RPC calls. - -## How to use Gomock? - -Documentation on Gomock can be found [here](https://github.com/golang/mock). -A quick reading of the documentation should enable users to follow the code below. - -Consider a gRPC service based on following proto file: - -```proto -//helloworld.proto - -package helloworld; - -message HelloRequest { - string name = 1; -} - -message HelloReply { - string name = 1; -} - -service Greeter { - rpc SayHello (HelloRequest) returns (HelloReply) {} -} -``` - -The generated file helloworld.pb.go will have a client interface for each service defined in the proto file. This interface will have methods corresponding to each rpc inside that service. - -```Go -type GreeterClient interface { - SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) -} -``` - -The generated code also contains a struct that implements this interface. - -```Go -type greeterClient struct { - cc *grpc.ClientConn -} -func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error){ - // ... - // gRPC specific code here - // ... -} -``` - -Along with this the generated code has a method to create an instance of this struct. -```Go -func NewGreeterClient(cc *grpc.ClientConn) GreeterClient -``` - -The user code uses this function to create an instance of the struct greeterClient which then can be used to make rpc calls to the server. -We will mock this interface GreeterClient and use an instance of that mock to make rpc calls. These calls instead of going to server will return pre-determined values. - -To create a mock we’ll use [mockgen](https://github.com/golang/mock#running-mockgen). -From the directory ``` examples/helloworld/ ``` run ``` mockgen google.golang.org/grpc/examples/helloworld/helloworld GreeterClient > mock_helloworld/hw_mock.go ``` - -Notice that in the above command we specify GreeterClient as the interface to be mocked. - -The user test code can import the package generated by mockgen along with library package gomock to write unit tests around client-side logic. -```Go -import "github.com/golang/mock/gomock" -import hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld" -``` - -An instance of the mocked interface can be created as: -```Go -mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) -``` -This mocked object can be programmed to expect calls to its methods and return pre-determined values. For instance, we can program mockGreeterClient to expect a call to its method SayHello and return a HelloReply with message “Mocked RPC”. - -```Go -mockGreeterClient.EXPECT().SayHello( - gomock.Any(), // expect any value for first parameter - gomock.Any(), // expect any value for second parameter -).Return(&helloworld.HelloReply{Message: “Mocked RPC”}, nil) -``` - -gomock.Any() indicates that the parameter can have any value or type. We can indicate specific values for built-in types with gomock.Eq(). -However, if the test code needs to specify the parameter to have a proto message type, we can replace gomock.Any() with an instance of a struct that implements gomock.Matcher interface. - -```Go -type rpcMsg struct { - msg proto.Message -} - -func (r *rpcMsg) Matches(msg interface{}) bool { - m, ok := msg.(proto.Message) - if !ok { - return false - } - return proto.Equal(m, r.msg) -} - -func (r *rpcMsg) String() string { - return fmt.Sprintf("is %s", r.msg) -} - -... - -req := &helloworld.HelloRequest{Name: "unit_test"} -mockGreeterClient.EXPECT().SayHello( - gomock.Any(), - &rpcMsg{msg: req}, -).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) -``` - -## Mock streaming RPCs: - -For our example we consider the case of bi-directional streaming RPCs. Concretely, we'll write a test for RouteChat function from the route guide example to demonstrate how to write mocks for streams. - -RouteChat is a bi-directional streaming RPC, which means calling RouteChat returns a stream that can __Send__ and __Recv__ messages to and from the server, respectively. We'll start by creating a mock of this stream interface returned by RouteChat and then we'll mock the client interface and set expectation on the method RouteChat to return our mocked stream. - -### Generating mocking code: -Like before we'll use [mockgen](https://github.com/golang/mock#running-mockgen). From the `examples/route_guide` directory run: `mockgen google.golang.org/grpc/examples/route_guide/routeguide RouteGuideClient,RouteGuide_RouteChatClient > mock_route_guide/rg_mock.go` - -Notice that we are mocking both client(`RouteGuideClient`) and stream(`RouteGuide_RouteChatClient`) interfaces here. - -This will create a file `rg_mock.go` under directory `mock_route_guide`. This file contins all the mocking code we need to write our test. - -In our test code, like before, we import the this mocking code along with the generated code - -```go -import ( - rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide" - rgpb "google.golang.org/grpc/examples/route_guide/routeguide" -) -``` - -Now conside a test that takes the RouteGuide client object as a parameter, makes a RouteChat rpc call and sends a message on the resulting stream. Furthermore, this test expects to see the same message to be received on the stream. - -```go -var msg = ... - -// Creates a RouteChat call and sends msg on it. -// Checks if the received message was equal to msg. -func testRouteChat(client rgb.RouteChatClient) error{ - ... -} -``` - -We can inject our mock in here by simply passing it as an argument to the method. - -Creating mock for stream interface: - -```go - stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl) -} -``` - -Setting Expectations: - -```go - stream.EXPECT().Send(gomock.Any()).Return(nil) - stream.EXPECT().Recv().Return(msg, nil) -``` - -Creating mock for client interface: - -```go - rgclient := rgmock.NewMockRouteGuideClient(ctrl) -``` - -Setting Expectations: - -```go - rgclient.EXPECT().RouteChat(gomock.Any()).Return(stream, nil) -``` diff --git a/examples/google.golang.org/grpc/Documentation/grpc-auth-support.md b/examples/google.golang.org/grpc/Documentation/grpc-auth-support.md deleted file mode 100755 index b023267..0000000 --- a/examples/google.golang.org/grpc/Documentation/grpc-auth-support.md +++ /dev/null @@ -1,78 +0,0 @@ -# Authentication - -As outlined in the [gRPC authentication guide](https://grpc.io/docs/guides/auth.html) there are a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it. - -# Enabling TLS on a gRPC client - -```Go -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))) -``` - -# Enabling TLS on a gRPC server - -```Go -creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) -if err != nil { - log.Fatalf("Failed to generate credentials %v", err) -} -lis, err := net.Listen("tcp", ":0") -server := grpc.NewServer(grpc.Creds(creds)) -... -server.Serve(lis) -``` - -# OAuth2 - -For an example of how to configure client and server to use OAuth2 tokens, see -[here](https://github.com/grpc/grpc-go/blob/master/examples/oauth/). - -## Validating a token on the server - -Clients may use -[metadata.MD](https://godoc.org/google.golang.org/grpc/metadata#MD) -to store tokens and other authentication-related data. To gain access to the -`metadata.MD` object, a server may use -[metadata.FromIncomingContext](https://godoc.org/google.golang.org/grpc/metadata#FromIncomingContext). -With a reference to `metadata.MD` on the server, one needs to simply lookup the -`authorization` key. Note, all keys stored within `metadata.MD` are normalized -to lowercase. See [here](https://godoc.org/google.golang.org/grpc/metadata#New). - -It is possible to configure token validation for all RPCs using an interceptor. -A server may configure either a -[grpc.UnaryInterceptor](https://godoc.org/google.golang.org/grpc#UnaryInterceptor) -or a -[grpc.StreamInterceptor](https://godoc.org/google.golang.org/grpc#StreamInterceptor). - -## Adding a token to all outgoing client RPCs - -To send an OAuth2 token with each RPC, a client may configure the -`grpc.DialOption` -[grpc.WithPerRPCCredentials](https://godoc.org/google.golang.org/grpc#WithPerRPCCredentials). -Alternatively, a client may also use the `grpc.CallOption` -[grpc.PerRPCCredentials](https://godoc.org/google.golang.org/grpc#PerRPCCredentials) -on each invocation of an RPC. - -To create a `credentials.PerRPCCredentials`, use -[oauth.NewOauthAccess](https://godoc.org/google.golang.org/grpc/credentials/oauth#NewOauthAccess). -Note, the OAuth2 implementation of `grpc.PerRPCCredentials` requires a client to use -[grpc.WithTransportCredentials](https://godoc.org/google.golang.org/grpc#WithTransportCredentials) -to prevent any insecure transmission of tokens. - -# Authenticating with Google - -## Google Compute Engine (GCE) - -```Go -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(oauth.NewComputeEngine())) -``` - -## JWT - -```Go -jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) -if err != nil { - log.Fatalf("Failed to create JWT credentials: %v", err) -} -conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(jwtCreds)) -``` - diff --git a/examples/google.golang.org/grpc/Documentation/grpc-metadata.md b/examples/google.golang.org/grpc/Documentation/grpc-metadata.md deleted file mode 100755 index 971c469..0000000 --- a/examples/google.golang.org/grpc/Documentation/grpc-metadata.md +++ /dev/null @@ -1,227 +0,0 @@ -# Metadata - -gRPC supports sending metadata between client and server. -This doc shows how to send and receive metadata in gRPC-go. - -## Background - -Four kinds of service method: - -- [Unary RPC](https://grpc.io/docs/guides/concepts.html#unary-rpc) -- [Server streaming RPC](https://grpc.io/docs/guides/concepts.html#server-streaming-rpc) -- [Client streaming RPC](https://grpc.io/docs/guides/concepts.html#client-streaming-rpc) -- [Bidirectional streaming RPC](https://grpc.io/docs/guides/concepts.html#bidirectional-streaming-rpc) - -And concept of [metadata](https://grpc.io/docs/guides/concepts.html#metadata). - -## Constructing metadata - -A metadata can be created using package [metadata](https://godoc.org/google.golang.org/grpc/metadata). -The type MD is actually a map from string to a list of strings: - -```go -type MD map[string][]string -``` - -Metadata can be read like a normal map. -Note that the value type of this map is `[]string`, -so that users can attach multiple values using a single key. - -### Creating a new metadata - -A metadata can be created from a `map[string]string` using function `New`: - -```go -md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"}) -``` - -Another way is to use `Pairs`. -Values with the same key will be merged into a list: - -```go -md := metadata.Pairs( - "key1", "val1", - "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"} - "key2", "val2", -) -``` - -__Note:__ all the keys will be automatically converted to lowercase, -so "key1" and "kEy1" will be the same key and their values will be merged into the same list. -This happens for both `New` and `Pairs`. - -### Storing binary data in metadata - -In metadata, keys are always strings. But values can be strings or binary data. -To store binary data value in metadata, simply add "-bin" suffix to the key. -The values with "-bin" suffixed keys will be encoded when creating the metadata: - -```go -md := metadata.Pairs( - "key", "string value", - "key-bin", string([]byte{96, 102}), // this binary data will be encoded (base64) before sending - // and will be decoded after being transferred. -) -``` - -## Retrieving metadata from context - -Metadata can be retrieved from context using `FromIncomingContext`: - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.SomeRequest) (*pb.SomeResponse, err) { - md, ok := metadata.FromIncomingContext(ctx) - // do something with metadata -} -``` - -## Sending and receiving metadata - client side - -[//]: # "TODO: uncomment next line after example source added" -[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)." - -### Sending metadata - -There are two ways to send metadata to the server. The recommended way is to append kv pairs to the context using -`AppendToOutgoingContext`. This can be used with or without existing metadata on the context. When there is no prior -metadata, metadata is added; when metadata already exists on the context, kv pairs are merged in. - -```go -// create a new context with some metadata -ctx := metadata.AppendToOutgoingContext(ctx, "k1", "v1", "k1", "v2", "k2", "v3") - -// later, add some more metadata to the context (e.g. in an interceptor) -ctx := metadata.AppendToOutgoingContext(ctx, "k3", "v4") - -// make unary RPC -response, err := client.SomeRPC(ctx, someRequest) - -// or make streaming RPC -stream, err := client.SomeStreamingRPC(ctx) -``` - -Alternatively, metadata may be attached to the context using `NewOutgoingContext`. However, this -replaces any existing metadata in the context, so care must be taken to preserve the existing -metadata if desired. This is slower than using `AppendToOutgoingContext`. An example of this -is below: - -```go -// create a new context with some metadata -md := metadata.Pairs("k1", "v1", "k1", "v2", "k2", "v3") -ctx := metadata.NewOutgoingContext(context.Background(), md) - -// later, add some more metadata to the context (e.g. in an interceptor) -md, _ := metadata.FromOutgoingContext(ctx) -newMD := metadata.Pairs("k3", "v3") -ctx = metadata.NewContext(ctx, metadata.Join(metadata.New(send), newMD)) - -// make unary RPC -response, err := client.SomeRPC(ctx, someRequest) - -// or make streaming RPC -stream, err := client.SomeStreamingRPC(ctx) -``` - -### Receiving metadata - -Metadata that a client can receive includes header and trailer. - -#### Unary call - -Header and trailer sent along with a unary call can be retrieved using function [Header](https://godoc.org/google.golang.org/grpc#Header) and [Trailer](https://godoc.org/google.golang.org/grpc#Trailer) in [CallOption](https://godoc.org/google.golang.org/grpc#CallOption): - -```go -var header, trailer metadata.MD // variable to store header and trailer -r, err := client.SomeRPC( - ctx, - someRequest, - grpc.Header(&header), // will retrieve header - grpc.Trailer(&trailer), // will retrieve trailer -) - -// do something with header and trailer -``` - -#### Streaming call - -For streaming calls including: - -- Server streaming RPC -- Client streaming RPC -- Bidirectional streaming RPC - -Header and trailer can be retrieved from the returned stream using function `Header` and `Trailer` in interface [ClientStream](https://godoc.org/google.golang.org/grpc#ClientStream): - -```go -stream, err := client.SomeStreamingRPC(ctx) - -// retrieve header -header, err := stream.Header() - -// retrieve trailer -trailer := stream.Trailer() - -``` - -## Sending and receiving metadata - server side - -[//]: # "TODO: uncomment next line after example source added" -[//]: # "Real metadata sending and receiving examples are available [here](TODO:example_dir)." - -### Receiving metadata - -To read metadata sent by the client, the server needs to retrieve it from RPC context. -If it is a unary call, the RPC handler's context can be used. -For streaming calls, the server needs to get context from the stream. - -#### Unary call - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.someRequest) (*pb.someResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - // do something with metadata -} -``` - -#### Streaming call - -```go -func (s *server) SomeStreamingRPC(stream pb.Service_SomeStreamingRPCServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) // get context from stream - // do something with metadata -} -``` - -### Sending metadata - -#### Unary call - -To send header and trailer to client in unary call, the server can call [SendHeader](https://godoc.org/google.golang.org/grpc#SendHeader) and [SetTrailer](https://godoc.org/google.golang.org/grpc#SetTrailer) functions in module [grpc](https://godoc.org/google.golang.org/grpc). -These two functions take a context as the first parameter. -It should be the RPC handler's context or one derived from it: - -```go -func (s *server) SomeRPC(ctx context.Context, in *pb.someRequest) (*pb.someResponse, error) { - // create and send header - header := metadata.Pairs("header-key", "val") - grpc.SendHeader(ctx, header) - // create and set trailer - trailer := metadata.Pairs("trailer-key", "val") - grpc.SetTrailer(ctx, trailer) -} -``` - -#### Streaming call - -For streaming calls, header and trailer can be sent using function `SendHeader` and `SetTrailer` in interface [ServerStream](https://godoc.org/google.golang.org/grpc#ServerStream): - -```go -func (s *server) SomeStreamingRPC(stream pb.Service_SomeStreamingRPCServer) error { - // create and send header - header := metadata.Pairs("header-key", "val") - stream.SendHeader(header) - // create and set trailer - trailer := metadata.Pairs("trailer-key", "val") - stream.SetTrailer(trailer) -} -``` diff --git a/examples/google.golang.org/grpc/Documentation/log_levels.md b/examples/google.golang.org/grpc/Documentation/log_levels.md deleted file mode 100755 index 6839f6d..0000000 --- a/examples/google.golang.org/grpc/Documentation/log_levels.md +++ /dev/null @@ -1,49 +0,0 @@ -# Log Levels - -This document describes the different log levels supported by the grpc-go -library, and under what conditions they should be used. - -### Info - -Info messages are for informational purposes and may aid in the debugging of -applications or the gRPC library. - -Examples: -- The name resolver received an update. -- The balancer updated its picker. -- Significant gRPC state is changing. - -At verbosity of 0 (the default), any single info message should not be output -more than once every 5 minutes under normal operation. - -### Warning - -Warning messages indicate problems that are non-fatal for the application, but -could lead to unexpected behavior or subsequent errors. - -Examples: -- Resolver could not resolve target name. -- Error received while connecting to a server. -- Lost or corrupt connection with remote endpoint. - -### Error - -Error messages represent errors in the usage of gRPC that cannot be returned to -the application as errors, or internal gRPC-Go errors that are recoverable. - -Internal errors are detected during gRPC tests and will result in test failures. - -Examples: -- Invalid arguments passed to a function that cannot return an error. -- An internal error that cannot be returned or would be inappropriate to return - to the user. - -### Fatal - -Fatal errors are severe internal errors that are unrecoverable. These lead -directly to panics, and are avoided as much as possible. - -Example: -- Internal invariant was violated. -- User attempted an action that cannot return an error gracefully, but would - lead to an invalid state if performed. diff --git a/examples/google.golang.org/grpc/Documentation/rpc-errors.md b/examples/google.golang.org/grpc/Documentation/rpc-errors.md deleted file mode 100755 index 27e74e0..0000000 --- a/examples/google.golang.org/grpc/Documentation/rpc-errors.md +++ /dev/null @@ -1,68 +0,0 @@ -# RPC Errors - -All service method handlers should return `nil` or errors from the -`status.Status` type. Clients have direct access to the errors. - -Upon encountering an error, a gRPC server method handler should create a -`status.Status`. In typical usage, one would use [status.New][new-status] -passing in an appropriate [codes.Code][code] as well as a description of the -error to produce a `status.Status`. Calling [status.Err][status-err] converts -the `status.Status` type into an `error`. As a convenience method, there is also -[status.Error][status-error] which obviates the conversion step. Compare: - -``` -st := status.New(codes.NotFound, "some description") -err := st.Err() - -// vs. - -err := status.Error(codes.NotFound, "some description") -``` - -## Adding additional details to errors - -In some cases, it may be necessary to add details for a particular error on the -server side. The [status.WithDetails][with-details] method exists for this -purpose. Clients may then read those details by first converting the plain -`error` type back to a [status.Status][status] and then using -[status.Details][details]. - -## Example - -The [example][example] demonstrates the API discussed above and shows how to add -information about rate limits to the error message using `status.Status`. - -To run the example, first start the server: - -``` -$ go run examples/rpc_errors/server/main.go -``` - -In a separate session, run the client: - -``` -$ go run examples/rpc_errors/client/main.go -``` - -On the first run of the client, all is well: - -``` -2018/03/12 19:39:33 Greeting: Hello world -``` - -Upon running the client a second time, the client exceeds the rate limit and -receives an error with details: - -``` -2018/03/19 16:42:01 Quota failure: violations: -exit status 1 -``` - -[status]: https://godoc.org/google.golang.org/grpc/status#Status -[new-status]: https://godoc.org/google.golang.org/grpc/status#New -[code]: https://godoc.org/google.golang.org/grpc/codes#Code -[with-details]: https://godoc.org/google.golang.org/grpc/status#Status.WithDetails -[details]: https://godoc.org/google.golang.org/grpc/status#Status.Details -[status-err]: https://godoc.org/google.golang.org/grpc/status#Status.Err -[status-error]: https://godoc.org/google.golang.org/grpc/status#Error -[example]: https://github.com/grpc/grpc-go/blob/master/examples/rpc_errors diff --git a/examples/google.golang.org/grpc/Documentation/server-reflection-tutorial.md b/examples/google.golang.org/grpc/Documentation/server-reflection-tutorial.md deleted file mode 100755 index ca8e30c..0000000 --- a/examples/google.golang.org/grpc/Documentation/server-reflection-tutorial.md +++ /dev/null @@ -1,152 +0,0 @@ -# gRPC Server Reflection Tutorial - -gRPC Server Reflection provides information about publicly-accessible gRPC -services on a server, and assists clients at runtime to construct RPC -requests and responses without precompiled service information. It is used by -gRPC CLI, which can be used to introspect server protos and send/receive test -RPCs. - -## Enable Server Reflection - -gRPC-go Server Reflection is implemented in package [reflection](https://github.com/grpc/grpc-go/tree/master/reflection). To enable server reflection, you need to import this package and register reflection service on your gRPC server. - -For example, to enable server reflection in `example/helloworld`, we need to make the following changes: - -```diff ---- a/examples/helloworld/greeter_server/main.go -+++ b/examples/helloworld/greeter_server/main.go -@@ -40,6 +40,7 @@ import ( - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" -+ "google.golang.org/grpc/reflection" - ) - - const ( -@@ -61,6 +62,8 @@ func main() { - } - s := grpc.NewServer() - pb.RegisterGreeterServer(s, &server{}) -+ // Register reflection service on gRPC server. -+ reflection.Register(s) - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -``` - -We have made this change in `example/helloworld`, and we will use it as an example to show the use of gRPC server reflection and gRPC CLI in this tutorial. - -## gRPC CLI - -After enabling Server Reflection in a server application, you can use gRPC CLI to check its services. -gRPC CLI is only available in c++. Instructions on how to use gRPC CLI can be found at [command_line_tool.md](https://github.com/grpc/grpc/blob/master/doc/command_line_tool.md). - -To build gRPC CLI: - -```sh -git clone https://github.com/grpc/grpc -cd grpc -make grpc_cli -cd bins/opt # grpc_cli is in directory bins/opt/ -``` - -## Use gRPC CLI to check services - -First, start the helloworld server in grpc-go directory: - -```sh -$ cd -$ go run examples/helloworld/greeter_server/main.go -``` - -Open a new terminal and make sure you are in the directory where grpc_cli lives: - -```sh -$ cd /bins/opt -``` - -### List services - -`grpc_cli ls` command lists services and methods exposed at a given port: - -- List all the services exposed at a given port - - ```sh - $ ./grpc_cli ls localhost:50051 - ``` - - output: - ```sh - helloworld.Greeter - grpc.reflection.v1alpha.ServerReflection - ``` - -- List one service with details - - `grpc_cli ls` command inspects a service given its full name (in the format of - \.\). It can print information with a long listing format - when `-l` flag is set. This flag can be used to get more details about a - service. - - ```sh - $ ./grpc_cli ls localhost:50051 helloworld.Greeter -l - ``` - - output: - ```sh - filename: helloworld.proto - package: helloworld; - service Greeter { - rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {} - } - - ``` - -### List methods - -- List one method with details - - `grpc_cli ls` command also inspects a method given its full name (in the - format of \.\.\). - - ```sh - $ ./grpc_cli ls localhost:50051 helloworld.Greeter.SayHello -l - ``` - - output: - ```sh - rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {} - ``` - -### Inspect message types - -We can use`grpc_cli type` command to inspect request/response types given the -full name of the type (in the format of \.\). - -- Get information about the request type - - ```sh - $ ./grpc_cli type localhost:50051 helloworld.HelloRequest - ``` - - output: - ```sh - message HelloRequest { - optional string name = 1[json_name = "name"]; - } - ``` - -### Call a remote method - -We can send RPCs to a server and get responses using `grpc_cli call` command. - -- Call a unary method - - ```sh - $ ./grpc_cli call localhost:50051 SayHello "name: 'gRPC CLI'" - ``` - - output: - ```sh - message: "Hello gRPC CLI" - ``` diff --git a/examples/google.golang.org/grpc/Documentation/stickiness.md b/examples/google.golang.org/grpc/Documentation/stickiness.md deleted file mode 100755 index e5db053..0000000 --- a/examples/google.golang.org/grpc/Documentation/stickiness.md +++ /dev/null @@ -1,46 +0,0 @@ -# Stickiness - -With load balancer, each RPC pick a different backend based on the load -balancing policy. Stickiness policies try to preserve peers for the duration of -a session, so that RPCs with the same stickiness key will be directed to the -same server. - -Note that there's only "soft" stickiness now, which means RPCs with the same -stickienss key could still be sent to different servers. If stickiness is -critical for the system, server side application level handling is still -necessary. - -## Stickiness Key - -A stickiness key works as the session id. RPCs with the same stickiness key will -be assigned to the same backend. - -Stickiness key is set as part of the custom metadata. - -## Enable stickiness - -Stickiness can be enabled by setting `stickinessKey` field in [service -config](https://github.com/grpc/grpc/blob/master/doc/service_config.md). - -```json -{ - "stickinessKey": "sessionid" -} -``` - -The value `sesseionid` will be used as the key of the metadata entry that -defines the stickiness key for each RPC. - -## Send RPC with stickiness - -To set the stickiness key for an RPC, set the corresponding metadata. The -following RPC will be sent with stickiness key `session1`. - -```go -// "sessionid" is the metadata key specified by service config, "session1" is -// the stickiness key for this RPC. -md := metadata.Paris("sessionid", "session1") - -ctx := metadata.NewOutgoingContext(context.Background(), md) -resp, err := client.SomeRPC(ctx, req) -``` diff --git a/examples/google.golang.org/grpc/Documentation/versioning.md b/examples/google.golang.org/grpc/Documentation/versioning.md deleted file mode 100755 index 03e868c..0000000 --- a/examples/google.golang.org/grpc/Documentation/versioning.md +++ /dev/null @@ -1,34 +0,0 @@ -# Versioning and Releases - -Note: This document references terminology defined at http://semver.org. - -## Release Frequency - -Regular MINOR releases of gRPC-Go are performed every six weeks. Patch releases -to the previous two MINOR releases may be performed on demand or if serious -security problems are discovered. - -## Versioning Policy - -The gRPC-Go versioning policy follows the Semantic Versioning 2.0.0 -specification, with the following exceptions: - -- A MINOR version will not _necessarily_ add new functionality. - -- MINOR releases will not break backward compatibility, except in the following -circumstances: - - - An API was marked as EXPERIMENTAL upon its introduction. - - An API was marked as DEPRECATED in the initial MAJOR release. - - An API is inherently flawed and cannot provide correct or secure behavior. - - In these cases, APIs MAY be changed or removed without a MAJOR release. -Otherwise, backward compatibility will be preserved by MINOR releases. - - For an API marked as DEPRECATED, an alternative will be available (if -appropriate) for at least three months prior to its removal. - -## Release History - -Please see our release history on GitHub: -https://github.com/grpc/grpc-go/releases diff --git a/examples/google.golang.org/grpc/LICENSE b/examples/google.golang.org/grpc/LICENSE deleted file mode 100755 index d645695..0000000 --- a/examples/google.golang.org/grpc/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/examples/google.golang.org/grpc/Makefile b/examples/google.golang.org/grpc/Makefile deleted file mode 100755 index 6f393a8..0000000 --- a/examples/google.golang.org/grpc/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -all: vet test testrace - -deps: - go get -d -v google.golang.org/grpc/... - -updatedeps: - go get -d -v -u -f google.golang.org/grpc/... - -testdeps: - go get -d -v -t google.golang.org/grpc/... - -updatetestdeps: - go get -d -v -t -u -f google.golang.org/grpc/... - -build: deps - go build google.golang.org/grpc/... - -proto: - @ if ! which protoc > /dev/null; then \ - echo "error: protoc not installed" >&2; \ - exit 1; \ - fi - go generate google.golang.org/grpc/... - -vet: - ./vet.sh - -test: testdeps - go test -cpu 1,4 -timeout 5m google.golang.org/grpc/... - -testrace: testdeps - go test -race -cpu 1,4 -timeout 7m google.golang.org/grpc/... - -clean: - go clean -i google.golang.org/grpc/... - -.PHONY: \ - all \ - deps \ - updatedeps \ - testdeps \ - updatetestdeps \ - build \ - proto \ - vet \ - test \ - testrace \ - clean diff --git a/examples/google.golang.org/grpc/README.md b/examples/google.golang.org/grpc/README.md deleted file mode 100755 index 789adfd..0000000 --- a/examples/google.golang.org/grpc/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# gRPC-Go - -[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc) [![GoReportCard](https://goreportcard.com/badge/grpc/grpc-go)](https://goreportcard.com/report/github.com/grpc/grpc-go) - -The Go implementation of [gRPC](https://grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start: Go](https://grpc.io/docs/quickstart/go.html) guide. - -Installation ------------- - -To install this package, you need to install Go and setup your Go workspace on your computer. The simplest way to install the library is to run: - -``` -$ go get -u google.golang.org/grpc -``` - -Prerequisites -------------- - -This requires Go 1.6 or later. Go 1.7 will be required soon. - -Constraints ------------ -The grpc package should only depend on standard Go packages and a small number of exceptions. If your contribution introduces new dependencies which are NOT in the [list](http://godoc.org/google.golang.org/grpc?imports), you need a discussion with gRPC-Go authors and consultants. - -Documentation -------------- -See [API documentation](https://godoc.org/google.golang.org/grpc) for package and API descriptions and find examples in the [examples directory](examples/). - -Performance ------------ -See the current benchmarks for some of the languages supported in [this dashboard](https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5652536396611584&widget=490377658&container=1286539696). - -Status ------- -General Availability [Google Cloud Platform Launch Stages](https://cloud.google.com/terms/launch-stages). - -FAQ ---- - -#### Compiling error, undefined: grpc.SupportPackageIsVersion - -Please update proto package, gRPC package and rebuild the proto files: - - `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}` - - `go get -u google.golang.org/grpc` - - `protoc --go_out=plugins=grpc:. *.proto` diff --git a/examples/google.golang.org/grpc/backoff.go b/examples/google.golang.org/grpc/backoff.go deleted file mode 100755 index fa31565..0000000 --- a/examples/google.golang.org/grpc/backoff.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// See internal/backoff package for the backoff implementation. This file is -// kept for the exported types and API backward compatility. - -package grpc - -import ( - "time" -) - -// DefaultBackoffConfig uses values specified for backoff in -// https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. -var DefaultBackoffConfig = BackoffConfig{ - MaxDelay: 120 * time.Second, -} - -// BackoffConfig defines the parameters for the default gRPC backoff strategy. -type BackoffConfig struct { - // MaxDelay is the upper bound of backoff delay. - MaxDelay time.Duration -} diff --git a/examples/google.golang.org/grpc/balancer.go b/examples/google.golang.org/grpc/balancer.go deleted file mode 100755 index e173016..0000000 --- a/examples/google.golang.org/grpc/balancer.go +++ /dev/null @@ -1,416 +0,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. - * - */ - -package grpc - -import ( - "fmt" - "net" - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/status" -) - -// Address represents a server the client connects to. -// -// Deprecated: please use package balancer. -type Address struct { - // Addr is the server address on which a connection will be established. - Addr string - // Metadata is the information associated with Addr, which may be used - // to make load balancing decision. - Metadata interface{} -} - -// BalancerConfig specifies the configurations for Balancer. -// -// Deprecated: please use package balancer. -type BalancerConfig struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. - DialCreds credentials.TransportCredentials - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. - Dialer func(context.Context, string) (net.Conn, error) -} - -// BalancerGetOptions configures a Get call. -// -// Deprecated: please use package balancer. -type BalancerGetOptions struct { - // BlockingWait specifies whether Get should block when there is no - // connected address. - BlockingWait bool -} - -// Balancer chooses network addresses for RPCs. -// -// Deprecated: please use package balancer. -type Balancer interface { - // Start does the initialization work to bootstrap a Balancer. For example, - // this function may start the name resolution and watch the updates. It will - // be called when dialing. - Start(target string, config BalancerConfig) error - // Up informs the Balancer that gRPC has a connection to the server at - // addr. It returns down which is called once the connection to addr gets - // lost or closed. - // TODO: It is not clear how to construct and take advantage of the meaningful error - // parameter for down. Need realistic demands to guide. - Up(addr Address) (down func(error)) - // Get gets the address of a server for the RPC corresponding to ctx. - // i) If it returns a connected address, gRPC internals issues the RPC on the - // connection to this address; - // ii) If it returns an address on which the connection is under construction - // (initiated by Notify(...)) but not connected, gRPC internals - // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or - // Shutdown state; - // or - // * issues RPC on the connection otherwise. - // iii) If it returns an address on which the connection does not exist, gRPC - // internals treats it as an error and will fail the corresponding RPC. - // - // Therefore, the following is the recommended rule when writing a custom Balancer. - // If opts.BlockingWait is true, it should return a connected address or - // block if there is no connected address. It should respect the timeout or - // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast - // RPCs), it should return an address it has notified via Notify(...) immediately - // instead of blocking. - // - // The function returns put which is called once the rpc has completed or failed. - // put can collect and report RPC stats to a remote load balancer. - // - // This function should only return the errors Balancer cannot recover by itself. - // gRPC internals will fail the RPC if an error is returned. - Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) - // Notify returns a channel that is used by gRPC internals to watch the addresses - // gRPC needs to connect. The addresses might be from a name resolver or remote - // load balancer. gRPC internals will compare it with the existing connected - // addresses. If the address Balancer notified is not in the existing connected - // addresses, gRPC starts to connect the address. If an address in the existing - // connected addresses is not in the notification list, the corresponding connection - // is shutdown gracefully. Otherwise, there are no operations to take. Note that - // the Address slice must be the full list of the Addresses which should be connected. - // It is NOT delta. - Notify() <-chan []Address - // Close shuts down the balancer. - Close() error -} - -// downErr implements net.Error. It is constructed by gRPC internals and passed to the down -// call of Balancer. -type downErr struct { - timeout bool - temporary bool - desc string -} - -func (e downErr) Error() string { return e.desc } -func (e downErr) Timeout() bool { return e.timeout } -func (e downErr) Temporary() bool { return e.temporary } - -func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr { - return downErr{ - timeout: timeout, - temporary: temporary, - desc: fmt.Sprintf(format, a...), - } -} - -// RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch -// the name resolution updates and updates the addresses available correspondingly. -// -// Deprecated: please use package balancer/roundrobin. -func RoundRobin(r naming.Resolver) Balancer { - return &roundRobin{r: r} -} - -type addrInfo struct { - addr Address - connected bool -} - -type roundRobin struct { - r naming.Resolver - w naming.Watcher - addrs []*addrInfo // all the addresses the client should potentially connect - mu sync.Mutex - addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to. - next int // index of the next address to return for Get() - waitCh chan struct{} // the channel to block when there is no connected address available - done bool // The Balancer is closed. -} - -func (rr *roundRobin) watchAddrUpdates() error { - updates, err := rr.w.Next() - if err != nil { - grpclog.Warningf("grpc: the naming watcher stops working due to %v.", err) - return err - } - rr.mu.Lock() - defer rr.mu.Unlock() - for _, update := range updates { - addr := Address{ - Addr: update.Addr, - Metadata: update.Metadata, - } - switch update.Op { - case naming.Add: - var exist bool - for _, v := range rr.addrs { - if addr == v.addr { - exist = true - grpclog.Infoln("grpc: The name resolver wanted to add an existing address: ", addr) - break - } - } - if exist { - continue - } - rr.addrs = append(rr.addrs, &addrInfo{addr: addr}) - case naming.Delete: - for i, v := range rr.addrs { - if addr == v.addr { - copy(rr.addrs[i:], rr.addrs[i+1:]) - rr.addrs = rr.addrs[:len(rr.addrs)-1] - break - } - } - default: - grpclog.Errorln("Unknown update.Op ", update.Op) - } - } - // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified. - open := make([]Address, len(rr.addrs)) - for i, v := range rr.addrs { - open[i] = v.addr - } - if rr.done { - return ErrClientConnClosing - } - select { - case <-rr.addrCh: - default: - } - rr.addrCh <- open - return nil -} - -func (rr *roundRobin) Start(target string, config BalancerConfig) error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return ErrClientConnClosing - } - if rr.r == nil { - // If there is no name resolver installed, it is not needed to - // do name resolution. In this case, target is added into rr.addrs - // as the only address available and rr.addrCh stays nil. - rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}}) - return nil - } - w, err := rr.r.Resolve(target) - if err != nil { - return err - } - rr.w = w - rr.addrCh = make(chan []Address, 1) - go func() { - for { - if err := rr.watchAddrUpdates(); err != nil { - return - } - } - }() - return nil -} - -// Up sets the connected state of addr and sends notification if there are pending -// Get() calls. -func (rr *roundRobin) Up(addr Address) func(error) { - rr.mu.Lock() - defer rr.mu.Unlock() - var cnt int - for _, a := range rr.addrs { - if a.addr == addr { - if a.connected { - return nil - } - a.connected = true - } - if a.connected { - cnt++ - } - } - // addr is only one which is connected. Notify the Get() callers who are blocking. - if cnt == 1 && rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - return func(err error) { - rr.down(addr, err) - } -} - -// down unsets the connected state of addr. -func (rr *roundRobin) down(addr Address, err error) { - rr.mu.Lock() - defer rr.mu.Unlock() - for _, a := range rr.addrs { - if addr == a.addr { - a.connected = false - break - } - } -} - -// Get returns the next addr in the rotation. -func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - var ch chan struct{} - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - if !opts.BlockingWait { - if len(rr.addrs) == 0 { - rr.mu.Unlock() - err = status.Errorf(codes.Unavailable, "there is no address available") - return - } - // Returns the next addr on rr.addrs for failfast RPCs. - addr = rr.addrs[rr.next].addr - rr.next++ - rr.mu.Unlock() - return - } - // Wait on rr.waitCh for non-failfast RPCs. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - for { - select { - case <-ctx.Done(): - err = ctx.Err() - return - case <-ch: - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - // The newly added addr got removed by Down() again. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - } - } -} - -func (rr *roundRobin) Notify() <-chan []Address { - return rr.addrCh -} - -func (rr *roundRobin) Close() error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return errBalancerClosed - } - rr.done = true - if rr.w != nil { - rr.w.Close() - } - if rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - if rr.addrCh != nil { - close(rr.addrCh) - } - return nil -} - -// pickFirst is used to test multi-addresses in one addrConn in which all addresses share the same addrConn. -// It is a wrapper around roundRobin balancer. The logic of all methods works fine because balancer.Get() -// returns the only address Up by resetTransport(). -type pickFirst struct { - *roundRobin -} - -func pickFirstBalancerV1(r naming.Resolver) Balancer { - return &pickFirst{&roundRobin{r: r}} -} diff --git a/examples/google.golang.org/grpc/balancer/balancer.go b/examples/google.golang.org/grpc/balancer/balancer.go deleted file mode 100755 index f9d83c2..0000000 --- a/examples/google.golang.org/grpc/balancer/balancer.go +++ /dev/null @@ -1,270 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package balancer defines APIs for load balancing in gRPC. -// All APIs in this package are experimental. -package balancer - -import ( - "errors" - "net" - "strings" - - "golang.org/x/net/context" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/resolver" -) - -var ( - // m is a map from name to balancer builder. - m = make(map[string]Builder) -) - -// Register registers the balancer builder to the balancer map. b.Name -// (lowercased) will be used as the name registered with this builder. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Balancers are -// registered with the same name, the one registered last will take effect. -func Register(b Builder) { - m[strings.ToLower(b.Name())] = b -} - -// Get returns the resolver builder registered with the given name. -// Note that the compare is done in a case-insenstive fashion. -// If no builder is register with the name, nil will be returned. -func Get(name string) Builder { - if b, ok := m[strings.ToLower(name)]; ok { - return b - } - return nil -} - -// SubConn represents a gRPC sub connection. -// Each sub connection contains a list of addresses. gRPC will -// try to connect to them (in sequence), and stop trying the -// remainder once one connection is successful. -// -// The reconnect backoff will be applied on the list, not a single address. -// For example, try_on_all_addresses -> backoff -> try_on_all_addresses. -// -// All SubConns start in IDLE, and will not try to connect. To trigger -// the connecting, Balancers must call Connect. -// When the connection encounters an error, it will reconnect immediately. -// When the connection becomes IDLE, it will not reconnect unless Connect is -// called. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type SubConn interface { - // UpdateAddresses updates the addresses used in this SubConn. - // gRPC checks if currently-connected address is still in the new list. - // If it's in the list, the connection will be kept. - // If it's not in the list, the connection will gracefully closed, and - // a new connection will be created. - // - // This will trigger a state transition for the SubConn. - UpdateAddresses([]resolver.Address) - // Connect starts the connecting for this SubConn. - Connect() -} - -// NewSubConnOptions contains options to create new SubConn. -type NewSubConnOptions struct{} - -// ClientConn represents a gRPC ClientConn. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type ClientConn interface { - // NewSubConn is called by balancer to create a new SubConn. - // It doesn't block and wait for the connections to be established. - // Behaviors of the SubConn can be controlled by options. - NewSubConn([]resolver.Address, NewSubConnOptions) (SubConn, error) - // RemoveSubConn removes the SubConn from ClientConn. - // The SubConn will be shutdown. - RemoveSubConn(SubConn) - - // UpdateBalancerState is called by balancer to nofity gRPC that some internal - // state in balancer has changed. - // - // gRPC will update the connectivity state of the ClientConn, and will call pick - // on the new picker to pick new SubConn. - UpdateBalancerState(s connectivity.State, p Picker) - - // ResolveNow is called by balancer to notify gRPC to do a name resolving. - ResolveNow(resolver.ResolveNowOption) - - // Target returns the dial target for this ClientConn. - Target() string -} - -// BuildOptions contains additional information for Build. -type BuildOptions struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. - DialCreds credentials.TransportCredentials - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. - Dialer func(context.Context, string) (net.Conn, error) - // ChannelzParentID is the entity parent's channelz unique identification number. - ChannelzParentID int64 -} - -// Builder creates a balancer. -type Builder interface { - // Build creates a new balancer with the ClientConn. - Build(cc ClientConn, opts BuildOptions) Balancer - // Name returns the name of balancers built by this builder. - // It will be used to pick balancers (for example in service config). - Name() string -} - -// PickOptions contains addition information for the Pick operation. -type PickOptions struct{} - -// DoneInfo contains additional information for done. -type DoneInfo struct { - // Err is the rpc error the RPC finished with. It could be nil. - Err error - // BytesSent indicates if any bytes have been sent to the server. - BytesSent bool - // BytesReceived indicates if any byte has been received from the server. - BytesReceived bool -} - -var ( - // ErrNoSubConnAvailable indicates no SubConn is available for pick(). - // gRPC will block the RPC until a new picker is available via UpdateBalancerState(). - ErrNoSubConnAvailable = errors.New("no SubConn is available") - // ErrTransientFailure indicates all SubConns are in TransientFailure. - // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. - ErrTransientFailure = errors.New("all SubConns are in TransientFailure") -) - -// Picker is used by gRPC to pick a SubConn to send an RPC. -// Balancer is expected to generate a new picker from its snapshot every time its -// internal state has changed. -// -// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState(). -type Picker interface { - // Pick returns the SubConn to be used to send the RPC. - // The returned SubConn must be one returned by NewSubConn(). - // - // This functions is expected to return: - // - a SubConn that is known to be READY; - // - ErrNoSubConnAvailable if no SubConn is available, but progress is being - // made (for example, some SubConn is in CONNECTING mode); - // - other errors if no active connecting is happening (for example, all SubConn - // are in TRANSIENT_FAILURE mode). - // - // If a SubConn is returned: - // - If it is READY, gRPC will send the RPC on it; - // - If it is not ready, or becomes not ready after it's returned, gRPC will block - // until UpdateBalancerState() is called and will call pick on the new picker. - // - // If the returned error is not nil: - // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState() - // - If the error is ErrTransientFailure: - // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState() - // is called to pick again; - // - Otherwise, RPC will fail with unavailable error. - // - Else (error is other non-nil error): - // - The RPC will fail with unavailable error. - // - // The returned done() function will be called once the rpc has finished, with the - // final status of that RPC. - // done may be nil if balancer doesn't care about the RPC status. - Pick(ctx context.Context, opts PickOptions) (conn SubConn, done func(DoneInfo), err error) -} - -// Balancer takes input from gRPC, manages SubConns, and collects and aggregates -// the connectivity states. -// -// It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. -// -// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed -// to be called synchronously from the same goroutine. -// There's no guarantee on picker.Pick, it may be called anytime. -type Balancer interface { - // HandleSubConnStateChange is called by gRPC when the connectivity state - // of sc has changed. - // Balancer is expected to aggregate all the state of SubConn and report - // that back to gRPC. - // Balancer should also generate and update Pickers when its internal state has - // been changed by the new state. - HandleSubConnStateChange(sc SubConn, state connectivity.State) - // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to - // balancers. - // Balancer can create new SubConn or remove SubConn with the addresses. - // An empty address slice and a non-nil error will be passed if the resolver returns - // non-nil error to gRPC. - HandleResolvedAddrs([]resolver.Address, error) - // Close closes the balancer. The balancer is not required to call - // ClientConn.RemoveSubConn for its existing SubConns. - Close() -} - -// ConnectivityStateEvaluator takes the connectivity states of multiple SubConns -// and returns one aggregated connectivity state. -// -// It's not thread safe. -type ConnectivityStateEvaluator struct { - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. - numTransientFailure uint64 // Number of addrConns in transientFailure. -} - -// RecordTransition records state change happening in subConn and based on that -// it evaluates what aggregated state should be. -// -// - If at least one SubConn in Ready, the aggregated state is Ready; -// - Else if at least one SubConn in Connecting, the aggregated state is Connecting; -// - Else the aggregated state is TransientFailure. -// -// Idle and Shutdown are not considered. -func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { - // Update counters. - for idx, state := range []connectivity.State{oldState, newState} { - updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. - switch state { - case connectivity.Ready: - cse.numReady += updateVal - case connectivity.Connecting: - cse.numConnecting += updateVal - case connectivity.TransientFailure: - cse.numTransientFailure += updateVal - } - } - - // Evaluate. - if cse.numReady > 0 { - return connectivity.Ready - } - if cse.numConnecting > 0 { - return connectivity.Connecting - } - return connectivity.TransientFailure -} diff --git a/examples/google.golang.org/grpc/balancer/base/balancer.go b/examples/google.golang.org/grpc/balancer/base/balancer.go deleted file mode 100755 index 23d1351..0000000 --- a/examples/google.golang.org/grpc/balancer/base/balancer.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package base - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -type baseBuilder struct { - name string - pickerBuilder PickerBuilder -} - -func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - return &baseBalancer{ - cc: cc, - pickerBuilder: bb.pickerBuilder, - - subConns: make(map[resolver.Address]balancer.SubConn), - scStates: make(map[balancer.SubConn]connectivity.State), - csEvltr: &connectivityStateEvaluator{}, - // Initialize picker to a picker that always return - // ErrNoSubConnAvailable, because when state of a SubConn changes, we - // may call UpdateBalancerState with this picker. - picker: NewErrPicker(balancer.ErrNoSubConnAvailable), - } -} - -func (bb *baseBuilder) Name() string { - return bb.name -} - -type baseBalancer struct { - cc balancer.ClientConn - pickerBuilder PickerBuilder - - csEvltr *connectivityStateEvaluator - state connectivity.State - - subConns map[resolver.Address]balancer.SubConn - scStates map[balancer.SubConn]connectivity.State - picker balancer.Picker -} - -func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - if err != nil { - grpclog.Infof("base.baseBalancer: HandleResolvedAddrs called with error %v", err) - return - } - grpclog.Infoln("base.baseBalancer: got new resolved addresses: ", addrs) - // addrsSet is the set converted from addrs, it's used for quick lookup of an address. - addrsSet := make(map[resolver.Address]struct{}) - for _, a := range addrs { - addrsSet[a] = struct{}{} - if _, ok := b.subConns[a]; !ok { - // a is a new address (not existing in b.subConns). - sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("base.baseBalancer: failed to create new SubConn: %v", err) - continue - } - b.subConns[a] = sc - b.scStates[sc] = connectivity.Idle - sc.Connect() - } - } - for a, sc := range b.subConns { - // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - b.cc.RemoveSubConn(sc) - delete(b.subConns, a) - // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. - } - } -} - -// regeneratePicker takes a snapshot of the balancer, and generates a picker -// from it. The picker is -// - errPicker with ErrTransientFailure if the balancer is in TransientFailure, -// - built by the pickerBuilder with all READY SubConns otherwise. -func (b *baseBalancer) regeneratePicker() { - if b.state == connectivity.TransientFailure { - b.picker = NewErrPicker(balancer.ErrTransientFailure) - return - } - readySCs := make(map[resolver.Address]balancer.SubConn) - - // Filter out all ready SCs from full subConn map. - for addr, sc := range b.subConns { - if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { - readySCs[addr] = sc - } - } - b.picker = b.pickerBuilder.Build(readySCs) -} - -func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s) - oldS, ok := b.scStates[sc] - if !ok { - grpclog.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) - return - } - b.scStates[sc] = s - switch s { - case connectivity.Idle: - sc.Connect() - case connectivity.Shutdown: - // When an address was removed by resolver, b called RemoveSubConn but - // kept the sc's state in scStates. Remove state for this sc here. - delete(b.scStates, sc) - } - - oldAggrState := b.state - b.state = b.csEvltr.recordTransition(oldS, s) - - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure - if (s == connectivity.Ready) != (oldS == connectivity.Ready) || - (b.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { - b.regeneratePicker() - } - - b.cc.UpdateBalancerState(b.state, b.picker) -} - -// Close is a nop because base balancer doesn't have internal state to clean up, -// and it doesn't need to call RemoveSubConn for the SubConns. -func (b *baseBalancer) Close() { -} - -// NewErrPicker returns a picker that always returns err on Pick(). -func NewErrPicker(err error) balancer.Picker { - return &errPicker{err: err} -} - -type errPicker struct { - err error // Pick() always returns this err. -} - -func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// connectivityStateEvaluator gets updated by addrConns when their -// states transition, based on which it evaluates the state of -// ClientConn. -type connectivityStateEvaluator struct { - numReady uint64 // Number of addrConns in ready state. - numConnecting uint64 // Number of addrConns in connecting state. - numTransientFailure uint64 // Number of addrConns in transientFailure. -} - -// recordTransition records state change happening in every subConn and based on -// that it evaluates what aggregated state should be. -// It can only transition between Ready, Connecting and TransientFailure. Other states, -// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection -// before any subConn is created ClientConn is in idle state. In the end when ClientConn -// closes it is in Shutdown state. -// -// recordTransition should only be called synchronously from the same goroutine. -func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { - // Update counters. - for idx, state := range []connectivity.State{oldState, newState} { - updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. - switch state { - case connectivity.Ready: - cse.numReady += updateVal - case connectivity.Connecting: - cse.numConnecting += updateVal - case connectivity.TransientFailure: - cse.numTransientFailure += updateVal - } - } - - // Evaluate. - if cse.numReady > 0 { - return connectivity.Ready - } - if cse.numConnecting > 0 { - return connectivity.Connecting - } - return connectivity.TransientFailure -} diff --git a/examples/google.golang.org/grpc/balancer/base/base.go b/examples/google.golang.org/grpc/balancer/base/base.go deleted file mode 100755 index 012ace2..0000000 --- a/examples/google.golang.org/grpc/balancer/base/base.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package base defines a balancer base that can be used to build balancers with -// different picking algorithms. -// -// The base balancer creates a new SubConn for each resolved address. The -// provided picker will only be notified about READY SubConns. -// -// This package is the base of round_robin balancer, its purpose is to be used -// to build round_robin like balancers with complex picking algorithms. -// Balancers with more complicated logic should try to implement a balancer -// builder from scratch. -// -// All APIs in this package are experimental. -package base - -import ( - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/resolver" -) - -// PickerBuilder creates balancer.Picker. -type PickerBuilder interface { - // Build takes a slice of ready SubConns, and returns a picker that will be - // used by gRPC to pick a SubConn. - Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker -} - -// NewBalancerBuilder returns a balancer builder. The balancers -// built by this builder will use the picker builder to build pickers. -func NewBalancerBuilder(name string, pb PickerBuilder) balancer.Builder { - return &baseBuilder{ - name: name, - pickerBuilder: pb, - } -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go b/examples/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go deleted file mode 100755 index d08bffc..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go +++ /dev/null @@ -1,832 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/lb/v1/load_balancer.proto - -package grpc_lb_v1 // import "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type LoadBalanceRequest struct { - // Types that are valid to be assigned to LoadBalanceRequestType: - // *LoadBalanceRequest_InitialRequest - // *LoadBalanceRequest_ClientStats - LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } -func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceRequest) ProtoMessage() {} -func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{0} -} -func (m *LoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceRequest.Unmarshal(m, b) -} -func (m *LoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceRequest.Merge(dst, src) -} -func (m *LoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_LoadBalanceRequest.Size(m) -} -func (m *LoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceRequest proto.InternalMessageInfo - -type isLoadBalanceRequest_LoadBalanceRequestType interface { - isLoadBalanceRequest_LoadBalanceRequestType() -} - -type LoadBalanceRequest_InitialRequest struct { - InitialRequest *InitialLoadBalanceRequest `protobuf:"bytes,1,opt,name=initial_request,json=initialRequest,proto3,oneof"` -} -type LoadBalanceRequest_ClientStats struct { - ClientStats *ClientStats `protobuf:"bytes,2,opt,name=client_stats,json=clientStats,proto3,oneof"` -} - -func (*LoadBalanceRequest_InitialRequest) isLoadBalanceRequest_LoadBalanceRequestType() {} -func (*LoadBalanceRequest_ClientStats) isLoadBalanceRequest_LoadBalanceRequestType() {} - -func (m *LoadBalanceRequest) GetLoadBalanceRequestType() isLoadBalanceRequest_LoadBalanceRequestType { - if m != nil { - return m.LoadBalanceRequestType - } - return nil -} - -func (m *LoadBalanceRequest) GetInitialRequest() *InitialLoadBalanceRequest { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_InitialRequest); ok { - return x.InitialRequest - } - return nil -} - -func (m *LoadBalanceRequest) GetClientStats() *ClientStats { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_ClientStats); ok { - return x.ClientStats - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{ - (*LoadBalanceRequest_InitialRequest)(nil), - (*LoadBalanceRequest_ClientStats)(nil), - } -} - -func _LoadBalanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialRequest); err != nil { - return err - } - case *LoadBalanceRequest_ClientStats: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientStats); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceRequest.LoadBalanceRequestType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceRequest) - switch tag { - case 1: // load_balance_request_type.initial_request - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceRequest) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_InitialRequest{msg} - return true, err - case 2: // load_balance_request_type.client_stats - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientStats) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_ClientStats{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - s := proto.Size(x.InitialRequest) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceRequest_ClientStats: - s := proto.Size(x.ClientStats) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceRequest struct { - // Name of load balanced service (IE, service.googleapis.com). Its - // length should be less than 256 bytes. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } -func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceRequest) ProtoMessage() {} -func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{1} -} -func (m *InitialLoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceRequest.Unmarshal(m, b) -} -func (m *InitialLoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceRequest.Merge(dst, src) -} -func (m *InitialLoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceRequest.Size(m) -} -func (m *InitialLoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceRequest proto.InternalMessageInfo - -func (m *InitialLoadBalanceRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// Contains the number of calls finished for a particular load balance token. -type ClientStatsPerToken struct { - // See Server.load_balance_token. - LoadBalanceToken string `protobuf:"bytes,1,opt,name=load_balance_token,json=loadBalanceToken,proto3" json:"load_balance_token,omitempty"` - // The total number of RPCs that finished associated with the token. - NumCalls int64 `protobuf:"varint,2,opt,name=num_calls,json=numCalls,proto3" json:"num_calls,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStatsPerToken) Reset() { *m = ClientStatsPerToken{} } -func (m *ClientStatsPerToken) String() string { return proto.CompactTextString(m) } -func (*ClientStatsPerToken) ProtoMessage() {} -func (*ClientStatsPerToken) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{2} -} -func (m *ClientStatsPerToken) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStatsPerToken.Unmarshal(m, b) -} -func (m *ClientStatsPerToken) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStatsPerToken.Marshal(b, m, deterministic) -} -func (dst *ClientStatsPerToken) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStatsPerToken.Merge(dst, src) -} -func (m *ClientStatsPerToken) XXX_Size() int { - return xxx_messageInfo_ClientStatsPerToken.Size(m) -} -func (m *ClientStatsPerToken) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStatsPerToken.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStatsPerToken proto.InternalMessageInfo - -func (m *ClientStatsPerToken) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *ClientStatsPerToken) GetNumCalls() int64 { - if m != nil { - return m.NumCalls - } - return 0 -} - -// Contains client level statistics that are useful to load balancing. Each -// count except the timestamp should be reset to zero after reporting the stats. -type ClientStats struct { - // The timestamp of generating the report. - Timestamp *timestamp.Timestamp `protobuf:"bytes,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // The total number of RPCs that started. - NumCallsStarted int64 `protobuf:"varint,2,opt,name=num_calls_started,json=numCallsStarted,proto3" json:"num_calls_started,omitempty"` - // The total number of RPCs that finished. - NumCallsFinished int64 `protobuf:"varint,3,opt,name=num_calls_finished,json=numCallsFinished,proto3" json:"num_calls_finished,omitempty"` - // The total number of RPCs that failed to reach a server except dropped RPCs. - NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend,proto3" json:"num_calls_finished_with_client_failed_to_send,omitempty"` - // The total number of RPCs that finished and are known to have been received - // by a server. - NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived,proto3" json:"num_calls_finished_known_received,omitempty"` - // The list of dropped calls. - CallsFinishedWithDrop []*ClientStatsPerToken `protobuf:"bytes,8,rep,name=calls_finished_with_drop,json=callsFinishedWithDrop,proto3" json:"calls_finished_with_drop,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{3} -} -func (m *ClientStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStats.Unmarshal(m, b) -} -func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) -} -func (dst *ClientStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStats.Merge(dst, src) -} -func (m *ClientStats) XXX_Size() int { - return xxx_messageInfo_ClientStats.Size(m) -} -func (m *ClientStats) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStats proto.InternalMessageInfo - -func (m *ClientStats) GetTimestamp() *timestamp.Timestamp { - if m != nil { - return m.Timestamp - } - return nil -} - -func (m *ClientStats) GetNumCallsStarted() int64 { - if m != nil { - return m.NumCallsStarted - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinished() int64 { - if m != nil { - return m.NumCallsFinished - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithClientFailedToSend() int64 { - if m != nil { - return m.NumCallsFinishedWithClientFailedToSend - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedKnownReceived() int64 { - if m != nil { - return m.NumCallsFinishedKnownReceived - } - return 0 -} - -func (m *ClientStats) GetCallsFinishedWithDrop() []*ClientStatsPerToken { - if m != nil { - return m.CallsFinishedWithDrop - } - return nil -} - -type LoadBalanceResponse struct { - // Types that are valid to be assigned to LoadBalanceResponseType: - // *LoadBalanceResponse_InitialResponse - // *LoadBalanceResponse_ServerList - LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } -func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceResponse) ProtoMessage() {} -func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{4} -} -func (m *LoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceResponse.Unmarshal(m, b) -} -func (m *LoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceResponse.Merge(dst, src) -} -func (m *LoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_LoadBalanceResponse.Size(m) -} -func (m *LoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceResponse proto.InternalMessageInfo - -type isLoadBalanceResponse_LoadBalanceResponseType interface { - isLoadBalanceResponse_LoadBalanceResponseType() -} - -type LoadBalanceResponse_InitialResponse struct { - InitialResponse *InitialLoadBalanceResponse `protobuf:"bytes,1,opt,name=initial_response,json=initialResponse,proto3,oneof"` -} -type LoadBalanceResponse_ServerList struct { - ServerList *ServerList `protobuf:"bytes,2,opt,name=server_list,json=serverList,proto3,oneof"` -} - -func (*LoadBalanceResponse_InitialResponse) isLoadBalanceResponse_LoadBalanceResponseType() {} -func (*LoadBalanceResponse_ServerList) isLoadBalanceResponse_LoadBalanceResponseType() {} - -func (m *LoadBalanceResponse) GetLoadBalanceResponseType() isLoadBalanceResponse_LoadBalanceResponseType { - if m != nil { - return m.LoadBalanceResponseType - } - return nil -} - -func (m *LoadBalanceResponse) GetInitialResponse() *InitialLoadBalanceResponse { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_InitialResponse); ok { - return x.InitialResponse - } - return nil -} - -func (m *LoadBalanceResponse) GetServerList() *ServerList { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_ServerList); ok { - return x.ServerList - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceResponse_OneofMarshaler, _LoadBalanceResponse_OneofUnmarshaler, _LoadBalanceResponse_OneofSizer, []interface{}{ - (*LoadBalanceResponse_InitialResponse)(nil), - (*LoadBalanceResponse_ServerList)(nil), - } -} - -func _LoadBalanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialResponse); err != nil { - return err - } - case *LoadBalanceResponse_ServerList: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerList); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceResponse.LoadBalanceResponseType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceResponse) - switch tag { - case 1: // load_balance_response_type.initial_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceResponse) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_InitialResponse{msg} - return true, err - case 2: // load_balance_response_type.server_list - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerList) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_ServerList{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - s := proto.Size(x.InitialResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceResponse_ServerList: - s := proto.Size(x.ServerList) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceResponse struct { - // This is an application layer redirect that indicates the client should use - // the specified server for load balancing. When this field is non-empty in - // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. Its length should - // be less than 64 bytes. - LoadBalancerDelegate string `protobuf:"bytes,1,opt,name=load_balancer_delegate,json=loadBalancerDelegate,proto3" json:"load_balancer_delegate,omitempty"` - // This interval defines how often the client should send the client stats - // to the load balancer. Stats should only be reported when the duration is - // positive. - ClientStatsReportInterval *duration.Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval,proto3" json:"client_stats_report_interval,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } -func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceResponse) ProtoMessage() {} -func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{5} -} -func (m *InitialLoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceResponse.Unmarshal(m, b) -} -func (m *InitialLoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceResponse.Merge(dst, src) -} -func (m *InitialLoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceResponse.Size(m) -} -func (m *InitialLoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceResponse proto.InternalMessageInfo - -func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string { - if m != nil { - return m.LoadBalancerDelegate - } - return "" -} - -func (m *InitialLoadBalanceResponse) GetClientStatsReportInterval() *duration.Duration { - if m != nil { - return m.ClientStatsReportInterval - } - return nil -} - -type ServerList struct { - // Contains a list of servers selected by the load balancer. The list will - // be updated when server resolutions change or as needed to balance load - // across more servers. The client should consume the server list in order - // unless instructed otherwise via the client_config. - Servers []*Server `protobuf:"bytes,1,rep,name=servers,proto3" json:"servers,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerList) Reset() { *m = ServerList{} } -func (m *ServerList) String() string { return proto.CompactTextString(m) } -func (*ServerList) ProtoMessage() {} -func (*ServerList) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{6} -} -func (m *ServerList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerList.Unmarshal(m, b) -} -func (m *ServerList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerList.Marshal(b, m, deterministic) -} -func (dst *ServerList) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerList.Merge(dst, src) -} -func (m *ServerList) XXX_Size() int { - return xxx_messageInfo_ServerList.Size(m) -} -func (m *ServerList) XXX_DiscardUnknown() { - xxx_messageInfo_ServerList.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerList proto.InternalMessageInfo - -func (m *ServerList) GetServers() []*Server { - if m != nil { - return m.Servers - } - return nil -} - -// Contains server information. When the drop field is not true, use the other -// fields. -type Server struct { - // A resolved address for the server, serialized in network-byte-order. It may - // either be an IPv4 or IPv6 address. - IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // A resolved port number for the server. - Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` - // An opaque but printable token given to the frontend for each pick. All - // frontend requests for that pick must include the token in its initial - // metadata. The token is used by the backend to verify the request and to - // allow the backend to report load to the gRPC LB system. The token is also - // used in client stats for reporting dropped calls. - LoadBalanceToken string `protobuf:"bytes,3,opt,name=load_balance_token,json=loadBalanceToken,proto3" json:"load_balance_token,omitempty"` - // 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. - Drop bool `protobuf:"varint,4,opt,name=drop,proto3" json:"drop,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { - return fileDescriptor_load_balancer_077502ef49b0d1b1, []int{7} -} -func (m *Server) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Server.Unmarshal(m, b) -} -func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Server.Marshal(b, m, deterministic) -} -func (dst *Server) XXX_Merge(src proto.Message) { - xxx_messageInfo_Server.Merge(dst, src) -} -func (m *Server) XXX_Size() int { - return xxx_messageInfo_Server.Size(m) -} -func (m *Server) XXX_DiscardUnknown() { - xxx_messageInfo_Server.DiscardUnknown(m) -} - -var xxx_messageInfo_Server proto.InternalMessageInfo - -func (m *Server) GetIpAddress() []byte { - if m != nil { - return m.IpAddress - } - return nil -} - -func (m *Server) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Server) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *Server) GetDrop() bool { - if m != nil { - return m.Drop - } - return false -} - -func init() { - proto.RegisterType((*LoadBalanceRequest)(nil), "grpc.lb.v1.LoadBalanceRequest") - proto.RegisterType((*InitialLoadBalanceRequest)(nil), "grpc.lb.v1.InitialLoadBalanceRequest") - proto.RegisterType((*ClientStatsPerToken)(nil), "grpc.lb.v1.ClientStatsPerToken") - proto.RegisterType((*ClientStats)(nil), "grpc.lb.v1.ClientStats") - proto.RegisterType((*LoadBalanceResponse)(nil), "grpc.lb.v1.LoadBalanceResponse") - proto.RegisterType((*InitialLoadBalanceResponse)(nil), "grpc.lb.v1.InitialLoadBalanceResponse") - proto.RegisterType((*ServerList)(nil), "grpc.lb.v1.ServerList") - proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// LoadBalancerClient is the client API for LoadBalancer service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type LoadBalancerClient interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) -} - -type loadBalancerClient struct { - cc *grpc.ClientConn -} - -func NewLoadBalancerClient(cc *grpc.ClientConn) LoadBalancerClient { - return &loadBalancerClient{cc} -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) { - stream, err := c.cc.NewStream(ctx, &_LoadBalancer_serviceDesc.Streams[0], "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &loadBalancerBalanceLoadClient{stream} - return x, nil -} - -type LoadBalancer_BalanceLoadClient interface { - Send(*LoadBalanceRequest) error - Recv() (*LoadBalanceResponse, error) - grpc.ClientStream -} - -type loadBalancerBalanceLoadClient struct { - grpc.ClientStream -} - -func (x *loadBalancerBalanceLoadClient) Send(m *LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadClient) Recv() (*LoadBalanceResponse, error) { - m := new(LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// LoadBalancerServer is the server API for LoadBalancer service. -type LoadBalancerServer interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(LoadBalancer_BalanceLoadServer) error -} - -func RegisterLoadBalancerServer(s *grpc.Server, srv LoadBalancerServer) { - s.RegisterService(&_LoadBalancer_serviceDesc, srv) -} - -func _LoadBalancer_BalanceLoad_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(LoadBalancerServer).BalanceLoad(&loadBalancerBalanceLoadServer{stream}) -} - -type LoadBalancer_BalanceLoadServer interface { - Send(*LoadBalanceResponse) error - Recv() (*LoadBalanceRequest, error) - grpc.ServerStream -} - -type loadBalancerBalanceLoadServer struct { - grpc.ServerStream -} - -func (x *loadBalancerBalanceLoadServer) Send(m *LoadBalanceResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadServer) Recv() (*LoadBalanceRequest, error) { - m := new(LoadBalanceRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _LoadBalancer_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.lb.v1.LoadBalancer", - HandlerType: (*LoadBalancerServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "BalanceLoad", - Handler: _LoadBalancer_BalanceLoad_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc/lb/v1/load_balancer.proto", -} - -func init() { - proto.RegisterFile("grpc/lb/v1/load_balancer.proto", fileDescriptor_load_balancer_077502ef49b0d1b1) -} - -var fileDescriptor_load_balancer_077502ef49b0d1b1 = []byte{ - // 756 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x55, 0xdd, 0x6e, 0x23, 0x35, - 0x14, 0xee, 0x90, 0x69, 0x36, 0x39, 0xa9, 0xb6, 0x59, 0x2f, 0x2c, 0x93, 0xec, 0x6e, 0x5b, 0x22, - 0xb1, 0x8a, 0xd0, 0x32, 0x43, 0x0a, 0x17, 0x20, 0x71, 0x01, 0xd9, 0x6a, 0x95, 0x2d, 0xbd, 0x88, - 0x9c, 0x4a, 0x54, 0x95, 0x90, 0x99, 0xc9, 0xb8, 0xa9, 0x55, 0xc7, 0x1e, 0x3c, 0x4e, 0x2a, 0xae, - 0x79, 0x1f, 0xc4, 0x2b, 0x20, 0x5e, 0x0c, 0x8d, 0xed, 0x49, 0xa6, 0x49, 0xa3, 0xbd, 0x69, 0x3d, - 0xe7, 0x7c, 0xfe, 0xce, 0xef, 0xe7, 0xc0, 0xd1, 0x4c, 0x65, 0xd3, 0x88, 0x27, 0xd1, 0x72, 0x10, - 0x71, 0x19, 0xa7, 0x24, 0x89, 0x79, 0x2c, 0xa6, 0x54, 0x85, 0x99, 0x92, 0x5a, 0x22, 0x28, 0xfc, - 0x21, 0x4f, 0xc2, 0xe5, 0xa0, 0x7b, 0x34, 0x93, 0x72, 0xc6, 0x69, 0x64, 0x3c, 0xc9, 0xe2, 0x26, - 0x4a, 0x17, 0x2a, 0xd6, 0x4c, 0x0a, 0x8b, 0xed, 0x1e, 0x6f, 0xfa, 0x35, 0x9b, 0xd3, 0x5c, 0xc7, - 0xf3, 0xcc, 0x02, 0x7a, 0xff, 0x7a, 0x80, 0x2e, 0x64, 0x9c, 0x0e, 0x6d, 0x0c, 0x4c, 0xff, 0x58, - 0xd0, 0x5c, 0xa3, 0x31, 0x1c, 0x32, 0xc1, 0x34, 0x8b, 0x39, 0x51, 0xd6, 0x14, 0x78, 0x27, 0x5e, - 0xbf, 0x75, 0xfa, 0x65, 0xb8, 0x8e, 0x1e, 0x7e, 0xb0, 0x90, 0xed, 0xfb, 0xa3, 0x3d, 0xfc, 0xd4, - 0xdd, 0x2f, 0x19, 0x7f, 0x84, 0x83, 0x29, 0x67, 0x54, 0x68, 0x92, 0xeb, 0x58, 0xe7, 0xc1, 0x27, - 0x86, 0xee, 0xf3, 0x2a, 0xdd, 0x3b, 0xe3, 0x9f, 0x14, 0xee, 0xd1, 0x1e, 0x6e, 0x4d, 0xd7, 0x9f, - 0xc3, 0x97, 0xd0, 0xa9, 0xb6, 0xa2, 0x4c, 0x8a, 0xe8, 0x3f, 0x33, 0xda, 0x8b, 0xa0, 0xb3, 0x33, - 0x13, 0x84, 0xc0, 0x17, 0xf1, 0x9c, 0x9a, 0xf4, 0x9b, 0xd8, 0x9c, 0x7b, 0xbf, 0xc3, 0xf3, 0x4a, - 0xac, 0x31, 0x55, 0x97, 0xf2, 0x8e, 0x0a, 0xf4, 0x16, 0xd0, 0x83, 0x20, 0xba, 0xb0, 0xba, 0x8b, - 0x6d, 0xbe, 0xa6, 0xb6, 0xe8, 0x97, 0xd0, 0x14, 0x8b, 0x39, 0x99, 0xc6, 0x9c, 0xdb, 0x6a, 0x6a, - 0xb8, 0x21, 0x16, 0xf3, 0x77, 0xc5, 0x77, 0xef, 0x9f, 0x1a, 0xb4, 0x2a, 0x21, 0xd0, 0xf7, 0xd0, - 0x5c, 0x75, 0xde, 0x75, 0xb2, 0x1b, 0xda, 0xd9, 0x84, 0xe5, 0x6c, 0xc2, 0xcb, 0x12, 0x81, 0xd7, - 0x60, 0xf4, 0x15, 0x3c, 0x5b, 0x85, 0x29, 0x5a, 0xa7, 0x34, 0x4d, 0x5d, 0xb8, 0xc3, 0x32, 0xdc, - 0xc4, 0x9a, 0x8b, 0x02, 0xd6, 0xd8, 0x1b, 0x26, 0x58, 0x7e, 0x4b, 0xd3, 0xa0, 0x66, 0xc0, 0xed, - 0x12, 0xfc, 0xde, 0xd9, 0xd1, 0x6f, 0xf0, 0xf5, 0x36, 0x9a, 0xdc, 0x33, 0x7d, 0x4b, 0xdc, 0xa4, - 0x6e, 0x62, 0xc6, 0x69, 0x4a, 0xb4, 0x24, 0x39, 0x15, 0x69, 0x50, 0x37, 0x44, 0x6f, 0x36, 0x89, - 0x7e, 0x65, 0xfa, 0xd6, 0xd6, 0xfa, 0xde, 0xe0, 0x2f, 0xe5, 0x84, 0x8a, 0x14, 0x8d, 0xe0, 0x8b, - 0x47, 0xe8, 0xef, 0x84, 0xbc, 0x17, 0x44, 0xd1, 0x29, 0x65, 0x4b, 0x9a, 0x06, 0x4f, 0x0c, 0xe5, - 0xeb, 0x4d, 0xca, 0x5f, 0x0a, 0x14, 0x76, 0x20, 0x74, 0x05, 0xc1, 0x63, 0x49, 0xa6, 0x4a, 0x66, - 0x41, 0xe3, 0xa4, 0xd6, 0x6f, 0x9d, 0x1e, 0xef, 0x58, 0xa3, 0x72, 0xb4, 0xf8, 0xb3, 0xe9, 0x66, - 0xc6, 0x67, 0x4a, 0x66, 0xe7, 0x7e, 0xc3, 0x6f, 0xef, 0x9f, 0xfb, 0x8d, 0xfd, 0x76, 0xbd, 0xf7, - 0x9f, 0x07, 0xcf, 0x1f, 0xec, 0x4f, 0x9e, 0x49, 0x91, 0x53, 0x34, 0x81, 0xf6, 0x5a, 0x0a, 0xd6, - 0xe6, 0x26, 0xf8, 0xe6, 0x63, 0x5a, 0xb0, 0xe8, 0xd1, 0x1e, 0x3e, 0x5c, 0x89, 0xc1, 0x91, 0xfe, - 0x00, 0xad, 0x9c, 0xaa, 0x25, 0x55, 0x84, 0xb3, 0x5c, 0x3b, 0x31, 0xbc, 0xa8, 0xf2, 0x4d, 0x8c, - 0xfb, 0x82, 0x19, 0x31, 0x41, 0xbe, 0xfa, 0x1a, 0xbe, 0x82, 0xee, 0x86, 0x14, 0x2c, 0xa7, 0xd5, - 0xc2, 0xdf, 0x1e, 0x74, 0x77, 0xa7, 0x82, 0xbe, 0x83, 0x17, 0x0f, 0x9e, 0x14, 0x92, 0x52, 0x4e, - 0x67, 0xb1, 0x2e, 0xf5, 0xf1, 0x69, 0x65, 0xcd, 0xd5, 0x99, 0xf3, 0xa1, 0x6b, 0x78, 0x55, 0xd5, - 0x2e, 0x51, 0x34, 0x93, 0x4a, 0x13, 0x26, 0x34, 0x55, 0xcb, 0x98, 0xbb, 0xf4, 0x3b, 0x5b, 0x0b, - 0x7d, 0xe6, 0x1e, 0x23, 0xdc, 0xa9, 0x68, 0x19, 0x9b, 0xcb, 0x1f, 0xdc, 0xdd, 0xde, 0x4f, 0x00, - 0xeb, 0x52, 0xd1, 0x5b, 0x78, 0x62, 0x4b, 0xcd, 0x03, 0xcf, 0x4c, 0x16, 0x6d, 0xf7, 0x04, 0x97, - 0x90, 0x73, 0xbf, 0x51, 0x6b, 0xfb, 0xbd, 0xbf, 0x3c, 0xa8, 0x5b, 0x0f, 0x7a, 0x0d, 0xc0, 0x32, - 0x12, 0xa7, 0xa9, 0xa2, 0x79, 0x6e, 0x4a, 0x3a, 0xc0, 0x4d, 0x96, 0xfd, 0x6c, 0x0d, 0xc5, 0x5b, - 0x50, 0xc4, 0x36, 0xf9, 0xee, 0x63, 0x73, 0xde, 0x21, 0xfa, 0xda, 0x0e, 0xd1, 0x23, 0xf0, 0xcd, - 0xda, 0xf9, 0x27, 0x5e, 0xbf, 0x81, 0xcd, 0xd9, 0xae, 0xcf, 0x69, 0x02, 0x07, 0x95, 0x86, 0x2b, - 0x84, 0xa1, 0xe5, 0xce, 0x85, 0x19, 0x1d, 0x55, 0xeb, 0xd8, 0x7e, 0xa6, 0xba, 0xc7, 0x3b, 0xfd, - 0x76, 0x72, 0x7d, 0xef, 0x1b, 0x6f, 0x78, 0x05, 0x4f, 0x99, 0xb4, 0xc0, 0xe2, 0x0f, 0x4f, 0x86, - 0xcf, 0xaa, 0x31, 0xc7, 0x45, 0xdf, 0xc7, 0xde, 0xf5, 0xc0, 0xcd, 0x61, 0x26, 0x79, 0x2c, 0x66, - 0xa1, 0x54, 0xb3, 0xc8, 0xfc, 0xa4, 0x94, 0x43, 0x8f, 0xec, 0x65, 0xf3, 0x8f, 0xf0, 0x84, 0x2c, - 0x07, 0x49, 0xdd, 0xcc, 0xec, 0xdb, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0x5f, 0xc0, 0x96, 0xfd, - 0x7c, 0x06, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb.go deleted file mode 100755 index 0c46ae3..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb.go +++ /dev/null @@ -1,368 +0,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. - * - */ - -//go:generate ./regenerate.sh - -// Package grpclb defines a grpclb balancer. -// -// To install grpclb balancer, import this package as: -// import _ "google.golang.org/grpc/balancer/grpclb" -package grpclb - -import ( - "fmt" - "strconv" - "strings" - "sync" - "time" - - durationpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer" - lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/backoff" - "google.golang.org/grpc/resolver" -) - -const ( - lbTokeyKey = "lb-token" - defaultFallbackTimeout = 10 * time.Second - grpclbName = "grpclb" -) - -var ( - // defaultBackoffConfig configures the backoff strategy that's used when the - // init handshake in the RPC is unsuccessful. It's not for the clientconn - // reconnect backoff. - // - // It has the same value as the default grpc.DefaultBackoffConfig. - // - // TODO: make backoff configurable. - defaultBackoffConfig = backoff.Exponential{ - MaxDelay: 120 * time.Second, - } - errServerTerminatedConnection = fmt.Errorf("grpclb: failed to recv server list: server terminated connection") -) - -func convertDuration(d *durationpb.Duration) time.Duration { - if d == nil { - return 0 - } - return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond -} - -// Client API for LoadBalancer service. -// Mostly copied from generated pb.go file. -// To avoid circular dependency. -type loadBalancerClient struct { - cc *grpc.ClientConn -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (*balanceLoadClientStream, error) { - desc := &grpc.StreamDesc{ - StreamName: "BalanceLoad", - ServerStreams: true, - ClientStreams: true, - } - stream, err := c.cc.NewStream(ctx, desc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &balanceLoadClientStream{stream} - return x, nil -} - -type balanceLoadClientStream struct { - grpc.ClientStream -} - -func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) { - m := new(lbpb.LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func init() { - balancer.Register(newLBBuilder()) -} - -// newLBBuilder creates a builder for grpclb. -func newLBBuilder() balancer.Builder { - return newLBBuilderWithFallbackTimeout(defaultFallbackTimeout) -} - -// newLBBuilderWithFallbackTimeout creates a grpclb builder with the given -// fallbackTimeout. If no response is received from the remote balancer within -// fallbackTimeout, the backend addresses from the resolved address list will be -// used. -// -// Only call this function when a non-default fallback timeout is needed. -func newLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder { - return &lbBuilder{ - fallbackTimeout: fallbackTimeout, - } -} - -type lbBuilder struct { - fallbackTimeout time.Duration -} - -func (b *lbBuilder) Name() string { - return grpclbName -} - -func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - // This generates a manual resolver builder with a random scheme. This - // scheme will be used to dial to remote LB, so we can send filtered address - // updates to remote LB ClientConn using this manual resolver. - scheme := "grpclb_internal_" + strconv.FormatInt(time.Now().UnixNano(), 36) - r := &lbManualResolver{scheme: scheme, ccb: cc} - - var target string - targetSplitted := strings.Split(cc.Target(), ":///") - if len(targetSplitted) < 2 { - target = cc.Target() - } else { - target = targetSplitted[1] - } - - lb := &lbBalancer{ - cc: newLBCacheClientConn(cc), - target: target, - opt: opt, - fallbackTimeout: b.fallbackTimeout, - doneCh: make(chan struct{}), - - manualResolver: r, - csEvltr: &balancer.ConnectivityStateEvaluator{}, - subConns: make(map[resolver.Address]balancer.SubConn), - scStates: make(map[balancer.SubConn]connectivity.State), - picker: &errPicker{err: balancer.ErrNoSubConnAvailable}, - clientStats: newRPCStats(), - backoff: defaultBackoffConfig, // TODO: make backoff configurable. - } - - return lb -} - -type lbBalancer struct { - cc *lbCacheClientConn - target string - opt balancer.BuildOptions - fallbackTimeout time.Duration - doneCh chan struct{} - - // manualResolver is used in the remote LB ClientConn inside grpclb. When - // resolved address updates are received by grpclb, filtered updates will be - // send to remote LB ClientConn through this resolver. - manualResolver *lbManualResolver - // The ClientConn to talk to the remote balancer. - ccRemoteLB *grpc.ClientConn - // backoff for calling remote balancer. - backoff backoff.Strategy - - // Support client side load reporting. Each picker gets a reference to this, - // and will update its content. - clientStats *rpcStats - - mu sync.Mutex // guards everything following. - // The full server list including drops, used to check if the newly received - // serverList contains anything new. Each generate picker will also have - // reference to this list to do the first layer pick. - fullServerList []*lbpb.Server - // All backends addresses, with metadata set to nil. This list contains all - // backend addresses in the same order and with the same duplicates as in - // serverlist. When generating picker, a SubConn slice with the same order - // but with only READY SCs will be gerenated. - backendAddrs []resolver.Address - // Roundrobin functionalities. - csEvltr *balancer.ConnectivityStateEvaluator - state connectivity.State - subConns map[resolver.Address]balancer.SubConn // Used to new/remove SubConn. - scStates map[balancer.SubConn]connectivity.State // Used to filter READY SubConns. - picker balancer.Picker - // Support fallback to resolved backend addresses if there's no response - // from remote balancer within fallbackTimeout. - fallbackTimerExpired bool - serverListReceived bool - // resolvedBackendAddrs is resolvedAddrs minus remote balancers. It's set - // when resolved address updates are received, and read in the goroutine - // handling fallback. - resolvedBackendAddrs []resolver.Address -} - -// regeneratePicker takes a snapshot of the balancer, and generates a picker from -// it. The picker -// - always returns ErrTransientFailure if the balancer is in TransientFailure, -// - does two layer roundrobin pick otherwise. -// Caller must hold lb.mu. -func (lb *lbBalancer) regeneratePicker() { - if lb.state == connectivity.TransientFailure { - lb.picker = &errPicker{err: balancer.ErrTransientFailure} - return - } - var readySCs []balancer.SubConn - for _, a := range lb.backendAddrs { - if sc, ok := lb.subConns[a]; ok { - if st, ok := lb.scStates[sc]; ok && st == connectivity.Ready { - readySCs = append(readySCs, sc) - } - } - } - - if len(lb.fullServerList) <= 0 { - if len(readySCs) <= 0 { - lb.picker = &errPicker{err: balancer.ErrNoSubConnAvailable} - return - } - lb.picker = &rrPicker{subConns: readySCs} - return - } - lb.picker = &lbPicker{ - serverList: lb.fullServerList, - subConns: readySCs, - stats: lb.clientStats, - } -} - -func (lb *lbBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("lbBalancer: handle SubConn state change: %p, %v", sc, s) - lb.mu.Lock() - defer lb.mu.Unlock() - - oldS, ok := lb.scStates[sc] - if !ok { - grpclog.Infof("lbBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) - return - } - lb.scStates[sc] = s - switch s { - case connectivity.Idle: - sc.Connect() - case connectivity.Shutdown: - // When an address was removed by resolver, b called RemoveSubConn but - // kept the sc's state in scStates. Remove state for this sc here. - delete(lb.scStates, sc) - } - - oldAggrState := lb.state - lb.state = lb.csEvltr.RecordTransition(oldS, s) - - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure - if (oldS == connectivity.Ready) != (s == connectivity.Ready) || - (lb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { - lb.regeneratePicker() - } - - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// fallbackToBackendsAfter blocks for fallbackTimeout and falls back to use -// resolved backends (backends received from resolver, not from remote balancer) -// if no connection to remote balancers was successful. -func (lb *lbBalancer) fallbackToBackendsAfter(fallbackTimeout time.Duration) { - timer := time.NewTimer(fallbackTimeout) - defer timer.Stop() - select { - case <-timer.C: - case <-lb.doneCh: - return - } - lb.mu.Lock() - if lb.serverListReceived { - lb.mu.Unlock() - return - } - lb.fallbackTimerExpired = true - lb.refreshSubConns(lb.resolvedBackendAddrs) - lb.mu.Unlock() -} - -// HandleResolvedAddrs sends the updated remoteLB addresses to remoteLB -// clientConn. The remoteLB clientConn will handle creating/removing remoteLB -// connections. -func (lb *lbBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - grpclog.Infof("lbBalancer: handleResolvedResult: %+v", addrs) - if len(addrs) <= 0 { - return - } - - var remoteBalancerAddrs, backendAddrs []resolver.Address - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - remoteBalancerAddrs = append(remoteBalancerAddrs, a) - } else { - backendAddrs = append(backendAddrs, a) - } - } - - if lb.ccRemoteLB == nil { - if len(remoteBalancerAddrs) <= 0 { - grpclog.Errorf("grpclb: no remote balancer address is available, should never happen") - return - } - // First time receiving resolved addresses, create a cc to remote - // balancers. - lb.dialRemoteLB(remoteBalancerAddrs[0].ServerName) - // Start the fallback goroutine. - go lb.fallbackToBackendsAfter(lb.fallbackTimeout) - } - - // cc to remote balancers uses lb.manualResolver. Send the updated remote - // balancer addresses to it through manualResolver. - lb.manualResolver.NewAddress(remoteBalancerAddrs) - - lb.mu.Lock() - lb.resolvedBackendAddrs = backendAddrs - // If serverListReceived is true, connection to remote balancer was - // successful and there's no need to do fallback anymore. - // If fallbackTimerExpired is false, fallback hasn't happened yet. - if !lb.serverListReceived && lb.fallbackTimerExpired { - // This means we received a new list of resolved backends, and we are - // still in fallback mode. Need to update the list of backends we are - // using to the new list of backends. - lb.refreshSubConns(lb.resolvedBackendAddrs) - } - lb.mu.Unlock() -} - -func (lb *lbBalancer) Close() { - select { - case <-lb.doneCh: - return - default: - } - close(lb.doneCh) - if lb.ccRemoteLB != nil { - lb.ccRemoteLB.Close() - } - lb.cc.close() -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_picker.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb_picker.go deleted file mode 100755 index d77af40..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_picker.go +++ /dev/null @@ -1,170 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpclb - -import ( - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// rpcStats is same as lbmpb.ClientStats, except that numCallsDropped is a map -// instead of a slice. -type rpcStats struct { - // Only access the following fields atomically. - numCallsStarted int64 - numCallsFinished int64 - numCallsFinishedWithClientFailedToSend int64 - numCallsFinishedKnownReceived int64 - - mu sync.Mutex - // map load_balance_token -> num_calls_dropped - numCallsDropped map[string]int64 -} - -func newRPCStats() *rpcStats { - return &rpcStats{ - numCallsDropped: make(map[string]int64), - } -} - -// toClientStats converts rpcStats to lbpb.ClientStats, and clears rpcStats. -func (s *rpcStats) toClientStats() *lbpb.ClientStats { - stats := &lbpb.ClientStats{ - NumCallsStarted: atomic.SwapInt64(&s.numCallsStarted, 0), - NumCallsFinished: atomic.SwapInt64(&s.numCallsFinished, 0), - NumCallsFinishedWithClientFailedToSend: atomic.SwapInt64(&s.numCallsFinishedWithClientFailedToSend, 0), - NumCallsFinishedKnownReceived: atomic.SwapInt64(&s.numCallsFinishedKnownReceived, 0), - } - s.mu.Lock() - dropped := s.numCallsDropped - s.numCallsDropped = make(map[string]int64) - s.mu.Unlock() - for token, count := range dropped { - stats.CallsFinishedWithDrop = append(stats.CallsFinishedWithDrop, &lbpb.ClientStatsPerToken{ - LoadBalanceToken: token, - NumCalls: count, - }) - } - return stats -} - -func (s *rpcStats) drop(token string) { - atomic.AddInt64(&s.numCallsStarted, 1) - s.mu.Lock() - s.numCallsDropped[token]++ - s.mu.Unlock() - atomic.AddInt64(&s.numCallsFinished, 1) -} - -func (s *rpcStats) failedToSend() { - atomic.AddInt64(&s.numCallsStarted, 1) - atomic.AddInt64(&s.numCallsFinishedWithClientFailedToSend, 1) - atomic.AddInt64(&s.numCallsFinished, 1) -} - -func (s *rpcStats) knownReceived() { - atomic.AddInt64(&s.numCallsStarted, 1) - atomic.AddInt64(&s.numCallsFinishedKnownReceived, 1) - atomic.AddInt64(&s.numCallsFinished, 1) -} - -type errPicker struct { - // Pick always returns this err. - err error -} - -func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// rrPicker does roundrobin on subConns. It's typically used when there's no -// response from remote balancer, and grpclb falls back to the resolved -// backends. -// -// It guaranteed that len(subConns) > 0. -type rrPicker struct { - mu sync.Mutex - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int -} - -func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - return sc, nil, nil -} - -// lbPicker does two layers of picks: -// -// First layer: roundrobin on all servers in serverList, including drops and backends. -// - If it picks a drop, the RPC will fail as being dropped. -// - If it picks a backend, do a second layer pick to pick the real backend. -// -// Second layer: roundrobin on all READY backends. -// -// It's guaranteed that len(serverList) > 0. -type lbPicker struct { - mu sync.Mutex - serverList []*lbpb.Server - serverListNext int - subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. - subConnsNext int - - stats *rpcStats -} - -func (p *lbPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - p.mu.Lock() - defer p.mu.Unlock() - - // Layer one roundrobin on serverList. - s := p.serverList[p.serverListNext] - p.serverListNext = (p.serverListNext + 1) % len(p.serverList) - - // If it's a drop, return an error and fail the RPC. - if s.Drop { - p.stats.drop(s.LoadBalanceToken) - return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") - } - - // If not a drop but there's no ready subConns. - if len(p.subConns) <= 0 { - return nil, nil, balancer.ErrNoSubConnAvailable - } - - // Return the next ready subConn in the list, also collect rpc stats. - sc := p.subConns[p.subConnsNext] - p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) - done := func(info balancer.DoneInfo) { - if !info.BytesSent { - p.stats.failedToSend() - } else if info.BytesReceived { - p.stats.knownReceived() - } - } - return sc, done, nil -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go deleted file mode 100755 index d0ecd68..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go +++ /dev/null @@ -1,294 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpclb - -import ( - "fmt" - "io" - "net" - "reflect" - "time" - - timestamppb "github.com/golang/protobuf/ptypes/timestamp" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer" - lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" -) - -// processServerList updates balaner's internal state, create/remove SubConns -// and regenerates picker using the received serverList. -func (lb *lbBalancer) processServerList(l *lbpb.ServerList) { - grpclog.Infof("lbBalancer: processing server list: %+v", l) - lb.mu.Lock() - defer lb.mu.Unlock() - - // Set serverListReceived to true so fallback will not take effect if it has - // not hit timeout. - lb.serverListReceived = true - - // If the new server list == old server list, do nothing. - if reflect.DeepEqual(lb.fullServerList, l.Servers) { - grpclog.Infof("lbBalancer: new serverlist same as the previous one, ignoring") - return - } - lb.fullServerList = l.Servers - - var backendAddrs []resolver.Address - for i, s := range l.Servers { - if s.Drop { - continue - } - - md := metadata.Pairs(lbTokeyKey, s.LoadBalanceToken) - ip := net.IP(s.IpAddress) - ipStr := ip.String() - if ip.To4() == nil { - // Add square brackets to ipv6 addresses, otherwise net.Dial() and - // net.SplitHostPort() will return too many colons error. - ipStr = fmt.Sprintf("[%s]", ipStr) - } - addr := resolver.Address{ - Addr: fmt.Sprintf("%s:%d", ipStr, s.Port), - Metadata: &md, - } - grpclog.Infof("lbBalancer: server list entry[%d]: ipStr:|%s|, port:|%d|, load balancer token:|%v|", - i, ipStr, s.Port, s.LoadBalanceToken) - backendAddrs = append(backendAddrs, addr) - } - - // Call refreshSubConns to create/remove SubConns. - lb.refreshSubConns(backendAddrs) - // Regenerate and update picker no matter if there's update on backends (if - // any SubConn will be newed/removed). Because since the full serverList was - // different, there might be updates in drops or pick weights(different - // number of duplicates). We need to update picker with the fulllist. - // - // Now with cache, even if SubConn was newed/removed, there might be no - // state changes. - lb.regeneratePicker() - lb.cc.UpdateBalancerState(lb.state, lb.picker) -} - -// refreshSubConns creates/removes SubConns with backendAddrs. It returns a bool -// indicating whether the backendAddrs are different from the cached -// backendAddrs (whether any SubConn was newed/removed). -// Caller must hold lb.mu. -func (lb *lbBalancer) refreshSubConns(backendAddrs []resolver.Address) bool { - lb.backendAddrs = nil - var backendsUpdated bool - // addrsSet is the set converted from backendAddrs, it's used to quick - // lookup for an address. - addrsSet := make(map[resolver.Address]struct{}) - // Create new SubConns. - for _, addr := range backendAddrs { - addrWithoutMD := addr - addrWithoutMD.Metadata = nil - addrsSet[addrWithoutMD] = struct{}{} - lb.backendAddrs = append(lb.backendAddrs, addrWithoutMD) - - if _, ok := lb.subConns[addrWithoutMD]; !ok { - backendsUpdated = true - - // Use addrWithMD to create the SubConn. - sc, err := lb.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("roundrobinBalancer: failed to create new SubConn: %v", err) - continue - } - lb.subConns[addrWithoutMD] = sc // Use the addr without MD as key for the map. - if _, ok := lb.scStates[sc]; !ok { - // Only set state of new sc to IDLE. The state could already be - // READY for cached SubConns. - lb.scStates[sc] = connectivity.Idle - } - sc.Connect() - } - } - - for a, sc := range lb.subConns { - // a was removed by resolver. - if _, ok := addrsSet[a]; !ok { - backendsUpdated = true - - lb.cc.RemoveSubConn(sc) - delete(lb.subConns, a) - // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. - } - } - - return backendsUpdated -} - -func (lb *lbBalancer) readServerList(s *balanceLoadClientStream) error { - for { - reply, err := s.Recv() - if err != nil { - if err == io.EOF { - return errServerTerminatedConnection - } - return fmt.Errorf("grpclb: failed to recv server list: %v", err) - } - if serverList := reply.GetServerList(); serverList != nil { - lb.processServerList(serverList) - } - } -} - -func (lb *lbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - case <-s.Context().Done(): - return - } - stats := lb.clientStats.toClientStats() - t := time.Now() - stats.Timestamp = ×tamppb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := s.Send(&lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{ - ClientStats: stats, - }, - }); err != nil { - return - } - } -} - -func (lb *lbBalancer) callRemoteBalancer() (backoff bool, _ error) { - lbClient := &loadBalancerClient{cc: lb.ccRemoteLB} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := lbClient.BalanceLoad(ctx, grpc.FailFast(false)) - if err != nil { - return true, fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) - } - - // grpclb handshake on the stream. - initReq := &lbpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{ - InitialRequest: &lbpb.InitialLoadBalanceRequest{ - Name: lb.target, - }, - }, - } - if err := stream.Send(initReq); err != nil { - return true, fmt.Errorf("grpclb: failed to send init request: %v", err) - } - reply, err := stream.Recv() - if err != nil { - return true, fmt.Errorf("grpclb: failed to recv init response: %v", err) - } - initResp := reply.GetInitialResponse() - if initResp == nil { - return true, fmt.Errorf("grpclb: reply from remote balancer did not include initial response") - } - if initResp.LoadBalancerDelegate != "" { - return true, fmt.Errorf("grpclb: Delegation is not supported") - } - - go func() { - if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 { - lb.sendLoadReport(stream, d) - } - }() - // No backoff if init req/resp handshake was successful. - return false, lb.readServerList(stream) -} - -func (lb *lbBalancer) watchRemoteBalancer() { - var retryCount int - for { - doBackoff, err := lb.callRemoteBalancer() - select { - case <-lb.doneCh: - return - default: - if err != nil { - if err == errServerTerminatedConnection { - grpclog.Info(err) - } else { - grpclog.Error(err) - } - } - } - - if !doBackoff { - retryCount = 0 - continue - } - - timer := time.NewTimer(lb.backoff.Backoff(retryCount)) - select { - case <-timer.C: - case <-lb.doneCh: - timer.Stop() - return - } - retryCount++ - } -} - -func (lb *lbBalancer) dialRemoteLB(remoteLBName string) { - var dopts []grpc.DialOption - if creds := lb.opt.DialCreds; creds != nil { - if err := creds.OverrideServerName(remoteLBName); err == nil { - dopts = append(dopts, grpc.WithTransportCredentials(creds)) - } else { - grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v, using Insecure", err) - dopts = append(dopts, grpc.WithInsecure()) - } - } else { - dopts = append(dopts, grpc.WithInsecure()) - } - if lb.opt.Dialer != nil { - // WithDialer takes a different type of function, so we instead use a - // special DialOption here. - wcd := internal.WithContextDialer.(func(func(context.Context, string) (net.Conn, error)) grpc.DialOption) - dopts = append(dopts, wcd(lb.opt.Dialer)) - } - // Explicitly set pickfirst as the balancer. - dopts = append(dopts, grpc.WithBalancerName(grpc.PickFirstBalancerName)) - wrb := internal.WithResolverBuilder.(func(resolver.Builder) grpc.DialOption) - dopts = append(dopts, wrb(lb.manualResolver)) - if channelz.IsOn() { - dopts = append(dopts, grpc.WithChannelzParentID(lb.opt.ChannelzParentID)) - } - - // DialContext using manualResolver.Scheme, which is a random scheme generated - // when init grpclb. The target name is not important. - cc, err := grpc.DialContext(context.Background(), "grpclb:///grpclb.server", dopts...) - if err != nil { - grpclog.Fatalf("failed to dial: %v", err) - } - lb.ccRemoteLB = cc - go lb.watchRemoteBalancer() -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_test.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb_test.go deleted file mode 100755 index 7e6ca76..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_test.go +++ /dev/null @@ -1,970 +0,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. - * - */ - -package grpclb - -import ( - "errors" - "fmt" - "io" - "net" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - durationpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer" - lbgrpc "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - "google.golang.org/grpc/status" - testpb "google.golang.org/grpc/test/grpc_testing" -) - -var ( - lbServerName = "bar.com" - beServerName = "foo.com" - lbToken = "iamatoken" - - // Resolver replaces localhost with fakeName in Next(). - // Dialer replaces fakeName with localhost when dialing. - // This will test that custom dialer is passed from Dial to grpclb. - fakeName = "fake.Name" -) - -type serverNameCheckCreds struct { - mu sync.Mutex - sn string - expected string -} - -func (c *serverNameCheckCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if _, err := io.WriteString(rawConn, c.sn); err != nil { - fmt.Printf("Failed to write the server name %s to the client %v", c.sn, err) - return nil, nil, err - } - return rawConn, nil, nil -} -func (c *serverNameCheckCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - c.mu.Lock() - defer c.mu.Unlock() - b := make([]byte, len(c.expected)) - errCh := make(chan error, 1) - go func() { - _, err := rawConn.Read(b) - errCh <- err - }() - select { - case err := <-errCh: - if err != nil { - fmt.Printf("Failed to read the server name from the server %v", err) - return nil, nil, err - } - case <-ctx.Done(): - return nil, nil, ctx.Err() - } - if c.expected != string(b) { - fmt.Printf("Read the server name %s want %s", string(b), c.expected) - return nil, nil, errors.New("received unexpected server name") - } - return rawConn, nil, nil -} -func (c *serverNameCheckCreds) Info() credentials.ProtocolInfo { - c.mu.Lock() - defer c.mu.Unlock() - return credentials.ProtocolInfo{} -} -func (c *serverNameCheckCreds) Clone() credentials.TransportCredentials { - c.mu.Lock() - defer c.mu.Unlock() - return &serverNameCheckCreds{ - expected: c.expected, - } -} -func (c *serverNameCheckCreds) OverrideServerName(s string) error { - c.mu.Lock() - defer c.mu.Unlock() - c.expected = s - return nil -} - -// fakeNameDialer replaces fakeName with localhost when dialing. -// This will test that custom dialer is passed from Dial to grpclb. -func fakeNameDialer(addr string, timeout time.Duration) (net.Conn, error) { - addr = strings.Replace(addr, fakeName, "localhost", 1) - return net.DialTimeout("tcp", addr, timeout) -} - -// merge merges the new client stats into current stats. -// -// It's a test-only method. rpcStats is defined in grpclb_picker. -func (s *rpcStats) merge(new *lbpb.ClientStats) { - atomic.AddInt64(&s.numCallsStarted, new.NumCallsStarted) - atomic.AddInt64(&s.numCallsFinished, new.NumCallsFinished) - atomic.AddInt64(&s.numCallsFinishedWithClientFailedToSend, new.NumCallsFinishedWithClientFailedToSend) - atomic.AddInt64(&s.numCallsFinishedKnownReceived, new.NumCallsFinishedKnownReceived) - s.mu.Lock() - for _, perToken := range new.CallsFinishedWithDrop { - s.numCallsDropped[perToken.LoadBalanceToken] += perToken.NumCalls - } - s.mu.Unlock() -} - -func mapsEqual(a, b map[string]int64) bool { - if len(a) != len(b) { - return false - } - for k, v1 := range a { - if v2, ok := b[k]; !ok || v1 != v2 { - return false - } - } - return true -} - -func atomicEqual(a, b *int64) bool { - return atomic.LoadInt64(a) == atomic.LoadInt64(b) -} - -// equal compares two rpcStats. -// -// It's a test-only method. rpcStats is defined in grpclb_picker. -func (s *rpcStats) equal(new *rpcStats) bool { - if !atomicEqual(&s.numCallsStarted, &new.numCallsStarted) { - return false - } - if !atomicEqual(&s.numCallsFinished, &new.numCallsFinished) { - return false - } - if !atomicEqual(&s.numCallsFinishedWithClientFailedToSend, &new.numCallsFinishedWithClientFailedToSend) { - return false - } - if !atomicEqual(&s.numCallsFinishedKnownReceived, &new.numCallsFinishedKnownReceived) { - return false - } - s.mu.Lock() - defer s.mu.Unlock() - new.mu.Lock() - defer new.mu.Unlock() - if !mapsEqual(s.numCallsDropped, new.numCallsDropped) { - return false - } - return true -} - -type remoteBalancer struct { - sls chan *lbpb.ServerList - statsDura time.Duration - done chan struct{} - stats *rpcStats -} - -func newRemoteBalancer(intervals []time.Duration) *remoteBalancer { - return &remoteBalancer{ - sls: make(chan *lbpb.ServerList, 1), - done: make(chan struct{}), - stats: newRPCStats(), - } -} - -func (b *remoteBalancer) stop() { - close(b.sls) - close(b.done) -} - -func (b *remoteBalancer) BalanceLoad(stream lbgrpc.LoadBalancer_BalanceLoadServer) error { - req, err := stream.Recv() - if err != nil { - return err - } - initReq := req.GetInitialRequest() - if initReq.Name != beServerName { - return status.Errorf(codes.InvalidArgument, "invalid service name: %v", initReq.Name) - } - resp := &lbpb.LoadBalanceResponse{ - LoadBalanceResponseType: &lbpb.LoadBalanceResponse_InitialResponse{ - InitialResponse: &lbpb.InitialLoadBalanceResponse{ - ClientStatsReportInterval: &durationpb.Duration{ - Seconds: int64(b.statsDura.Seconds()), - Nanos: int32(b.statsDura.Nanoseconds() - int64(b.statsDura.Seconds())*1e9), - }, - }, - }, - } - if err := stream.Send(resp); err != nil { - return err - } - go func() { - for { - var ( - req *lbpb.LoadBalanceRequest - err error - ) - if req, err = stream.Recv(); err != nil { - return - } - b.stats.merge(req.GetClientStats()) - } - }() - for v := range b.sls { - resp = &lbpb.LoadBalanceResponse{ - LoadBalanceResponseType: &lbpb.LoadBalanceResponse_ServerList{ - ServerList: v, - }, - } - if err := stream.Send(resp); err != nil { - return err - } - } - <-b.done - return nil -} - -type testServer struct { - testpb.TestServiceServer - - addr string - fallback bool -} - -const testmdkey = "testmd" - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, status.Error(codes.Internal, "failed to receive metadata") - } - if !s.fallback && (md == nil || md["lb-token"][0] != lbToken) { - return nil, status.Errorf(codes.Internal, "received unexpected metadata: %v", md) - } - grpc.SetTrailer(ctx, metadata.Pairs(testmdkey, s.addr)) - return &testpb.Empty{}, nil -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return nil -} - -func startBackends(sn string, fallback bool, lis ...net.Listener) (servers []*grpc.Server) { - for _, l := range lis { - creds := &serverNameCheckCreds{ - sn: sn, - } - s := grpc.NewServer(grpc.Creds(creds)) - testpb.RegisterTestServiceServer(s, &testServer{addr: l.Addr().String(), fallback: fallback}) - servers = append(servers, s) - go func(s *grpc.Server, l net.Listener) { - s.Serve(l) - }(s, l) - } - return -} - -func stopBackends(servers []*grpc.Server) { - for _, s := range servers { - s.Stop() - } -} - -type testServers struct { - lbAddr string - ls *remoteBalancer - lb *grpc.Server - beIPs []net.IP - bePorts []int -} - -func newLoadBalancer(numberOfBackends int) (tss *testServers, cleanup func(), err error) { - var ( - beListeners []net.Listener - ls *remoteBalancer - lb *grpc.Server - beIPs []net.IP - bePorts []int - ) - for i := 0; i < numberOfBackends; i++ { - // Start a backend. - beLis, e := net.Listen("tcp", "localhost:0") - if e != nil { - err = fmt.Errorf("Failed to listen %v", err) - return - } - beIPs = append(beIPs, beLis.Addr().(*net.TCPAddr).IP) - bePorts = append(bePorts, beLis.Addr().(*net.TCPAddr).Port) - - beListeners = append(beListeners, beLis) - } - backends := startBackends(beServerName, false, beListeners...) - - // Start a load balancer. - lbLis, err := net.Listen("tcp", "localhost:0") - if err != nil { - err = fmt.Errorf("Failed to create the listener for the load balancer %v", err) - return - } - lbCreds := &serverNameCheckCreds{ - sn: lbServerName, - } - lb = grpc.NewServer(grpc.Creds(lbCreds)) - ls = newRemoteBalancer(nil) - lbgrpc.RegisterLoadBalancerServer(lb, ls) - go func() { - lb.Serve(lbLis) - }() - - tss = &testServers{ - lbAddr: fakeName + ":" + strconv.Itoa(lbLis.Addr().(*net.TCPAddr).Port), - ls: ls, - lb: lb, - beIPs: beIPs, - bePorts: bePorts, - } - cleanup = func() { - defer stopBackends(backends) - defer func() { - ls.stop() - lb.Stop() - }() - } - return -} - -func TestGRPCLB(t *testing.T) { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - be := &lbpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - } - var bes []*lbpb.Server - bes = append(bes, be) - sl := &lbpb.ServerList{ - Servers: bes, - } - tss.ls.sls <- sl - creds := serverNameCheckCreds{ - expected: beServerName, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{ - Addr: tss.lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }}) - - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } -} - -// The remote balancer sends response with duplicates to grpclb client. -func TestGRPCLBWeighted(t *testing.T) { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - tss, cleanup, err := newLoadBalancer(2) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - beServers := []*lbpb.Server{{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - }, { - IpAddress: tss.beIPs[1], - Port: int32(tss.bePorts[1]), - LoadBalanceToken: lbToken, - }} - portsToIndex := make(map[int]int) - for i := range beServers { - portsToIndex[tss.bePorts[i]] = i - } - - creds := serverNameCheckCreds{ - expected: beServerName, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{ - Addr: tss.lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }}) - - sequences := []string{"00101", "00011"} - for _, seq := range sequences { - var ( - bes []*lbpb.Server - p peer.Peer - result string - ) - for _, s := range seq { - bes = append(bes, beServers[s-'0']) - } - tss.ls.sls <- &lbpb.ServerList{Servers: bes} - - for i := 0; i < 1000; i++ { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false), grpc.Peer(&p)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - result += strconv.Itoa(portsToIndex[p.Addr.(*net.TCPAddr).Port]) - } - // The generated result will be in format of "0010100101". - if !strings.Contains(result, strings.Repeat(seq, 2)) { - t.Errorf("got result sequence %q, want patten %q", result, seq) - } - } -} - -func TestDropRequest(t *testing.T) { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - tss.ls.sls <- &lbpb.ServerList{ - Servers: []*lbpb.Server{{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - Drop: false, - }, { - Drop: true, - }}, - } - creds := serverNameCheckCreds{ - expected: beServerName, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{ - Addr: tss.lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }}) - - // Wait for the 1st, non-fail-fast RPC to succeed. This ensures both server - // connections are made, because the first one has DropForLoadBalancing set - // to true. - var i int - for i = 0; i < 1000; i++ { - if _, err := testC.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err == nil { - break - } - time.Sleep(time.Millisecond) - } - if i >= 1000 { - t.Fatalf("%v.SayHello(_, _) = _, %v, want _, ", testC, err) - } - select { - case <-ctx.Done(): - t.Fatal("timed out", ctx.Err()) - default: - } - for _, failfast := range []bool{true, false} { - for i := 0; i < 3; i++ { - // Even RPCs should fail, because the 2st backend has - // DropForLoadBalancing set to true. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(failfast)); status.Code(err) != codes.Unavailable { - t.Errorf("%v.EmptyCall(_, _) = _, %v, want _, %s", testC, err, codes.Unavailable) - } - // Odd RPCs should succeed since they choose the non-drop-request - // backend according to the round robin policy. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(failfast)); err != nil { - t.Errorf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - } - } -} - -// When the balancer in use disconnects, grpclb should connect to the next address from resolved balancer address list. -func TestBalancerDisconnects(t *testing.T) { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - var ( - tests []*testServers - lbs []*grpc.Server - ) - for i := 0; i < 2; i++ { - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - be := &lbpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - } - var bes []*lbpb.Server - bes = append(bes, be) - sl := &lbpb.ServerList{ - Servers: bes, - } - tss.ls.sls <- sl - - tests = append(tests, tss) - lbs = append(lbs, tss.lb) - } - - creds := serverNameCheckCreds{ - expected: beServerName, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{ - Addr: tests[0].lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }, { - Addr: tests[1].lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }}) - - var p peer.Peer - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false), grpc.Peer(&p)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - if p.Addr.(*net.TCPAddr).Port != tests[0].bePorts[0] { - t.Fatalf("got peer: %v, want peer port: %v", p.Addr, tests[0].bePorts[0]) - } - - lbs[0].Stop() - // Stop balancer[0], balancer[1] should be used by grpclb. - // Check peer address to see if that happened. - for i := 0; i < 1000; i++ { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false), grpc.Peer(&p)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - if p.Addr.(*net.TCPAddr).Port == tests[1].bePorts[0] { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("No RPC sent to second backend after 1 second") -} - -type customGRPCLBBuilder struct { - balancer.Builder - name string -} - -func (b *customGRPCLBBuilder) Name() string { - return b.name -} - -const grpclbCustomFallbackName = "grpclb_with_custom_fallback_timeout" - -func init() { - balancer.Register(&customGRPCLBBuilder{ - Builder: newLBBuilderWithFallbackTimeout(100 * time.Millisecond), - name: grpclbCustomFallbackName, - }) -} - -func TestFallback(t *testing.T) { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - // Start a standalone backend. - beLis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen %v", err) - } - defer beLis.Close() - standaloneBEs := startBackends(beServerName, true, beLis) - defer stopBackends(standaloneBEs) - - be := &lbpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - } - var bes []*lbpb.Server - bes = append(bes, be) - sl := &lbpb.ServerList{ - Servers: bes, - } - tss.ls.sls <- sl - creds := serverNameCheckCreds{ - expected: beServerName, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithBalancerName(grpclbCustomFallbackName), - grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{ - Addr: "", - Type: resolver.GRPCLB, - ServerName: lbServerName, - }, { - Addr: beLis.Addr().String(), - Type: resolver.Backend, - ServerName: beServerName, - }}) - - var p peer.Peer - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false), grpc.Peer(&p)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - if p.Addr.String() != beLis.Addr().String() { - t.Fatalf("got peer: %v, want peer: %v", p.Addr, beLis.Addr()) - } - - r.NewAddress([]resolver.Address{{ - Addr: tss.lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }, { - Addr: beLis.Addr().String(), - Type: resolver.Backend, - ServerName: beServerName, - }}) - - for i := 0; i < 1000; i++ { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false), grpc.Peer(&p)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - if p.Addr.(*net.TCPAddr).Port == tss.bePorts[0] { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("No RPC sent to backend behind remote balancer after 1 second") -} - -type failPreRPCCred struct{} - -func (failPreRPCCred) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - if strings.Contains(uri[0], failtosendURI) { - return nil, fmt.Errorf("rpc should fail to send") - } - return nil, nil -} - -func (failPreRPCCred) RequireTransportSecurity() bool { - return false -} - -func checkStats(stats, expected *rpcStats) error { - if !stats.equal(expected) { - return fmt.Errorf("stats not equal: got %+v, want %+v", stats, expected) - } - return nil -} - -func runAndGetStats(t *testing.T, drop bool, runRPCs func(*grpc.ClientConn)) *rpcStats { - defer leakcheck.Check(t) - - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - tss.ls.sls <- &lbpb.ServerList{ - Servers: []*lbpb.Server{{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - Drop: drop, - }}, - } - tss.ls.statsDura = 100 * time.Millisecond - creds := serverNameCheckCreds{expected: beServerName} - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, r.Scheme()+":///"+beServerName, - grpc.WithTransportCredentials(&creds), - grpc.WithPerRPCCredentials(failPreRPCCred{}), - grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - - r.NewAddress([]resolver.Address{{ - Addr: tss.lbAddr, - Type: resolver.GRPCLB, - ServerName: lbServerName, - }}) - - runRPCs(cc) - time.Sleep(1 * time.Second) - stats := tss.ls.stats - return stats -} - -const ( - countRPC = 40 - failtosendURI = "failtosend" - dropErrDesc = "request dropped by grpclb" -) - -func TestGRPCLBStatsUnarySuccess(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - for i := 0; i < countRPC-1; i++ { - testC.EmptyCall(context.Background(), &testpb.Empty{}) - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC), - numCallsFinished: int64(countRPC), - numCallsFinishedKnownReceived: int64(countRPC), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsUnaryDrop(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, true, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), dropErrDesc) { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.EmptyCall(context.Background(), &testpb.Empty{}) - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC + c), - numCallsFinished: int64(countRPC + c), - numCallsFinishedWithClientFailedToSend: int64(c - 1), - numCallsDropped: map[string]int64{lbToken: int64(countRPC + 1)}, - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsUnaryFailedToSend(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, ", testC, err) - } - for i := 0; i < countRPC-1; i++ { - cc.Invoke(context.Background(), failtosendURI, &testpb.Empty{}, nil) - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC), - numCallsFinished: int64(countRPC), - numCallsFinishedWithClientFailedToSend: int64(countRPC - 1), - numCallsFinishedKnownReceived: 1, - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingSuccess(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - stream, err := testC.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_, _) = _, %v, want _, ", testC, err) - } - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - for i := 0; i < countRPC-1; i++ { - stream, err = testC.FullDuplexCall(context.Background()) - if err == nil { - // Wait for stream to end if err is nil. - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - } - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC), - numCallsFinished: int64(countRPC), - numCallsFinishedKnownReceived: int64(countRPC), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingDrop(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, true, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), dropErrDesc) { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.FullDuplexCall(context.Background()) - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC + c), - numCallsFinished: int64(countRPC + c), - numCallsFinishedWithClientFailedToSend: int64(c - 1), - numCallsDropped: map[string]int64{lbToken: int64(countRPC + 1)}, - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingFailedToSend(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - stream, err := testC.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_, _) = _, %v, want _, ", testC, err) - } - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - for i := 0; i < countRPC-1; i++ { - cc.NewStream(context.Background(), &grpc.StreamDesc{}, failtosendURI) - } - }) - - if err := checkStats(stats, &rpcStats{ - numCallsStarted: int64(countRPC), - numCallsFinished: int64(countRPC), - numCallsFinishedWithClientFailedToSend: int64(countRPC - 1), - numCallsFinishedKnownReceived: 1, - }); err != nil { - t.Fatal(err) - } -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util.go deleted file mode 100755 index 3194c07..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util.go +++ /dev/null @@ -1,214 +0,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. - * - */ - -package grpclb - -import ( - "fmt" - "sync" - "time" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/resolver" -) - -// The parent ClientConn should re-resolve when grpclb loses connection to the -// remote balancer. When the ClientConn inside grpclb gets a TransientFailure, -// it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's -// ResolveNow, and eventually results in re-resolve happening in parent -// ClientConn's resolver (DNS for example). -// -// parent -// ClientConn -// +-----------------------------------------------------------------+ -// | parent +---------------------------------+ | -// | DNS ClientConn | grpclb | | -// | resolver balancerWrapper | | | -// | + + | grpclb grpclb | | -// | | | | ManualResolver ClientConn | | -// | | | | + + | | -// | | | | | | Transient | | -// | | | | | | Failure | | -// | | | | | <--------- | | | -// | | | <--------------- | ResolveNow | | | -// | | <--------- | ResolveNow | | | | | -// | | ResolveNow | | | | | | -// | | | | | | | | -// | + + | + + | | -// | +---------------------------------+ | -// +-----------------------------------------------------------------+ - -// lbManualResolver is used by the ClientConn inside grpclb. It's a manual -// resolver with a special ResolveNow() function. -// -// When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn, -// so when grpclb client lose contact with remote balancers, the parent -// ClientConn's resolver will re-resolve. -type lbManualResolver struct { - scheme string - ccr resolver.ClientConn - - ccb balancer.ClientConn -} - -func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOption) (resolver.Resolver, error) { - r.ccr = cc - return r, nil -} - -func (r *lbManualResolver) Scheme() string { - return r.scheme -} - -// ResolveNow calls resolveNow on the parent ClientConn. -func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOption) { - r.ccb.ResolveNow(o) -} - -// Close is a noop for Resolver. -func (*lbManualResolver) Close() {} - -// NewAddress calls cc.NewAddress. -func (r *lbManualResolver) NewAddress(addrs []resolver.Address) { - r.ccr.NewAddress(addrs) -} - -// NewServiceConfig calls cc.NewServiceConfig. -func (r *lbManualResolver) NewServiceConfig(sc string) { - r.ccr.NewServiceConfig(sc) -} - -const subConnCacheTime = time.Second * 10 - -// lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache. -// SubConns will be kept in cache for subConnCacheTime before being removed. -// -// Its new and remove methods are updated to do cache first. -type lbCacheClientConn struct { - cc balancer.ClientConn - timeout time.Duration - - mu sync.Mutex - // subConnCache only keeps subConns that are being deleted. - subConnCache map[resolver.Address]*subConnCacheEntry - subConnToAddr map[balancer.SubConn]resolver.Address -} - -type subConnCacheEntry struct { - sc balancer.SubConn - - cancel func() - abortDeleting bool -} - -func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn { - return &lbCacheClientConn{ - cc: cc, - timeout: subConnCacheTime, - subConnCache: make(map[resolver.Address]*subConnCacheEntry), - subConnToAddr: make(map[balancer.SubConn]resolver.Address), - } -} - -func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - if len(addrs) != 1 { - return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs)) - } - addrWithoutMD := addrs[0] - addrWithoutMD.Metadata = nil - - ccc.mu.Lock() - defer ccc.mu.Unlock() - if entry, ok := ccc.subConnCache[addrWithoutMD]; ok { - // If entry is in subConnCache, the SubConn was being deleted. - // cancel function will never be nil. - entry.cancel() - delete(ccc.subConnCache, addrWithoutMD) - return entry.sc, nil - } - - scNew, err := ccc.cc.NewSubConn(addrs, opts) - if err != nil { - return nil, err - } - - ccc.subConnToAddr[scNew] = addrWithoutMD - return scNew, nil -} - -func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) { - ccc.mu.Lock() - defer ccc.mu.Unlock() - addr, ok := ccc.subConnToAddr[sc] - if !ok { - return - } - - if entry, ok := ccc.subConnCache[addr]; ok { - if entry.sc != sc { - // This could happen if NewSubConn was called multiple times for the - // same address, and those SubConns are all removed. We remove sc - // immediately here. - delete(ccc.subConnToAddr, sc) - ccc.cc.RemoveSubConn(sc) - } - return - } - - entry := &subConnCacheEntry{ - sc: sc, - } - ccc.subConnCache[addr] = entry - - timer := time.AfterFunc(ccc.timeout, func() { - ccc.mu.Lock() - if entry.abortDeleting { - return - } - ccc.cc.RemoveSubConn(sc) - delete(ccc.subConnToAddr, sc) - delete(ccc.subConnCache, addr) - ccc.mu.Unlock() - }) - entry.cancel = func() { - if !timer.Stop() { - // If stop was not successful, the timer has fired (this can only - // happen in a race). But the deleting function is blocked on ccc.mu - // because the mutex was held by the caller of this function. - // - // Set abortDeleting to true to abort the deleting function. When - // the lock is released, the deleting function will acquire the - // lock, check the value of abortDeleting and return. - entry.abortDeleting = true - } - } -} - -func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccc.cc.UpdateBalancerState(s, p) -} - -func (ccc *lbCacheClientConn) close() { - ccc.mu.Lock() - // Only cancel all existing timers. There's no need to remove SubConns. - for _, entry := range ccc.subConnCache { - entry.cancel() - } - ccc.mu.Unlock() -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util_test.go b/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util_test.go deleted file mode 100755 index 39d422a..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/grpclb_util_test.go +++ /dev/null @@ -1,219 +0,0 @@ -/* - * - * 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. - * - */ - -package grpclb - -import ( - "fmt" - "sync" - "testing" - "time" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/resolver" -) - -type mockSubConn struct { - balancer.SubConn -} - -type mockClientConn struct { - balancer.ClientConn - - mu sync.Mutex - subConns map[balancer.SubConn]resolver.Address -} - -func newMockClientConn() *mockClientConn { - return &mockClientConn{ - subConns: make(map[balancer.SubConn]resolver.Address), - } -} - -func (mcc *mockClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - sc := &mockSubConn{} - mcc.mu.Lock() - defer mcc.mu.Unlock() - mcc.subConns[sc] = addrs[0] - return sc, nil -} - -func (mcc *mockClientConn) RemoveSubConn(sc balancer.SubConn) { - mcc.mu.Lock() - defer mcc.mu.Unlock() - delete(mcc.subConns, sc) -} - -const testCacheTimeout = 100 * time.Millisecond - -func checkMockCC(mcc *mockClientConn, scLen int) error { - mcc.mu.Lock() - defer mcc.mu.Unlock() - if len(mcc.subConns) != scLen { - return fmt.Errorf("mcc = %+v, want len(mcc.subConns) = %v", mcc.subConns, scLen) - } - return nil -} - -func checkCacheCC(ccc *lbCacheClientConn, sccLen, sctaLen int) error { - ccc.mu.Lock() - defer ccc.mu.Unlock() - if len(ccc.subConnCache) != sccLen { - return fmt.Errorf("ccc = %+v, want len(ccc.subConnCache) = %v", ccc.subConnCache, sccLen) - } - if len(ccc.subConnToAddr) != sctaLen { - return fmt.Errorf("ccc = %+v, want len(ccc.subConnToAddr) = %v", ccc.subConnToAddr, sctaLen) - } - return nil -} - -// Test that SubConn won't be immediately removed. -func TestLBCacheClientConnExpire(t *testing.T) { - mcc := newMockClientConn() - if err := checkMockCC(mcc, 0); err != nil { - t.Fatal(err) - } - - ccc := newLBCacheClientConn(mcc) - ccc.timeout = testCacheTimeout - if err := checkCacheCC(ccc, 0, 0); err != nil { - t.Fatal(err) - } - - sc, _ := ccc.NewSubConn([]resolver.Address{{Addr: "address1"}}, balancer.NewSubConnOptions{}) - // One subconn in MockCC. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // No subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 0, 1); err != nil { - t.Fatal(err) - } - - ccc.RemoveSubConn(sc) - // One subconn in MockCC before timeout. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // One subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 1, 1); err != nil { - t.Fatal(err) - } - - // Should all become empty after timeout. - var err error - for i := 0; i < 2; i++ { - time.Sleep(testCacheTimeout) - err = checkMockCC(mcc, 0) - if err != nil { - continue - } - err = checkCacheCC(ccc, 0, 0) - if err != nil { - continue - } - } - if err != nil { - t.Fatal(err) - } -} - -// Test that NewSubConn with the same address of a SubConn being removed will -// reuse the SubConn and cancel the removing. -func TestLBCacheClientConnReuse(t *testing.T) { - mcc := newMockClientConn() - if err := checkMockCC(mcc, 0); err != nil { - t.Fatal(err) - } - - ccc := newLBCacheClientConn(mcc) - ccc.timeout = testCacheTimeout - if err := checkCacheCC(ccc, 0, 0); err != nil { - t.Fatal(err) - } - - sc, _ := ccc.NewSubConn([]resolver.Address{{Addr: "address1"}}, balancer.NewSubConnOptions{}) - // One subconn in MockCC. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // No subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 0, 1); err != nil { - t.Fatal(err) - } - - ccc.RemoveSubConn(sc) - // One subconn in MockCC before timeout. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // One subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 1, 1); err != nil { - t.Fatal(err) - } - - // Recreate the old subconn, this should cancel the deleting process. - sc, _ = ccc.NewSubConn([]resolver.Address{{Addr: "address1"}}, balancer.NewSubConnOptions{}) - // One subconn in MockCC. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // No subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 0, 1); err != nil { - t.Fatal(err) - } - - var err error - // Should not become empty after 2*timeout. - time.Sleep(2 * testCacheTimeout) - err = checkMockCC(mcc, 1) - if err != nil { - t.Fatal(err) - } - err = checkCacheCC(ccc, 0, 1) - if err != nil { - t.Fatal(err) - } - - // Call remove again, will delete after timeout. - ccc.RemoveSubConn(sc) - // One subconn in MockCC before timeout. - if err := checkMockCC(mcc, 1); err != nil { - t.Fatal(err) - } - // One subconn being deleted, and one in CacheCC. - if err := checkCacheCC(ccc, 1, 1); err != nil { - t.Fatal(err) - } - - // Should all become empty after timeout. - for i := 0; i < 2; i++ { - time.Sleep(testCacheTimeout) - err = checkMockCC(mcc, 0) - if err != nil { - continue - } - err = checkCacheCC(ccc, 0, 0) - if err != nil { - continue - } - } - if err != nil { - t.Fatal(err) - } -} diff --git a/examples/google.golang.org/grpc/balancer/grpclb/regenerate.sh b/examples/google.golang.org/grpc/balancer/grpclb/regenerate.sh deleted file mode 100755 index b8978e1..0000000 --- a/examples/google.golang.org/grpc/balancer/grpclb/regenerate.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/lb/v1 -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/lb/v1/load_balancer.proto > grpc/lb/v1/load_balancer.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/lb/v1/*.proto -popd -rm -f grpc_lb_v1/*.pb.go -cp "$TMP"/grpc/lb/v1/*.pb.go grpc_lb_v1/ - diff --git a/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin.go deleted file mode 100755 index 2eda0a1..0000000 --- a/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package roundrobin defines a roundrobin balancer. Roundrobin balancer is -// installed as one of the default balancers in gRPC, users don't need to -// explicitly install this balancer. -package roundrobin - -import ( - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/balancer/base" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// Name is the name of round_robin balancer. -const Name = "round_robin" - -// newBuilder creates a new roundrobin balancer builder. -func newBuilder() balancer.Builder { - return base.NewBalancerBuilder(Name, &rrPickerBuilder{}) -} - -func init() { - balancer.Register(newBuilder()) -} - -type rrPickerBuilder struct{} - -func (*rrPickerBuilder) Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker { - grpclog.Infof("roundrobinPicker: newPicker called with readySCs: %v", readySCs) - var scs []balancer.SubConn - for _, sc := range readySCs { - scs = append(scs, sc) - } - return &rrPicker{ - subConns: scs, - } -} - -type rrPicker struct { - // subConns is the snapshot of the roundrobin balancer when this picker was - // created. The slice is immutable. Each Get() will do a round robin - // selection from it and return the selected SubConn. - subConns []balancer.SubConn - - mu sync.Mutex - next int -} - -func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if len(p.subConns) <= 0 { - return nil, nil, balancer.ErrNoSubConnAvailable - } - - p.mu.Lock() - sc := p.subConns[p.next] - p.next = (p.next + 1) % len(p.subConns) - p.mu.Unlock() - return sc, nil, nil -} diff --git a/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go b/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go deleted file mode 100755 index 70d8af7..0000000 --- a/examples/google.golang.org/grpc/balancer/roundrobin/roundrobin_test.go +++ /dev/null @@ -1,477 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package roundrobin_test - -import ( - "fmt" - "net" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer/roundrobin" - "google.golang.org/grpc/codes" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - "google.golang.org/grpc/status" - testpb "google.golang.org/grpc/test/grpc_testing" -) - -type testServer struct { - testpb.TestServiceServer -} - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return &testpb.Empty{}, nil -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return nil -} - -type test struct { - servers []*grpc.Server - addresses []string -} - -func (t *test) cleanup() { - for _, s := range t.servers { - s.Stop() - } -} - -func startTestServers(count int) (_ *test, err error) { - t := &test{} - - defer func() { - if err != nil { - for _, s := range t.servers { - s.Stop() - } - } - }() - for i := 0; i < count; i++ { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - return nil, fmt.Errorf("Failed to listen %v", err) - } - - s := grpc.NewServer() - testpb.RegisterTestServiceServer(s, &testServer{}) - t.servers = append(t.servers, s) - t.addresses = append(t.addresses, lis.Addr().String()) - - go func(s *grpc.Server, l net.Listener) { - s.Serve(l) - }(s, lis) - } - - return t, nil -} - -func TestOneBackend(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - test, err := startTestServers(1) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) - // The second RPC should succeed. - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } -} - -func TestBackendsRoundRobin(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - backendCount := 5 - test, err := startTestServers(backendCount) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var resolvedAddrs []resolver.Address - for i := 0; i < backendCount; i++ { - resolvedAddrs = append(resolvedAddrs, resolver.Address{Addr: test.addresses[i]}) - } - - r.NewAddress(resolvedAddrs) - var p peer.Peer - // Make sure connections to all servers are up. - for si := 0; si < backendCount; si++ { - var connected bool - for i := 0; i < 1000; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() == test.addresses[si] { - connected = true - break - } - time.Sleep(time.Millisecond) - } - if !connected { - t.Fatalf("Connection to %v was not up after more than 1 second", test.addresses[si]) - } - } - - for i := 0; i < 3*backendCount; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() != test.addresses[i%backendCount] { - t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) - } - } -} - -func TestAddressesRemoved(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - test, err := startTestServers(1) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) - // The second RPC should succeed. - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - - r.NewAddress([]resolver.Address{}) - for i := 0; i < 1000; i++ { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) == codes.DeadlineExceeded { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("No RPC failed after removing all addresses, want RPC to fail with DeadlineExceeded") -} - -func TestCloseWithPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - test, err := startTestServers(1) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - testc := testpb.NewTestServiceClient(cc) - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until cc is closed. - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); status.Code(err) == codes.DeadlineExceeded { - t.Errorf("RPC failed because of deadline after cc is closed; want error the client connection is closing") - } - cancel() - }() - } - cc.Close() - wg.Wait() -} - -func TestNewAddressWhileBlocking(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - test, err := startTestServers(1) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) - // The second RPC should succeed. - ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, nil", err) - } - - r.NewAddress([]resolver.Address{}) - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until NewAddress is called. - testc.EmptyCall(context.Background(), &testpb.Empty{}) - }() - } - time.Sleep(50 * time.Millisecond) - r.NewAddress([]resolver.Address{{Addr: test.addresses[0]}}) - wg.Wait() -} - -func TestOneServerDown(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - backendCount := 3 - test, err := startTestServers(backendCount) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name), grpc.WithWaitForHandshake()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var resolvedAddrs []resolver.Address - for i := 0; i < backendCount; i++ { - resolvedAddrs = append(resolvedAddrs, resolver.Address{Addr: test.addresses[i]}) - } - - r.NewAddress(resolvedAddrs) - var p peer.Peer - // Make sure connections to all servers are up. - for si := 0; si < backendCount; si++ { - var connected bool - for i := 0; i < 1000; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() == test.addresses[si] { - connected = true - break - } - time.Sleep(time.Millisecond) - } - if !connected { - t.Fatalf("Connection to %v was not up after more than 1 second", test.addresses[si]) - } - } - - for i := 0; i < 3*backendCount; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() != test.addresses[i%backendCount] { - t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) - } - } - - // Stop one server, RPCs should roundrobin among the remaining servers. - backendCount-- - test.servers[backendCount].Stop() - // Loop until see server[backendCount-1] twice without seeing server[backendCount]. - var targetSeen int - for i := 0; i < 1000; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - targetSeen = 0 - t.Logf("EmptyCall() = _, %v, want _, ", err) - // Due to a race, this RPC could possibly get the connection that - // was closing, and this RPC may fail. Keep trying when this - // happens. - continue - } - switch p.Addr.String() { - case test.addresses[backendCount-1]: - targetSeen++ - case test.addresses[backendCount]: - // Reset targetSeen if peer is server[backendCount]. - targetSeen = 0 - } - // Break to make sure the last picked address is server[-1], so the following for loop won't be flaky. - if targetSeen >= 2 { - break - } - } - if targetSeen != 2 { - t.Fatal("Failed to see server[backendCount-1] twice without seeing server[backendCount]") - } - for i := 0; i < 3*backendCount; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() != test.addresses[i%backendCount] { - t.Errorf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) - } - } -} - -func TestAllServersDown(t *testing.T) { - defer leakcheck.Check(t) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - - backendCount := 3 - test, err := startTestServers(backendCount) - if err != nil { - t.Fatalf("failed to start servers: %v", err) - } - defer test.cleanup() - - cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name), grpc.WithWaitForHandshake()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - testc := testpb.NewTestServiceClient(cc) - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, err := testc.EmptyCall(ctx, &testpb.Empty{}); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var resolvedAddrs []resolver.Address - for i := 0; i < backendCount; i++ { - resolvedAddrs = append(resolvedAddrs, resolver.Address{Addr: test.addresses[i]}) - } - - r.NewAddress(resolvedAddrs) - var p peer.Peer - // Make sure connections to all servers are up. - for si := 0; si < backendCount; si++ { - var connected bool - for i := 0; i < 1000; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() == test.addresses[si] { - connected = true - break - } - time.Sleep(time.Millisecond) - } - if !connected { - t.Fatalf("Connection to %v was not up after more than 1 second", test.addresses[si]) - } - } - - for i := 0; i < 3*backendCount; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(&p)); err != nil { - t.Fatalf("EmptyCall() = _, %v, want _, ", err) - } - if p.Addr.String() != test.addresses[i%backendCount] { - t.Fatalf("Index %d: want peer %v, got peer %v", i, test.addresses[i%backendCount], p.Addr.String()) - } - } - - // All servers are stopped, failfast RPC should fail with unavailable. - for i := 0; i < backendCount; i++ { - test.servers[i].Stop() - } - time.Sleep(100 * time.Millisecond) - for i := 0; i < 1000; i++ { - if _, err := testc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) == codes.Unavailable { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("Failfast RPCs didn't fail with Unavailable after all servers are stopped") -} diff --git a/examples/google.golang.org/grpc/balancer_conn_wrappers.go b/examples/google.golang.org/grpc/balancer_conn_wrappers.go deleted file mode 100755 index c23f817..0000000 --- a/examples/google.golang.org/grpc/balancer_conn_wrappers.go +++ /dev/null @@ -1,300 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "sync" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// scStateUpdate contains the subConn and the new state it changed to. -type scStateUpdate struct { - sc balancer.SubConn - state connectivity.State -} - -// scStateUpdateBuffer is an unbounded channel for scStateChangeTuple. -// TODO make a general purpose buffer that uses interface{}. -type scStateUpdateBuffer struct { - c chan *scStateUpdate - mu sync.Mutex - backlog []*scStateUpdate -} - -func newSCStateUpdateBuffer() *scStateUpdateBuffer { - return &scStateUpdateBuffer{ - c: make(chan *scStateUpdate, 1), - } -} - -func (b *scStateUpdateBuffer) put(t *scStateUpdate) { - b.mu.Lock() - defer b.mu.Unlock() - if len(b.backlog) == 0 { - select { - case b.c <- t: - return - default: - } - } - b.backlog = append(b.backlog, t) -} - -func (b *scStateUpdateBuffer) load() { - b.mu.Lock() - defer b.mu.Unlock() - if len(b.backlog) > 0 { - select { - case b.c <- b.backlog[0]: - b.backlog[0] = nil - b.backlog = b.backlog[1:] - default: - } - } -} - -// get returns the channel that the scStateUpdate will be sent to. -// -// Upon receiving, the caller should call load to send another -// scStateChangeTuple onto the channel if there is any. -func (b *scStateUpdateBuffer) get() <-chan *scStateUpdate { - return b.c -} - -// resolverUpdate contains the new resolved addresses or error if there's -// any. -type resolverUpdate struct { - addrs []resolver.Address - err error -} - -// ccBalancerWrapper is a wrapper on top of cc for balancers. -// It implements balancer.ClientConn interface. -type ccBalancerWrapper struct { - cc *ClientConn - balancer balancer.Balancer - stateChangeQueue *scStateUpdateBuffer - resolverUpdateCh chan *resolverUpdate - done chan struct{} - - mu sync.Mutex - subConns map[*acBalancerWrapper]struct{} -} - -func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { - ccb := &ccBalancerWrapper{ - cc: cc, - stateChangeQueue: newSCStateUpdateBuffer(), - resolverUpdateCh: make(chan *resolverUpdate, 1), - done: make(chan struct{}), - subConns: make(map[*acBalancerWrapper]struct{}), - } - go ccb.watcher() - ccb.balancer = b.Build(ccb, bopts) - return ccb -} - -// watcher balancer functions sequentially, so the balancer can be implemented -// lock-free. -func (ccb *ccBalancerWrapper) watcher() { - for { - select { - case t := <-ccb.stateChangeQueue.get(): - ccb.stateChangeQueue.load() - select { - case <-ccb.done: - ccb.balancer.Close() - return - default: - } - ccb.balancer.HandleSubConnStateChange(t.sc, t.state) - case t := <-ccb.resolverUpdateCh: - select { - case <-ccb.done: - ccb.balancer.Close() - return - default: - } - ccb.balancer.HandleResolvedAddrs(t.addrs, t.err) - case <-ccb.done: - } - - select { - case <-ccb.done: - ccb.balancer.Close() - ccb.mu.Lock() - scs := ccb.subConns - ccb.subConns = nil - ccb.mu.Unlock() - for acbw := range scs { - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) - } - return - default: - } - } -} - -func (ccb *ccBalancerWrapper) close() { - close(ccb.done) -} - -func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - // When updating addresses for a SubConn, if the address in use is not in - // the new addresses, the old ac will be tearDown() and a new ac will be - // created. tearDown() generates a state change with Shutdown state, we - // don't want the balancer to receive this state change. So before - // tearDown() on the old ac, ac.acbw (acWrapper) will be set to nil, and - // this function will be called with (nil, Shutdown). We don't need to call - // balancer method in this case. - if sc == nil { - return - } - ccb.stateChangeQueue.put(&scStateUpdate{ - sc: sc, - state: s, - }) -} - -func (ccb *ccBalancerWrapper) handleResolvedAddrs(addrs []resolver.Address, err error) { - select { - case <-ccb.resolverUpdateCh: - default: - } - ccb.resolverUpdateCh <- &resolverUpdate{ - addrs: addrs, - err: err, - } -} - -func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - if len(addrs) <= 0 { - return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") - } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed") - } - ac, err := ccb.cc.newAddrConn(addrs) - if err != nil { - return nil, err - } - acbw := &acBalancerWrapper{ac: ac} - acbw.ac.mu.Lock() - ac.acbw = acbw - acbw.ac.mu.Unlock() - ccb.subConns[acbw] = struct{}{} - return acbw, nil -} - -func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - acbw, ok := sc.(*acBalancerWrapper) - if !ok { - return - } - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } - delete(ccb.subConns, acbw) - ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) -} - -func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } - ccb.cc.csMgr.updateState(s) - ccb.cc.blockingpicker.updatePicker(p) -} - -func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOption) { - ccb.cc.resolveNow(o) -} - -func (ccb *ccBalancerWrapper) Target() string { - return ccb.cc.target -} - -// acBalancerWrapper is a wrapper on top of ac for balancers. -// It implements balancer.SubConn interface. -type acBalancerWrapper struct { - mu sync.Mutex - ac *addrConn -} - -func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { - acbw.mu.Lock() - defer acbw.mu.Unlock() - if len(addrs) <= 0 { - acbw.ac.tearDown(errConnDrain) - return - } - if !acbw.ac.tryUpdateAddrs(addrs) { - cc := acbw.ac.cc - acbw.ac.mu.Lock() - // Set old ac.acbw to nil so the Shutdown state update will be ignored - // by balancer. - // - // TODO(bar) the state transition could be wrong when tearDown() old ac - // and creating new ac, fix the transition. - acbw.ac.acbw = nil - acbw.ac.mu.Unlock() - acState := acbw.ac.getState() - acbw.ac.tearDown(errConnDrain) - - if acState == connectivity.Shutdown { - return - } - - ac, err := cc.newAddrConn(addrs) - if err != nil { - grpclog.Warningf("acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err) - return - } - acbw.ac = ac - ac.mu.Lock() - ac.acbw = acbw - ac.mu.Unlock() - if acState != connectivity.Idle { - ac.connect() - } - } -} - -func (acbw *acBalancerWrapper) Connect() { - acbw.mu.Lock() - defer acbw.mu.Unlock() - acbw.ac.connect() -} - -func (acbw *acBalancerWrapper) getAddrConn() *addrConn { - acbw.mu.Lock() - defer acbw.mu.Unlock() - return acbw.ac -} diff --git a/examples/google.golang.org/grpc/balancer_switching_test.go b/examples/google.golang.org/grpc/balancer_switching_test.go deleted file mode 100755 index 0dcd916..0000000 --- a/examples/google.golang.org/grpc/balancer_switching_test.go +++ /dev/null @@ -1,469 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "math" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/balancer/roundrobin" - "google.golang.org/grpc/connectivity" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" -) - -var _ balancer.Builder = &magicalLB{} -var _ balancer.Balancer = &magicalLB{} - -// magicalLB is a ringer for grpclb. It is used to avoid circular dependencies on the grpclb package -type magicalLB struct{} - -func (b *magicalLB) Name() string { - return "grpclb" -} - -func (b *magicalLB) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - return b -} - -func (b *magicalLB) HandleSubConnStateChange(balancer.SubConn, connectivity.State) {} - -func (b *magicalLB) HandleResolvedAddrs([]resolver.Address, error) {} - -func (b *magicalLB) Close() {} - -func init() { - balancer.Register(&magicalLB{}) -} - -func checkPickFirst(cc *ClientConn, servers []*server) error { - var ( - req = "port" - reply string - err error - ) - connected := false - for i := 0; i < 5000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); errorDesc(err) == servers[0].port { - if connected { - // connected is set to false if peer is not server[0]. So if - // connected is true here, this is the second time we saw - // server[0] in a row. Break because pickfirst is in effect. - break - } - connected = true - } else { - connected = false - } - time.Sleep(time.Millisecond) - } - if !connected { - return fmt.Errorf("pickfirst is not in effect after 5 second, EmptyCall() = _, %v, want _, %v", err, servers[0].port) - } - // The following RPCs should all succeed with the first server. - for i := 0; i < 3; i++ { - err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - if errorDesc(err) != servers[0].port { - return fmt.Errorf("Index %d: want peer %v, got peer %v", i, servers[0].port, err) - } - } - return nil -} - -func checkRoundRobin(cc *ClientConn, servers []*server) error { - var ( - req = "port" - reply string - err error - ) - - // Make sure connections to all servers are up. - for i := 0; i < 2; i++ { - // Do this check twice, otherwise the first RPC's transport may still be - // picked by the closing pickfirst balancer, and the test becomes flaky. - for _, s := range servers { - var up bool - for i := 0; i < 5000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); errorDesc(err) == s.port { - up = true - break - } - time.Sleep(time.Millisecond) - } - if !up { - return fmt.Errorf("server %v is not up within 5 second", s.port) - } - } - } - - serverCount := len(servers) - for i := 0; i < 3*serverCount; i++ { - err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - if errorDesc(err) != servers[i%serverCount].port { - return fmt.Errorf("Index %d: want peer %v, got peer %v", i, servers[i%serverCount].port, err) - } - } - return nil -} - -func TestSwitchBalancer(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The default balancer is pickfirst. - if err := checkPickFirst(cc, servers); err != nil { - t.Fatalf("check pickfirst returned non-nil error: %v", err) - } - // Switch to roundrobin. - cc.handleServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) - if err := checkRoundRobin(cc, servers); err != nil { - t.Fatalf("check roundrobin returned non-nil error: %v", err) - } - // Switch to pickfirst. - cc.handleServiceConfig(`{"loadBalancingPolicy": "pick_first"}`) - if err := checkPickFirst(cc, servers); err != nil { - t.Fatalf("check pickfirst returned non-nil error: %v", err) - } -} - -// Test that balancer specified by dial option will not be overridden. -func TestBalancerDialOption(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{}), WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The init balancer is roundrobin. - if err := checkRoundRobin(cc, servers); err != nil { - t.Fatalf("check roundrobin returned non-nil error: %v", err) - } - // Switch to pickfirst. - cc.handleServiceConfig(`{"loadBalancingPolicy": "pick_first"}`) - // Balancer is still roundrobin. - if err := checkRoundRobin(cc, servers); err != nil { - t.Fatalf("check roundrobin returned non-nil error: %v", err) - } -} - -// First addr update contains grpclb. -func TestSwitchBalancerGRPCLBFirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - // ClientConn will switch balancer to grpclb when receives an address of - // type GRPCLB. - r.NewAddress([]resolver.Address{{Addr: "backend"}, {Addr: "grpclb", Type: resolver.GRPCLB}}) - var isGRPCLB bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("after 5 second, cc.balancer is of type %v, not grpclb", cc.curBalancerName) - } - - // New update containing new backend and new grpclb. Should not switch - // balancer. - r.NewAddress([]resolver.Address{{Addr: "backend2"}, {Addr: "grpclb2", Type: resolver.GRPCLB}}) - for i := 0; i < 200; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if !isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("within 200 ms, cc.balancer switched to !grpclb, want grpclb") - } - - var isPickFirst bool - // Switch balancer to pickfirst. - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isPickFirst = cc.curBalancerName == PickFirstBalancerName - cc.mu.Unlock() - if isPickFirst { - break - } - time.Sleep(time.Millisecond) - } - if !isPickFirst { - t.Fatalf("after 5 second, cc.balancer is of type %v, not pick_first", cc.curBalancerName) - } -} - -// First addr update does not contain grpclb. -func TestSwitchBalancerGRPCLBSecond(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - var isPickFirst bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isPickFirst = cc.curBalancerName == PickFirstBalancerName - cc.mu.Unlock() - if isPickFirst { - break - } - time.Sleep(time.Millisecond) - } - if !isPickFirst { - t.Fatalf("after 5 second, cc.balancer is of type %v, not pick_first", cc.curBalancerName) - } - - // ClientConn will switch balancer to grpclb when receives an address of - // type GRPCLB. - r.NewAddress([]resolver.Address{{Addr: "backend"}, {Addr: "grpclb", Type: resolver.GRPCLB}}) - var isGRPCLB bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("after 5 second, cc.balancer is of type %v, not grpclb", cc.curBalancerName) - } - - // New update containing new backend and new grpclb. Should not switch - // balancer. - r.NewAddress([]resolver.Address{{Addr: "backend2"}, {Addr: "grpclb2", Type: resolver.GRPCLB}}) - for i := 0; i < 200; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if !isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("within 200 ms, cc.balancer switched to !grpclb, want grpclb") - } - - // Switch balancer back. - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isPickFirst = cc.curBalancerName == PickFirstBalancerName - cc.mu.Unlock() - if isPickFirst { - break - } - time.Sleep(time.Millisecond) - } - if !isPickFirst { - t.Fatalf("after 5 second, cc.balancer is of type %v, not pick_first", cc.curBalancerName) - } -} - -// Test that if the current balancer is roundrobin, after switching to grpclb, -// when the resolved address doesn't contain grpclb addresses, balancer will be -// switched back to roundrobin. -func TestSwitchBalancerGRPCLBRoundRobin(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - r.NewServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) - - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - var isRoundRobin bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isRoundRobin = cc.curBalancerName == "round_robin" - cc.mu.Unlock() - if isRoundRobin { - break - } - time.Sleep(time.Millisecond) - } - if !isRoundRobin { - t.Fatalf("after 5 second, cc.balancer is of type %v, not round_robin", cc.curBalancerName) - } - - // ClientConn will switch balancer to grpclb when receives an address of - // type GRPCLB. - r.NewAddress([]resolver.Address{{Addr: "grpclb", Type: resolver.GRPCLB}}) - var isGRPCLB bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("after 5 second, cc.balancer is of type %v, not grpclb", cc.curBalancerName) - } - - // Switch balancer back. - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isRoundRobin = cc.curBalancerName == "round_robin" - cc.mu.Unlock() - if isRoundRobin { - break - } - time.Sleep(time.Millisecond) - } - if !isRoundRobin { - t.Fatalf("after 5 second, cc.balancer is of type %v, not round_robin", cc.curBalancerName) - } -} - -// Test that if resolved address list contains grpclb, the balancer option in -// service config won't take effect. But when there's no grpclb address in a new -// resolved address list, balancer will be switched to the new one. -func TestSwitchBalancerGRPCLBServiceConfig(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - var isPickFirst bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isPickFirst = cc.curBalancerName == PickFirstBalancerName - cc.mu.Unlock() - if isPickFirst { - break - } - time.Sleep(time.Millisecond) - } - if !isPickFirst { - t.Fatalf("after 5 second, cc.balancer is of type %v, not pick_first", cc.curBalancerName) - } - - // ClientConn will switch balancer to grpclb when receives an address of - // type GRPCLB. - r.NewAddress([]resolver.Address{{Addr: "grpclb", Type: resolver.GRPCLB}}) - var isGRPCLB bool - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isGRPCLB = cc.curBalancerName == "grpclb" - cc.mu.Unlock() - if isGRPCLB { - break - } - time.Sleep(time.Millisecond) - } - if !isGRPCLB { - t.Fatalf("after 5 second, cc.balancer is of type %v, not grpclb", cc.curBalancerName) - } - - r.NewServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) - var isRoundRobin bool - for i := 0; i < 200; i++ { - cc.mu.Lock() - isRoundRobin = cc.curBalancerName == "round_robin" - cc.mu.Unlock() - if isRoundRobin { - break - } - time.Sleep(time.Millisecond) - } - // Balancer should NOT switch to round_robin because resolved list contains - // grpclb. - if isRoundRobin { - t.Fatalf("within 200 ms, cc.balancer switched to round_robin, want grpclb") - } - - // Switch balancer back. - r.NewAddress([]resolver.Address{{Addr: "backend"}}) - for i := 0; i < 5000; i++ { - cc.mu.Lock() - isRoundRobin = cc.curBalancerName == "round_robin" - cc.mu.Unlock() - if isRoundRobin { - break - } - time.Sleep(time.Millisecond) - } - if !isRoundRobin { - t.Fatalf("after 5 second, cc.balancer is of type %v, not round_robin", cc.curBalancerName) - } -} diff --git a/examples/google.golang.org/grpc/balancer_test.go b/examples/google.golang.org/grpc/balancer_test.go deleted file mode 100755 index 8675e7d..0000000 --- a/examples/google.golang.org/grpc/balancer_test.go +++ /dev/null @@ -1,804 +0,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. - * - */ - -package grpc - -import ( - "fmt" - "math" - "strconv" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/status" - - // V1 balancer tests use passthrough resolver instead of dns. - // TODO(bar) remove this when removing v1 balaner entirely. - - _ "google.golang.org/grpc/resolver/passthrough" -) - -type testWatcher struct { - // the channel to receives name resolution updates - update chan *naming.Update - // the side channel to get to know how many updates in a batch - side chan int - // the channel to notify update injector that the update reading is done - readDone chan int -} - -func (w *testWatcher) Next() (updates []*naming.Update, err error) { - n := <-w.side - if n == 0 { - return nil, fmt.Errorf("w.side is closed") - } - for i := 0; i < n; i++ { - u := <-w.update - if u != nil { - updates = append(updates, u) - } - } - w.readDone <- 0 - return -} - -func (w *testWatcher) Close() { - close(w.side) -} - -// Inject naming resolution updates to the testWatcher. -func (w *testWatcher) inject(updates []*naming.Update) { - w.side <- len(updates) - for _, u := range updates { - w.update <- u - } - <-w.readDone -} - -type testNameResolver struct { - w *testWatcher - addr string -} - -func (r *testNameResolver) Resolve(target string) (naming.Watcher, error) { - r.w = &testWatcher{ - update: make(chan *naming.Update, 1), - side: make(chan int, 1), - readDone: make(chan int), - } - r.w.side <- 1 - r.w.update <- &naming.Update{ - Op: naming.Add, - Addr: r.addr, - } - go func() { - <-r.w.readDone - }() - return r.w, nil -} - -func startServers(t *testing.T, numServers int, maxStreams uint32) ([]*server, *testNameResolver, func()) { - var servers []*server - for i := 0; i < numServers; i++ { - s := newTestServer() - servers = append(servers, s) - go s.start(t, 0, maxStreams) - s.wait(t, 2*time.Second) - } - // Point to server[0] - addr := "localhost:" + servers[0].port - return servers, &testNameResolver{ - addr: addr, - }, func() { - for i := 0; i < numServers; i++ { - servers[i].stop() - } - } -} - -func TestNameDiscovery(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers on 2 ports. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - req := "port" - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Inject the name resolution change to remove servers[0] and add servers[1]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - // Loop until the rpcs in flight talks to servers[1]. - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestEmptyAddrs(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, reply = %q, want %q, ", err, reply, expectedResponse) - } - // Inject name resolution change to remove the server so that there is no address - // available after that. - u := &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until the above updates apply. - for { - time.Sleep(10 * time.Millisecond) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := cc.Invoke(ctx, "/foo/bar", &expectedRequest, &reply); err != nil { - cancel() - break - } - cancel() - } -} - -func TestRoundRobin(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - // Add server2[2] to the service discovery. - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until both servers[2] are up. - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[2].port { - break - } - time.Sleep(10 * time.Millisecond) - } - // Check the incoming RPCs served in a round-robin manner. - for i := 0; i < 10; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[i%numServers].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", i, err, servers[i%numServers].port) - } - } -} - -func TestCloseWithPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err != nil { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Remove the server. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Loop until the above update applies. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := cc.Invoke(ctx, "/foo/bar", &expectedRequest, &reply, FailFast(false)); status.Code(err) == codes.DeadlineExceeded { - cancel() - break - } - time.Sleep(10 * time.Millisecond) - cancel() - } - // Issue 2 RPCs which should be completed with error status once cc is closed. - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - go func() { - defer wg.Done() - var reply string - time.Sleep(5 * time.Millisecond) - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - time.Sleep(5 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestGetOnWaitChannel(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Remove all servers so that all upcoming RPCs will block on waitCh. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - for { - var reply string - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := cc.Invoke(ctx, "/foo/bar", &expectedRequest, &reply, FailFast(false)); status.Code(err) == codes.DeadlineExceeded { - cancel() - break - } - cancel() - time.Sleep(10 * time.Millisecond) - } - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want ", err) - } - }() - // Add a connected server to get the above RPC through. - updates = []*naming.Update{{ - Op: naming.Add, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Wait until the above RPC succeeds. - wg.Wait() -} - -func TestOneServerDown(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}), WithWaitForHandshake()) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, kill server[0]. - servers[0].stop() - wg.Done() - }() - - // All non-failfast RPCs should not block because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is killed around the same time to make it racy between balancer and gRPC internals. - cc.Invoke(context.Background(), "/foo/bar", &req, &reply, FailFast(false)) - wg.Done() - }() - } - wg.Wait() -} - -func TestOneAddressRemoval(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, delete server[0]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - r.w.inject(updates) - wg.Done() - }() - - // All non-failfast RPCs should not fail because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - var reply string - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is removed around the same time to make it racy between balancer and gRPC internals. - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want nil", err) - } - wg.Done() - }() - } - wg.Wait() -} - -func checkServerUp(t *testing.T, currentServer *server) { - req := "port" - port := currentServer.port - cc, err := Dial("passthrough:///localhost:"+port, WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == port { - break - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstEmptyAddrs(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, reply = %q, want %q, ", err, reply, expectedResponse) - } - // Inject name resolution change to remove the server so that there is no address - // available after that. - u := &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until the above updates apply. - for { - time.Sleep(10 * time.Millisecond) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := cc.Invoke(ctx, "/foo/bar", &expectedRequest, &reply); err != nil { - cancel() - break - } - cancel() - } -} - -func TestPickFirstCloseWithPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err != nil { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Remove the server. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Loop until the above update applies. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := cc.Invoke(ctx, "/foo/bar", &expectedRequest, &reply, FailFast(false)); status.Code(err) == codes.DeadlineExceeded { - cancel() - break - } - time.Sleep(10 * time.Millisecond) - cancel() - } - // Issue 2 RPCs which should be completed with error status once cc is closed. - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - go func() { - defer wg.Done() - var reply string - time.Sleep(5 * time.Millisecond) - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - time.Sleep(5 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestPickFirstOrderAllServerUp(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] and [2] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - - // Loop until all 3 servers are up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - checkServerUp(t, servers[2]) - - // Check the incoming RPCs served in server[0] - req := "port" - var reply string - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[0] in the balancer, the incoming RPCs served in server[1] - // For test addrconn, close server[0] instead - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until it changes to server[1] - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Add server[0] back to the balancer, the incoming RPCs served in server[1] - // Add is append operation, the order of Notify now is {server[1].port server[2].port server[0].port} - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[1] in the balancer, the incoming RPCs served in server[2] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[2].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[2].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 2, err, servers[2].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[2] in the balancer, the incoming RPCs served in server[0] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstOrderOneServerDown(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}), WithWaitForHandshake()) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] and [2] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - - // Loop until all 3 servers are up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - checkServerUp(t, servers[2]) - - // Check the incoming RPCs served in server[0] - req := "port" - var reply string - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // server[0] down, incoming RPCs served in server[1], but the order of Notify still remains - // {server[0] server[1] server[2]} - servers[0].stop() - // Loop until it changes to server[1] - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // up the server[0] back, the incoming RPCs served in server[1] - p, _ := strconv.Atoi(servers[0].port) - servers[0] = newTestServer() - go servers[0].start(t, p, math.MaxUint32) - defer servers[0].stop() - servers[0].wait(t, 2*time.Second) - checkServerUp(t, servers[0]) - - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[1] in the balancer, the incoming RPCs served in server[0] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstOneAddressRemoval(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///localhost:"+servers[0].port, WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - - // Create a new cc to Loop until servers[1] is up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, delete server[0]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - r.w.inject(updates) - wg.Done() - }() - - // All non-failfast RPCs should not fail because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - var reply string - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is removed around the same time to make it racy between balancer and gRPC internals. - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want nil", err) - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/examples/google.golang.org/grpc/balancer_v1_wrapper.go b/examples/google.golang.org/grpc/balancer_v1_wrapper.go deleted file mode 100755 index e0ce32c..0000000 --- a/examples/google.golang.org/grpc/balancer_v1_wrapper.go +++ /dev/null @@ -1,328 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "strings" - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" -) - -type balancerWrapperBuilder struct { - b Balancer // The v1 balancer. -} - -func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - targetAddr := cc.Target() - targetSplitted := strings.Split(targetAddr, ":///") - if len(targetSplitted) >= 2 { - targetAddr = targetSplitted[1] - } - - bwb.b.Start(targetAddr, BalancerConfig{ - DialCreds: opts.DialCreds, - Dialer: opts.Dialer, - }) - _, pickfirst := bwb.b.(*pickFirst) - bw := &balancerWrapper{ - balancer: bwb.b, - pickfirst: pickfirst, - cc: cc, - targetAddr: targetAddr, - startCh: make(chan struct{}), - conns: make(map[resolver.Address]balancer.SubConn), - connSt: make(map[balancer.SubConn]*scState), - csEvltr: &balancer.ConnectivityStateEvaluator{}, - state: connectivity.Idle, - } - cc.UpdateBalancerState(connectivity.Idle, bw) - go bw.lbWatcher() - return bw -} - -func (bwb *balancerWrapperBuilder) Name() string { - return "wrapper" -} - -type scState struct { - addr Address // The v1 address type. - s connectivity.State - down func(error) -} - -type balancerWrapper struct { - balancer Balancer // The v1 balancer. - pickfirst bool - - cc balancer.ClientConn - targetAddr string // Target without the scheme. - - mu sync.Mutex - conns map[resolver.Address]balancer.SubConn - connSt map[balancer.SubConn]*scState - // This channel is closed when handling the first resolver result. - // lbWatcher blocks until this is closed, to avoid race between - // - NewSubConn is created, cc wants to notify balancer of state changes; - // - Build hasn't return, cc doesn't have access to balancer. - startCh chan struct{} - - // To aggregate the connectivity state. - csEvltr *balancer.ConnectivityStateEvaluator - state connectivity.State -} - -// lbWatcher watches the Notify channel of the balancer and manages -// connections accordingly. -func (bw *balancerWrapper) lbWatcher() { - <-bw.startCh - notifyCh := bw.balancer.Notify() - if notifyCh == nil { - // There's no resolver in the balancer. Connect directly. - a := resolver.Address{ - Addr: bw.targetAddr, - Type: resolver.Backend, - } - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: Address{Addr: bw.targetAddr}, - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - return - } - - for addrs := range notifyCh { - grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs) - if bw.pickfirst { - var ( - oldA resolver.Address - oldSC balancer.SubConn - ) - bw.mu.Lock() - for oldA, oldSC = range bw.conns { - break - } - bw.mu.Unlock() - if len(addrs) <= 0 { - if oldSC != nil { - // Teardown old sc. - bw.mu.Lock() - delete(bw.conns, oldA) - delete(bw.connSt, oldSC) - bw.mu.Unlock() - bw.cc.RemoveSubConn(oldSC) - } - continue - } - - var newAddrs []resolver.Address - for _, a := range addrs { - newAddr := resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - } - newAddrs = append(newAddrs, newAddr) - } - if oldSC == nil { - // Create new sc. - sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err) - } else { - bw.mu.Lock() - // For pickfirst, there should be only one SubConn, so the - // address doesn't matter. All states updating (up and down) - // and picking should all happen on that only SubConn. - bw.conns[resolver.Address{}] = sc - bw.connSt[sc] = &scState{ - addr: addrs[0], // Use the first address. - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } else { - bw.mu.Lock() - bw.connSt[oldSC].addr = addrs[0] - bw.mu.Unlock() - oldSC.UpdateAddresses(newAddrs) - } - } else { - var ( - add []resolver.Address // Addresses need to setup connections. - del []balancer.SubConn // Connections need to tear down. - ) - resAddrs := make(map[resolver.Address]Address) - for _, a := range addrs { - resAddrs[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - }] = a - } - bw.mu.Lock() - for a := range resAddrs { - if _, ok := bw.conns[a]; !ok { - add = append(add, a) - } - } - for a, c := range bw.conns { - if _, ok := resAddrs[a]; !ok { - del = append(del, c) - delete(bw.conns, a) - // Keep the state of this sc in bw.connSt until its state becomes Shutdown. - } - } - bw.mu.Unlock() - for _, a := range add { - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: resAddrs[a], - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } - for _, c := range del { - bw.cc.RemoveSubConn(c) - } - } - } -} - -func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - bw.mu.Lock() - defer bw.mu.Unlock() - scSt, ok := bw.connSt[sc] - if !ok { - return - } - if s == connectivity.Idle { - sc.Connect() - } - oldS := scSt.s - scSt.s = s - if oldS != connectivity.Ready && s == connectivity.Ready { - scSt.down = bw.balancer.Up(scSt.addr) - } else if oldS == connectivity.Ready && s != connectivity.Ready { - if scSt.down != nil { - scSt.down(errConnClosing) - } - } - sa := bw.csEvltr.RecordTransition(oldS, s) - if bw.state != sa { - bw.state = sa - } - bw.cc.UpdateBalancerState(bw.state, bw) - if s == connectivity.Shutdown { - // Remove state for this sc. - delete(bw.connSt, sc) - } -} - -func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - // There should be a resolver inside the balancer. - // All updates here, if any, are ignored. -} - -func (bw *balancerWrapper) Close() { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - bw.balancer.Close() -} - -// The picker is the balancerWrapper itself. -// Pick should never return ErrNoSubConnAvailable. -// It either blocks or returns error, consistent with v1 balancer Get(). -func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - failfast := true // Default failfast is true. - if ss, ok := rpcInfoFromContext(ctx); ok { - failfast = ss.failfast - } - a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast}) - if err != nil { - return nil, nil, err - } - var done func(balancer.DoneInfo) - if p != nil { - done = func(i balancer.DoneInfo) { p() } - } - var sc balancer.SubConn - bw.mu.Lock() - defer bw.mu.Unlock() - if bw.pickfirst { - // Get the first sc in conns. - for _, sc = range bw.conns { - break - } - } else { - var ok bool - sc, ok = bw.conns[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, - ServerName: "", - Metadata: a.Metadata, - }] - if !ok && failfast { - return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") - } - if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) { - // If the returned sc is not ready and RPC is failfast, - // return error, and this RPC will fail. - return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") - } - } - - return sc, done, nil -} diff --git a/examples/google.golang.org/grpc/benchmark/benchmain/main.go b/examples/google.golang.org/grpc/benchmark/benchmain/main.go deleted file mode 100755 index 5a9e478..0000000 --- a/examples/google.golang.org/grpc/benchmark/benchmain/main.go +++ /dev/null @@ -1,546 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* -Package main provides benchmark with setting flags. - -An example to run some benchmarks with profiling enabled: - -go run benchmark/benchmain/main.go -benchtime=10s -workloads=all \ - -compression=on -maxConcurrentCalls=1 -trace=off \ - -reqSizeBytes=1,1048576 -respSizeBytes=1,1048576 -networkMode=Local \ - -cpuProfile=cpuProf -memProfile=memProf -memProfileRate=10000 -resultFile=result - -As a suggestion, when creating a branch, you can run this benchmark and save the result -file "-resultFile=basePerf", and later when you at the middle of the work or finish the -work, you can get the benchmark result and compare it with the base anytime. - -Assume there are two result files names as "basePerf" and "curPerf" created by adding --resultFile=basePerf and -resultFile=curPerf. - To format the curPerf, run: - go run benchmark/benchresult/main.go curPerf - To observe how the performance changes based on a base result, run: - go run benchmark/benchresult/main.go basePerf curPerf -*/ -package main - -import ( - "encoding/gob" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "os" - "reflect" - "runtime" - "runtime/pprof" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - bm "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/latency" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/test/bufconn" -) - -const ( - modeOn = "on" - modeOff = "off" - modeBoth = "both" -) - -var allCompressionModes = []string{modeOn, modeOff, modeBoth} -var allTraceModes = []string{modeOn, modeOff, modeBoth} - -const ( - workloadsUnary = "unary" - workloadsStreaming = "streaming" - workloadsAll = "all" -) - -var allWorkloads = []string{workloadsUnary, workloadsStreaming, workloadsAll} - -var ( - runMode = []bool{true, true} // {runUnary, runStream} - // When set the latency to 0 (no delay), the result is slower than the real result with no delay - // because latency simulation section has extra operations - ltc = []time.Duration{0, 40 * time.Millisecond} // if non-positive, no delay. - kbps = []int{0, 10240} // if non-positive, infinite - mtu = []int{0} // if non-positive, infinite - maxConcurrentCalls = []int{1, 8, 64, 512} - reqSizeBytes = []int{1, 1024, 1024 * 1024} - respSizeBytes = []int{1, 1024, 1024 * 1024} - enableTrace []bool - benchtime time.Duration - memProfile, cpuProfile string - memProfileRate int - enableCompressor []bool - enableChannelz []bool - networkMode string - benchmarkResultFile string - networks = map[string]latency.Network{ - "Local": latency.Local, - "LAN": latency.LAN, - "WAN": latency.WAN, - "Longhaul": latency.Longhaul, - } -) - -func unaryBenchmark(startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - caller, close := makeFuncUnary(benchFeatures) - defer close() - runBenchmark(caller, startTimer, stopTimer, benchFeatures, benchtime, s) -} - -func streamBenchmark(startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - caller, close := makeFuncStream(benchFeatures) - defer close() - runBenchmark(caller, startTimer, stopTimer, benchFeatures, benchtime, s) -} - -func makeFuncUnary(benchFeatures stats.Features) (func(int), func()) { - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - opts := []grpc.DialOption{} - sopts := []grpc.ServerOption{} - if benchFeatures.EnableCompressor { - sopts = append(sopts, - grpc.RPCCompressor(nopCompressor{}), - grpc.RPCDecompressor(nopDecompressor{}), - ) - opts = append(opts, - grpc.WithCompressor(nopCompressor{}), - grpc.WithDecompressor(nopDecompressor{}), - ) - } - sopts = append(sopts, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - opts = append(opts, grpc.WithInsecure()) - - var lis net.Listener - if *useBufconn { - bcLis := bufconn.Listen(256 * 1024) - lis = bcLis - opts = append(opts, grpc.WithDialer(func(string, time.Duration) (net.Conn, error) { - return nw.TimeoutDialer( - func(string, string, time.Duration) (net.Conn, error) { - return bcLis.Dial() - })("", "", 0) - })) - } else { - var err error - lis, err = net.Listen("tcp", "localhost:0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - opts = append(opts, grpc.WithDialer(func(_ string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", lis.Addr().String(), timeout) - })) - } - lis = nw.Listener(lis) - stopper := bm.StartServer(bm.ServerInfo{Type: "protobuf", Listener: lis}, sopts...) - conn := bm.NewClientConn("" /* target not used */, opts...) - tc := testpb.NewBenchmarkServiceClient(conn) - return func(int) { - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - }, func() { - conn.Close() - stopper() - } -} - -func makeFuncStream(benchFeatures stats.Features) (func(int), func()) { - // TODO: Refactor to remove duplication with makeFuncUnary. - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - opts := []grpc.DialOption{} - sopts := []grpc.ServerOption{} - if benchFeatures.EnableCompressor { - sopts = append(sopts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - sopts = append(sopts, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - opts = append(opts, grpc.WithInsecure()) - - var lis net.Listener - if *useBufconn { - bcLis := bufconn.Listen(256 * 1024) - lis = bcLis - opts = append(opts, grpc.WithDialer(func(string, time.Duration) (net.Conn, error) { - return nw.TimeoutDialer( - func(string, string, time.Duration) (net.Conn, error) { - return bcLis.Dial() - })("", "", 0) - })) - } else { - var err error - lis, err = net.Listen("tcp", "localhost:0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - opts = append(opts, grpc.WithDialer(func(_ string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", lis.Addr().String(), timeout) - })) - } - lis = nw.Listener(lis) - stopper := bm.StartServer(bm.ServerInfo{Type: "protobuf", Listener: lis}, sopts...) - conn := bm.NewClientConn("" /* target not used */, opts...) - tc := testpb.NewBenchmarkServiceClient(conn) - streams := make([]testpb.BenchmarkService_StreamingCallClient, benchFeatures.MaxConcurrentCalls) - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - streams[i] = stream - } - return func(pos int) { - streamCaller(streams[pos], benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - }, func() { - conn.Close() - stopper() - } -} - -func unaryCaller(client testpb.BenchmarkServiceClient, reqSize, respSize int) { - if err := bm.DoUnaryCall(client, reqSize, respSize); err != nil { - grpclog.Fatalf("DoUnaryCall failed: %v", err) - } -} - -func streamCaller(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) { - if err := bm.DoStreamingRoundTrip(stream, reqSize, respSize); err != nil { - grpclog.Fatalf("DoStreamingRoundTrip failed: %v", err) - } -} - -func runBenchmark(caller func(int), startTimer func(), stopTimer func(int32), benchFeatures stats.Features, benchtime time.Duration, s *stats.Stats) { - // Warm up connection. - for i := 0; i < 10; i++ { - caller(0) - } - // Run benchmark. - startTimer() - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - bmEnd := time.Now().Add(benchtime) - var count int32 - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - go func(pos int) { - for { - t := time.Now() - if t.After(bmEnd) { - break - } - start := time.Now() - caller(pos) - elapse := time.Since(start) - atomic.AddInt32(&count, 1) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }(i) - } - wg.Wait() - stopTimer(count) -} - -var useBufconn = flag.Bool("bufconn", false, "Use in-memory connection instead of system network I/O") - -// Initiate main function to get settings of features. -func init() { - var ( - workloads, traceMode, compressorMode, readLatency, channelzOn string - readKbps, readMtu, readMaxConcurrentCalls intSliceType - readReqSizeBytes, readRespSizeBytes intSliceType - ) - flag.StringVar(&workloads, "workloads", workloadsAll, - fmt.Sprintf("Workloads to execute - One of: %v", strings.Join(allWorkloads, ", "))) - flag.StringVar(&traceMode, "trace", modeOff, - fmt.Sprintf("Trace mode - One of: %v", strings.Join(allTraceModes, ", "))) - flag.StringVar(&readLatency, "latency", "", "Simulated one-way network latency - may be a comma-separated list") - flag.StringVar(&channelzOn, "channelz", modeOff, "whether channelz should be turned on") - flag.DurationVar(&benchtime, "benchtime", time.Second, "Configures the amount of time to run each benchmark") - flag.Var(&readKbps, "kbps", "Simulated network throughput (in kbps) - may be a comma-separated list") - flag.Var(&readMtu, "mtu", "Simulated network MTU (Maximum Transmission Unit) - may be a comma-separated list") - flag.Var(&readMaxConcurrentCalls, "maxConcurrentCalls", "Number of concurrent RPCs during benchmarks") - flag.Var(&readReqSizeBytes, "reqSizeBytes", "Request size in bytes - may be a comma-separated list") - flag.Var(&readRespSizeBytes, "respSizeBytes", "Response size in bytes - may be a comma-separated list") - flag.StringVar(&memProfile, "memProfile", "", "Enables memory profiling output to the filename provided.") - flag.IntVar(&memProfileRate, "memProfileRate", 512*1024, "Configures the memory profiling rate. \n"+ - "memProfile should be set before setting profile rate. To include every allocated block in the profile, "+ - "set MemProfileRate to 1. To turn off profiling entirely, set MemProfileRate to 0. 512 * 1024 by default.") - flag.StringVar(&cpuProfile, "cpuProfile", "", "Enables CPU profiling output to the filename provided") - flag.StringVar(&compressorMode, "compression", modeOff, - fmt.Sprintf("Compression mode - One of: %v", strings.Join(allCompressionModes, ", "))) - flag.StringVar(&benchmarkResultFile, "resultFile", "", "Save the benchmark result into a binary file") - flag.StringVar(&networkMode, "networkMode", "", "Network mode includes LAN, WAN, Local and Longhaul") - flag.Parse() - if flag.NArg() != 0 { - log.Fatal("Error: unparsed arguments: ", flag.Args()) - } - switch workloads { - case workloadsUnary: - runMode[0] = true - runMode[1] = false - case workloadsStreaming: - runMode[0] = false - runMode[1] = true - case workloadsAll: - runMode[0] = true - runMode[1] = true - default: - log.Fatalf("Unknown workloads setting: %v (want one of: %v)", - workloads, strings.Join(allWorkloads, ", ")) - } - enableCompressor = setMode(compressorMode) - enableTrace = setMode(traceMode) - enableChannelz = setMode(channelzOn) - // Time input formats as (time + unit). - readTimeFromInput(<c, readLatency) - readIntFromIntSlice(&kbps, readKbps) - readIntFromIntSlice(&mtu, readMtu) - readIntFromIntSlice(&maxConcurrentCalls, readMaxConcurrentCalls) - readIntFromIntSlice(&reqSizeBytes, readReqSizeBytes) - readIntFromIntSlice(&respSizeBytes, readRespSizeBytes) - // Re-write latency, kpbs and mtu if network mode is set. - if network, ok := networks[networkMode]; ok { - ltc = []time.Duration{network.Latency} - kbps = []int{network.Kbps} - mtu = []int{network.MTU} - } -} - -func setMode(name string) []bool { - switch name { - case modeOn: - return []bool{true} - case modeOff: - return []bool{false} - case modeBoth: - return []bool{false, true} - default: - log.Fatalf("Unknown %s setting: %v (want one of: %v)", - name, name, strings.Join(allCompressionModes, ", ")) - return []bool{} - } -} - -type intSliceType []int - -func (intSlice *intSliceType) String() string { - return fmt.Sprintf("%v", *intSlice) -} - -func (intSlice *intSliceType) Set(value string) error { - if len(*intSlice) > 0 { - return errors.New("interval flag already set") - } - for _, num := range strings.Split(value, ",") { - next, err := strconv.Atoi(num) - if err != nil { - return err - } - *intSlice = append(*intSlice, next) - } - return nil -} - -func readIntFromIntSlice(values *[]int, replace intSliceType) { - // If not set replace in the flag, just return to run the default settings. - if len(replace) == 0 { - return - } - *values = replace -} - -func readTimeFromInput(values *[]time.Duration, replace string) { - if strings.Compare(replace, "") != 0 { - *values = []time.Duration{} - for _, ltc := range strings.Split(replace, ",") { - duration, err := time.ParseDuration(ltc) - if err != nil { - log.Fatal(err.Error()) - } - *values = append(*values, duration) - } - } -} - -func main() { - before() - featuresPos := make([]int, 9) - // 0:enableTracing 1:ltc 2:kbps 3:mtu 4:maxC 5:reqSize 6:respSize - featuresNum := []int{len(enableTrace), len(ltc), len(kbps), len(mtu), - len(maxConcurrentCalls), len(reqSizeBytes), len(respSizeBytes), len(enableCompressor), len(enableChannelz)} - initalPos := make([]int, len(featuresPos)) - s := stats.NewStats(10) - s.SortLatency() - var memStats runtime.MemStats - var results testing.BenchmarkResult - var startAllocs, startBytes uint64 - var startTime time.Time - start := true - var startTimer = func() { - runtime.ReadMemStats(&memStats) - startAllocs = memStats.Mallocs - startBytes = memStats.TotalAlloc - startTime = time.Now() - } - var stopTimer = func(count int32) { - runtime.ReadMemStats(&memStats) - results = testing.BenchmarkResult{N: int(count), T: time.Since(startTime), - Bytes: 0, MemAllocs: memStats.Mallocs - startAllocs, MemBytes: memStats.TotalAlloc - startBytes} - } - sharedPos := make([]bool, len(featuresPos)) - for i := 0; i < len(featuresPos); i++ { - if featuresNum[i] <= 1 { - sharedPos[i] = true - } - } - - // Run benchmarks - resultSlice := []stats.BenchResults{} - for !reflect.DeepEqual(featuresPos, initalPos) || start { - start = false - benchFeature := stats.Features{ - NetworkMode: networkMode, - EnableTrace: enableTrace[featuresPos[0]], - Latency: ltc[featuresPos[1]], - Kbps: kbps[featuresPos[2]], - Mtu: mtu[featuresPos[3]], - MaxConcurrentCalls: maxConcurrentCalls[featuresPos[4]], - ReqSizeBytes: reqSizeBytes[featuresPos[5]], - RespSizeBytes: respSizeBytes[featuresPos[6]], - EnableCompressor: enableCompressor[featuresPos[7]], - EnableChannelz: enableChannelz[featuresPos[8]], - } - - grpc.EnableTracing = enableTrace[featuresPos[0]] - if enableChannelz[featuresPos[8]] { - grpc.RegisterChannelz() - } - if runMode[0] { - unaryBenchmark(startTimer, stopTimer, benchFeature, benchtime, s) - s.SetBenchmarkResult("Unary", benchFeature, results.N, - results.AllocedBytesPerOp(), results.AllocsPerOp(), sharedPos) - fmt.Println(s.BenchString()) - fmt.Println(s.String()) - resultSlice = append(resultSlice, s.GetBenchmarkResults()) - s.Clear() - } - if runMode[1] { - streamBenchmark(startTimer, stopTimer, benchFeature, benchtime, s) - s.SetBenchmarkResult("Stream", benchFeature, results.N, - results.AllocedBytesPerOp(), results.AllocsPerOp(), sharedPos) - fmt.Println(s.BenchString()) - fmt.Println(s.String()) - resultSlice = append(resultSlice, s.GetBenchmarkResults()) - s.Clear() - } - bm.AddOne(featuresPos, featuresNum) - } - after(resultSlice) -} - -func before() { - if memProfile != "" { - runtime.MemProfileRate = memProfileRate - } - if cpuProfile != "" { - f, err := os.Create(cpuProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s\n", err) - return - } - if err := pprof.StartCPUProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't start cpu profile: %s\n", err) - f.Close() - return - } - } -} - -func after(data []stats.BenchResults) { - if cpuProfile != "" { - pprof.StopCPUProfile() // flushes profile to disk - } - if memProfile != "" { - f, err := os.Create(memProfile) - if err != nil { - fmt.Fprintf(os.Stderr, "testing: %s\n", err) - os.Exit(2) - } - runtime.GC() // materialize all statistics - if err = pprof.WriteHeapProfile(f); err != nil { - fmt.Fprintf(os.Stderr, "testing: can't write heap profile %s: %s\n", memProfile, err) - os.Exit(2) - } - f.Close() - } - if benchmarkResultFile != "" { - f, err := os.Create(benchmarkResultFile) - if err != nil { - log.Fatalf("testing: can't write benchmark result %s: %s\n", benchmarkResultFile, err) - } - dataEncoder := gob.NewEncoder(f) - dataEncoder.Encode(data) - f.Close() - } -} - -// nopCompressor is a compressor that just copies data. -type nopCompressor struct{} - -func (nopCompressor) Do(w io.Writer, p []byte) error { - n, err := w.Write(p) - if err != nil { - return err - } - if n != len(p) { - return fmt.Errorf("nopCompressor.Write: wrote %v bytes; want %v", n, len(p)) - } - return nil -} - -func (nopCompressor) Type() string { return "nop" } - -// nopDecompressor is a decompressor that just copies data. -type nopDecompressor struct{} - -func (nopDecompressor) Do(r io.Reader) ([]byte, error) { return ioutil.ReadAll(r) } -func (nopDecompressor) Type() string { return "nop" } diff --git a/examples/google.golang.org/grpc/benchmark/benchmark.go b/examples/google.golang.org/grpc/benchmark/benchmark.go deleted file mode 100755 index ec9b50b..0000000 --- a/examples/google.golang.org/grpc/benchmark/benchmark.go +++ /dev/null @@ -1,369 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc -I grpc_testing --go_out=plugins=grpc:grpc_testing grpc_testing/control.proto grpc_testing/messages.proto grpc_testing/payloads.proto grpc_testing/services.proto grpc_testing/stats.proto - -/* -Package benchmark implements the building blocks to setup end-to-end gRPC benchmarks. -*/ -package benchmark - -import ( - "fmt" - "io" - "net" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/latency" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" -) - -// AddOne add 1 to the features slice -func AddOne(features []int, featuresMaxPosition []int) { - for i := len(features) - 1; i >= 0; i-- { - features[i] = (features[i] + 1) - if features[i]/featuresMaxPosition[i] == 0 { - break - } - features[i] = features[i] % featuresMaxPosition[i] - } -} - -// Allows reuse of the same testpb.Payload object. -func setPayload(p *testpb.Payload, t testpb.PayloadType, size int) { - if size < 0 { - grpclog.Fatalf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported") - default: - grpclog.Fatalf("Unsupported payload type: %d", t) - } - p.Type = t - p.Body = body -} - -func newPayload(t testpb.PayloadType, size int) *testpb.Payload { - p := new(testpb.Payload) - setPayload(p, t, size) - return p -} - -type testServer struct { -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return &testpb.SimpleResponse{ - Payload: newPayload(in.ResponseType, int(in.ResponseSize)), - }, nil -} - -func (s *testServer) StreamingCall(stream testpb.BenchmarkService_StreamingCallServer) error { - response := &testpb.SimpleResponse{ - Payload: new(testpb.Payload), - } - in := new(testpb.SimpleRequest) - for { - // use ServerStream directly to reuse the same testpb.SimpleRequest object - err := stream.(grpc.ServerStream).RecvMsg(in) - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - setPayload(response.Payload, in.ResponseType, int(in.ResponseSize)) - if err := stream.Send(response); err != nil { - return err - } - } -} - -// byteBufServer is a gRPC server that sends and receives byte buffer. -// The purpose is to benchmark the gRPC performance without protobuf serialization/deserialization overhead. -type byteBufServer struct { - respSize int32 -} - -// UnaryCall is an empty function and is not used for benchmark. -// If bytebuf UnaryCall benchmark is needed later, the function body needs to be updated. -func (s *byteBufServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return &testpb.SimpleResponse{}, nil -} - -func (s *byteBufServer) StreamingCall(stream testpb.BenchmarkService_StreamingCallServer) error { - for { - var in []byte - err := stream.(grpc.ServerStream).RecvMsg(&in) - if err == io.EOF { - return nil - } - if err != nil { - return err - } - out := make([]byte, s.respSize) - if err := stream.(grpc.ServerStream).SendMsg(&out); err != nil { - return err - } - } -} - -// ServerInfo contains the information to create a gRPC benchmark server. -type ServerInfo struct { - // Type is the type of the server. - // It should be "protobuf" or "bytebuf". - Type string - - // Metadata is an optional configuration. - // For "protobuf", it's ignored. - // For "bytebuf", it should be an int representing response size. - Metadata interface{} - - // Listener is the network listener for the server to use - Listener net.Listener -} - -// StartServer starts a gRPC server serving a benchmark service according to info. -// It returns a function to stop the server. -func StartServer(info ServerInfo, opts ...grpc.ServerOption) func() { - opts = append(opts, grpc.WriteBufferSize(128*1024)) - opts = append(opts, grpc.ReadBufferSize(128*1024)) - s := grpc.NewServer(opts...) - switch info.Type { - case "protobuf": - testpb.RegisterBenchmarkServiceServer(s, &testServer{}) - case "bytebuf": - respSize, ok := info.Metadata.(int32) - if !ok { - grpclog.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type) - } - testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize}) - default: - grpclog.Fatalf("failed to StartServer, unknown Type: %v", info.Type) - } - go s.Serve(info.Listener) - return func() { - s.Stop() - } -} - -// DoUnaryCall performs an unary RPC with given stub and request and response sizes. -func DoUnaryCall(tc testpb.BenchmarkServiceClient, reqSize, respSize int) error { - pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize) - req := &testpb.SimpleRequest{ - ResponseType: pl.Type, - ResponseSize: int32(respSize), - Payload: pl, - } - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - return fmt.Errorf("/BenchmarkService/UnaryCall(_, _) = _, %v, want _, ", err) - } - return nil -} - -// DoStreamingRoundTrip performs a round trip for a single streaming rpc. -func DoStreamingRoundTrip(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) error { - pl := newPayload(testpb.PayloadType_COMPRESSABLE, reqSize) - req := &testpb.SimpleRequest{ - ResponseType: pl.Type, - ResponseSize: int32(respSize), - Payload: pl, - } - if err := stream.Send(req); err != nil { - return fmt.Errorf("/BenchmarkService/StreamingCall.Send(_) = %v, want ", err) - } - if _, err := stream.Recv(); err != nil { - // EOF is a valid error here. - if err == io.EOF { - return nil - } - return fmt.Errorf("/BenchmarkService/StreamingCall.Recv(_) = %v, want ", err) - } - return nil -} - -// DoByteBufStreamingRoundTrip performs a round trip for a single streaming rpc, using a custom codec for byte buffer. -func DoByteBufStreamingRoundTrip(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) error { - out := make([]byte, reqSize) - if err := stream.(grpc.ClientStream).SendMsg(&out); err != nil { - return fmt.Errorf("/BenchmarkService/StreamingCall.(ClientStream).SendMsg(_) = %v, want ", err) - } - var in []byte - if err := stream.(grpc.ClientStream).RecvMsg(&in); err != nil { - // EOF is a valid error here. - if err == io.EOF { - return nil - } - return fmt.Errorf("/BenchmarkService/StreamingCall.(ClientStream).RecvMsg(_) = %v, want ", err) - } - return nil -} - -// NewClientConn creates a gRPC client connection to addr. -func NewClientConn(addr string, opts ...grpc.DialOption) *grpc.ClientConn { - return NewClientConnWithContext(context.Background(), addr, opts...) -} - -// NewClientConnWithContext creates a gRPC client connection to addr using ctx. -func NewClientConnWithContext(ctx context.Context, addr string, opts ...grpc.DialOption) *grpc.ClientConn { - opts = append(opts, grpc.WithWriteBufferSize(128*1024)) - opts = append(opts, grpc.WithReadBufferSize(128*1024)) - conn, err := grpc.DialContext(ctx, addr, opts...) - if err != nil { - grpclog.Fatalf("NewClientConn(%q) failed to create a ClientConn %v", addr, err) - } - return conn -} - -func runUnary(b *testing.B, benchFeatures stats.Features) { - s := stats.AddStats(b, 38) - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - target := lis.Addr().String() - lis = nw.Listener(lis) - stopper := StartServer(ServerInfo{Type: "protobuf", Listener: lis}, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - defer stopper() - conn := NewClientConn( - target, grpc.WithInsecure(), - grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - }), - ) - tc := testpb.NewBenchmarkServiceClient(conn) - - // Warm up connection. - for i := 0; i < 10; i++ { - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - } - ch := make(chan int, benchFeatures.MaxConcurrentCalls*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - - // Distribute the b.N calls over maxConcurrentCalls workers. - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - go func() { - for range ch { - start := time.Now() - unaryCaller(tc, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - ch <- i - } - close(ch) - wg.Wait() - b.StopTimer() - conn.Close() -} - -func runStream(b *testing.B, benchFeatures stats.Features) { - s := stats.AddStats(b, 38) - nw := &latency.Network{Kbps: benchFeatures.Kbps, Latency: benchFeatures.Latency, MTU: benchFeatures.Mtu} - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - target := lis.Addr().String() - lis = nw.Listener(lis) - stopper := StartServer(ServerInfo{Type: "protobuf", Listener: lis}, grpc.MaxConcurrentStreams(uint32(benchFeatures.MaxConcurrentCalls+1))) - defer stopper() - conn := NewClientConn( - target, grpc.WithInsecure(), - grpc.WithDialer(func(address string, timeout time.Duration) (net.Conn, error) { - return nw.TimeoutDialer(net.DialTimeout)("tcp", address, timeout) - }), - ) - tc := testpb.NewBenchmarkServiceClient(conn) - - // Warm up connection. - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - b.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - for i := 0; i < 10; i++ { - streamCaller(stream, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - } - - ch := make(chan struct{}, benchFeatures.MaxConcurrentCalls*4) - var ( - mu sync.Mutex - wg sync.WaitGroup - ) - wg.Add(benchFeatures.MaxConcurrentCalls) - - // Distribute the b.N calls over maxConcurrentCalls workers. - for i := 0; i < benchFeatures.MaxConcurrentCalls; i++ { - stream, err := tc.StreamingCall(context.Background()) - if err != nil { - b.Fatalf("%v.StreamingCall(_) = _, %v", tc, err) - } - go func() { - for range ch { - start := time.Now() - streamCaller(stream, benchFeatures.ReqSizeBytes, benchFeatures.RespSizeBytes) - elapse := time.Since(start) - mu.Lock() - s.Add(elapse) - mu.Unlock() - } - wg.Done() - }() - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - ch <- struct{}{} - } - close(ch) - wg.Wait() - b.StopTimer() - conn.Close() -} -func unaryCaller(client testpb.BenchmarkServiceClient, reqSize, respSize int) { - if err := DoUnaryCall(client, reqSize, respSize); err != nil { - grpclog.Fatalf("DoUnaryCall failed: %v", err) - } -} - -func streamCaller(stream testpb.BenchmarkService_StreamingCallClient, reqSize, respSize int) { - if err := DoStreamingRoundTrip(stream, reqSize, respSize); err != nil { - grpclog.Fatalf("DoStreamingRoundTrip failed: %v", err) - } -} diff --git a/examples/google.golang.org/grpc/benchmark/benchmark16_test.go b/examples/google.golang.org/grpc/benchmark/benchmark16_test.go deleted file mode 100755 index a036b63..0000000 --- a/examples/google.golang.org/grpc/benchmark/benchmark16_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package benchmark - -import ( - "os" - "testing" - - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark/stats" -) - -func BenchmarkClientStreamc1(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 1, 1, 1, false, false}) -} - -func BenchmarkClientStreamc8(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 8, 1, 1, false, false}) -} - -func BenchmarkClientStreamc64(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 64, 1, 1, false, false}) -} - -func BenchmarkClientStreamc512(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 512, 1, 1, false, false}) -} -func BenchmarkClientUnaryc1(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 1, 1, 1, false, false}) -} - -func BenchmarkClientUnaryc8(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 8, 1, 1, false, false}) -} - -func BenchmarkClientUnaryc64(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 64, 1, 1, false, false}) -} - -func BenchmarkClientUnaryc512(b *testing.B) { - grpc.EnableTracing = true - runStream(b, stats.Features{"", true, 0, 0, 0, 512, 1, 1, false, false}) -} - -func BenchmarkClientStreamNoTracec1(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 1, 1, 1, false, false}) -} - -func BenchmarkClientStreamNoTracec8(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 8, 1, 1, false, false}) -} - -func BenchmarkClientStreamNoTracec64(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 64, 1, 1, false, false}) -} - -func BenchmarkClientStreamNoTracec512(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 512, 1, 1, false, false}) -} -func BenchmarkClientUnaryNoTracec1(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 1, 1, 1, false, false}) -} - -func BenchmarkClientUnaryNoTracec8(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 8, 1, 1, false, false}) -} - -func BenchmarkClientUnaryNoTracec64(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 64, 1, 1, false, false}) -} - -func BenchmarkClientUnaryNoTracec512(b *testing.B) { - grpc.EnableTracing = false - runStream(b, stats.Features{"", false, 0, 0, 0, 512, 1, 1, false, false}) - runStream(b, stats.Features{"", false, 0, 0, 0, 512, 1, 1, false, false}) -} - -func TestMain(m *testing.M) { - os.Exit(stats.RunTestMain(m)) -} diff --git a/examples/google.golang.org/grpc/benchmark/benchmark17_test.go b/examples/google.golang.org/grpc/benchmark/benchmark17_test.go deleted file mode 100755 index 8dc7d3c..0000000 --- a/examples/google.golang.org/grpc/benchmark/benchmark17_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package benchmark - -import ( - "fmt" - "os" - "reflect" - "testing" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark/stats" -) - -func BenchmarkClient(b *testing.B) { - enableTrace := []bool{true, false} // run both enable and disable by default - // When set the latency to 0 (no delay), the result is slower than the real result with no delay - // because latency simulation section has extra operations - latency := []time.Duration{0, 40 * time.Millisecond} // if non-positive, no delay. - kbps := []int{0, 10240} // if non-positive, infinite - mtu := []int{0} // if non-positive, infinite - maxConcurrentCalls := []int{1, 8, 64, 512} - reqSizeBytes := []int{1, 1024 * 1024} - respSizeBytes := []int{1, 1024 * 1024} - featuresCurPos := make([]int, 7) - - // 0:enableTracing 1:md 2:ltc 3:kbps 4:mtu 5:maxC 6:connCount 7:reqSize 8:respSize - featuresMaxPosition := []int{len(enableTrace), len(latency), len(kbps), len(mtu), len(maxConcurrentCalls), len(reqSizeBytes), len(respSizeBytes)} - initalPos := make([]int, len(featuresCurPos)) - - // run benchmarks - start := true - for !reflect.DeepEqual(featuresCurPos, initalPos) || start { - start = false - tracing := "Trace" - if !enableTrace[featuresCurPos[0]] { - tracing = "noTrace" - } - - benchFeature := stats.Features{ - EnableTrace: enableTrace[featuresCurPos[0]], - Latency: latency[featuresCurPos[1]], - Kbps: kbps[featuresCurPos[2]], - Mtu: mtu[featuresCurPos[3]], - MaxConcurrentCalls: maxConcurrentCalls[featuresCurPos[4]], - ReqSizeBytes: reqSizeBytes[featuresCurPos[5]], - RespSizeBytes: respSizeBytes[featuresCurPos[6]], - } - - grpc.EnableTracing = enableTrace[featuresCurPos[0]] - b.Run(fmt.Sprintf("Unary-%s-%s", - tracing, benchFeature.String()), func(b *testing.B) { - runUnary(b, benchFeature) - }) - - b.Run(fmt.Sprintf("Stream-%s-%s", - tracing, benchFeature.String()), func(b *testing.B) { - runStream(b, benchFeature) - }) - AddOne(featuresCurPos, featuresMaxPosition) - } -} - -func TestMain(m *testing.M) { - os.Exit(stats.RunTestMain(m)) -} diff --git a/examples/google.golang.org/grpc/benchmark/benchresult/main.go b/examples/google.golang.org/grpc/benchmark/benchresult/main.go deleted file mode 100755 index 40226cf..0000000 --- a/examples/google.golang.org/grpc/benchmark/benchresult/main.go +++ /dev/null @@ -1,133 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* -To format the benchmark result: - go run benchmark/benchresult/main.go resultfile - -To see the performance change based on a old result: - go run benchmark/benchresult/main.go resultfile_old resultfile -It will print the comparison result of intersection benchmarks between two files. - -*/ -package main - -import ( - "encoding/gob" - "fmt" - "log" - "os" - "strconv" - "strings" - "time" - - "google.golang.org/grpc/benchmark/stats" -) - -func createMap(fileName string, m map[string]stats.BenchResults) { - f, err := os.Open(fileName) - if err != nil { - log.Fatalf("Read file %s error: %s\n", fileName, err) - } - defer f.Close() - var data []stats.BenchResults - decoder := gob.NewDecoder(f) - if err = decoder.Decode(&data); err != nil { - log.Fatalf("Decode file %s error: %s\n", fileName, err) - } - for _, d := range data { - m[d.RunMode+"-"+d.Features.String()] = d - } -} - -func intChange(title string, val1, val2 int64) string { - return fmt.Sprintf("%10s %12s %12s %8.2f%%\n", title, strconv.FormatInt(val1, 10), - strconv.FormatInt(val2, 10), float64(val2-val1)*100/float64(val1)) -} - -func timeChange(title int, val1, val2 time.Duration) string { - return fmt.Sprintf("%10s %12s %12s %8.2f%%\n", strconv.Itoa(title)+" latency", val1.String(), - val2.String(), float64(val2-val1)*100/float64(val1)) -} - -func compareTwoMap(m1, m2 map[string]stats.BenchResults) { - for k2, v2 := range m2 { - if v1, ok := m1[k2]; ok { - changes := k2 + "\n" - changes += fmt.Sprintf("%10s %12s %12s %8s\n", "Title", "Before", "After", "Percentage") - changes += intChange("Bytes/op", v1.AllocedBytesPerOp, v2.AllocedBytesPerOp) - changes += intChange("Allocs/op", v1.AllocsPerOp, v2.AllocsPerOp) - changes += timeChange(v1.Latency[1].Percent, v1.Latency[1].Value, v2.Latency[1].Value) - changes += timeChange(v1.Latency[2].Percent, v1.Latency[2].Value, v2.Latency[2].Value) - fmt.Printf("%s\n", changes) - } - } -} - -func compareBenchmark(file1, file2 string) { - var BenchValueFile1 map[string]stats.BenchResults - var BenchValueFile2 map[string]stats.BenchResults - BenchValueFile1 = make(map[string]stats.BenchResults) - BenchValueFile2 = make(map[string]stats.BenchResults) - - createMap(file1, BenchValueFile1) - createMap(file2, BenchValueFile2) - - compareTwoMap(BenchValueFile1, BenchValueFile2) -} - -func printline(benchName, ltc50, ltc90, allocByte, allocsOp interface{}) { - fmt.Printf("%-80v%12v%12v%12v%12v\n", benchName, ltc50, ltc90, allocByte, allocsOp) -} - -func formatBenchmark(fileName string) { - f, err := os.Open(fileName) - if err != nil { - log.Fatalf("Read file %s error: %s\n", fileName, err) - } - defer f.Close() - var data []stats.BenchResults - decoder := gob.NewDecoder(f) - if err = decoder.Decode(&data); err != nil { - log.Fatalf("Decode file %s error: %s\n", fileName, err) - } - if len(data) == 0 { - log.Fatalf("No data in file %s\n", fileName) - } - printPos := data[0].SharedPosion - fmt.Println("\nShared features:\n" + strings.Repeat("-", 20)) - fmt.Print(stats.PartialPrintString(printPos, data[0].Features, true)) - fmt.Println(strings.Repeat("-", 35)) - for i := 0; i < len(data[0].SharedPosion); i++ { - printPos[i] = !printPos[i] - } - printline("Name", "latency-50", "latency-90", "Alloc (B)", "Alloc (#)") - for _, d := range data { - name := d.RunMode + stats.PartialPrintString(printPos, d.Features, false) - printline(name, d.Latency[1].Value.String(), d.Latency[2].Value.String(), - d.AllocedBytesPerOp, d.AllocsPerOp) - } -} - -func main() { - if len(os.Args) == 2 { - formatBenchmark(os.Args[1]) - } else { - compareBenchmark(os.Args[1], os.Args[2]) - } -} diff --git a/examples/google.golang.org/grpc/benchmark/client/main.go b/examples/google.golang.org/grpc/benchmark/client/main.go deleted file mode 100755 index 13a5fb3..0000000 --- a/examples/google.golang.org/grpc/benchmark/client/main.go +++ /dev/null @@ -1,195 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "fmt" - "os" - "runtime" - "runtime/pprof" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/sys/unix" - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/grpclog" -) - -var ( - port = flag.String("port", "50051", "Localhost port to connect to.") - numRPC = flag.Int("r", 1, "The number of concurrent RPCs on each connection.") - numConn = flag.Int("c", 1, "The number of parallel connections.") - warmupDur = flag.Int("w", 10, "Warm-up duration in seconds") - duration = flag.Int("d", 60, "Benchmark duration in seconds") - rqSize = flag.Int("req", 1, "Request message size in bytes.") - rspSize = flag.Int("resp", 1, "Response message size in bytes.") - rpcType = flag.String("rpc_type", "unary", - `Configure different client rpc type. Valid options are: - unary; - streaming.`) - testName = flag.String("test_name", "", "Name of the test used for creating profiles.") - wg sync.WaitGroup - hopts = stats.HistogramOptions{ - NumBuckets: 2495, - GrowthFactor: .01, - } - mu sync.Mutex - hists []*stats.Histogram -) - -func main() { - flag.Parse() - if *testName == "" { - grpclog.Fatalf("test_name not set") - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(*rspSize), - Payload: &testpb.Payload{ - Type: testpb.PayloadType_COMPRESSABLE, - Body: make([]byte, *rqSize), - }, - } - connectCtx, connectCancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) - defer connectCancel() - ccs := buildConnections(connectCtx) - warmDeadline := time.Now().Add(time.Duration(*warmupDur) * time.Second) - endDeadline := warmDeadline.Add(time.Duration(*duration) * time.Second) - cf, err := os.Create("/tmp/" + *testName + ".cpu") - if err != nil { - grpclog.Fatalf("Error creating file: %v", err) - } - defer cf.Close() - pprof.StartCPUProfile(cf) - cpuBeg := getCPUTime() - for _, cc := range ccs { - runWithConn(cc, req, warmDeadline, endDeadline) - } - wg.Wait() - cpu := time.Duration(getCPUTime() - cpuBeg) - pprof.StopCPUProfile() - mf, err := os.Create("/tmp/" + *testName + ".mem") - if err != nil { - grpclog.Fatalf("Error creating file: %v", err) - } - defer mf.Close() - runtime.GC() // materialize all statistics - if err := pprof.WriteHeapProfile(mf); err != nil { - grpclog.Fatalf("Error writing memory profile: %v", err) - } - hist := stats.NewHistogram(hopts) - for _, h := range hists { - hist.Merge(h) - } - parseHist(hist) - fmt.Println("Client CPU utilization:", cpu) - fmt.Println("Client CPU profile:", cf.Name()) - fmt.Println("Client Mem Profile:", mf.Name()) -} - -func buildConnections(ctx context.Context) []*grpc.ClientConn { - ccs := make([]*grpc.ClientConn, *numConn) - for i := range ccs { - ccs[i] = benchmark.NewClientConnWithContext(ctx, "localhost:"+*port, grpc.WithInsecure(), grpc.WithBlock()) - } - return ccs -} - -func runWithConn(cc *grpc.ClientConn, req *testpb.SimpleRequest, warmDeadline, endDeadline time.Time) { - for i := 0; i < *numRPC; i++ { - wg.Add(1) - go func() { - defer wg.Done() - caller := makeCaller(cc, req) - hist := stats.NewHistogram(hopts) - for { - start := time.Now() - if start.After(endDeadline) { - mu.Lock() - hists = append(hists, hist) - mu.Unlock() - return - } - caller() - elapsed := time.Since(start) - if start.After(warmDeadline) { - hist.Add(elapsed.Nanoseconds()) - } - } - }() - } -} - -func makeCaller(cc *grpc.ClientConn, req *testpb.SimpleRequest) func() { - client := testpb.NewBenchmarkServiceClient(cc) - if *rpcType == "unary" { - return func() { - if _, err := client.UnaryCall(context.Background(), req); err != nil { - grpclog.Fatalf("RPC failed: %v", err) - } - } - } - stream, err := client.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("RPC failed: %v", err) - } - return func() { - if err := stream.Send(req); err != nil { - grpclog.Fatalf("Streaming RPC failed to send: %v", err) - } - if _, err := stream.Recv(); err != nil { - grpclog.Fatalf("Streaming RPC failed to read: %v", err) - } - } -} - -func parseHist(hist *stats.Histogram) { - fmt.Println("qps:", float64(hist.Count)/float64(*duration)) - fmt.Printf("Latency: (50/90/99 %%ile): %v/%v/%v\n", - time.Duration(median(.5, hist)), - time.Duration(median(.9, hist)), - time.Duration(median(.99, hist))) -} - -func median(percentile float64, h *stats.Histogram) int64 { - need := int64(float64(h.Count) * percentile) - have := int64(0) - for _, bucket := range h.Buckets { - count := bucket.Count - if have+count >= need { - percent := float64(need-have) / float64(count) - return int64((1.0-percent)*bucket.LowBound + percent*bucket.LowBound*(1.0+hopts.GrowthFactor)) - } - have += bucket.Count - } - panic("should have found a bound") -} - -func getCPUTime() int64 { - var ts unix.Timespec - if err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts); err != nil { - grpclog.Fatal(err) - } - return ts.Nano() -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go b/examples/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go deleted file mode 100755 index 2213442..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/control.pb.go +++ /dev/null @@ -1,1568 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: control.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ClientType int32 - -const ( - ClientType_SYNC_CLIENT ClientType = 0 - ClientType_ASYNC_CLIENT ClientType = 1 -) - -var ClientType_name = map[int32]string{ - 0: "SYNC_CLIENT", - 1: "ASYNC_CLIENT", -} -var ClientType_value = map[string]int32{ - "SYNC_CLIENT": 0, - "ASYNC_CLIENT": 1, -} - -func (x ClientType) String() string { - return proto.EnumName(ClientType_name, int32(x)) -} -func (ClientType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{0} -} - -type ServerType int32 - -const ( - ServerType_SYNC_SERVER ServerType = 0 - ServerType_ASYNC_SERVER ServerType = 1 - ServerType_ASYNC_GENERIC_SERVER ServerType = 2 -) - -var ServerType_name = map[int32]string{ - 0: "SYNC_SERVER", - 1: "ASYNC_SERVER", - 2: "ASYNC_GENERIC_SERVER", -} -var ServerType_value = map[string]int32{ - "SYNC_SERVER": 0, - "ASYNC_SERVER": 1, - "ASYNC_GENERIC_SERVER": 2, -} - -func (x ServerType) String() string { - return proto.EnumName(ServerType_name, int32(x)) -} -func (ServerType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{1} -} - -type RpcType int32 - -const ( - RpcType_UNARY RpcType = 0 - RpcType_STREAMING RpcType = 1 -) - -var RpcType_name = map[int32]string{ - 0: "UNARY", - 1: "STREAMING", -} -var RpcType_value = map[string]int32{ - "UNARY": 0, - "STREAMING": 1, -} - -func (x RpcType) String() string { - return proto.EnumName(RpcType_name, int32(x)) -} -func (RpcType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{2} -} - -// Parameters of poisson process distribution, which is a good representation -// of activity coming in from independent identical stationary sources. -type PoissonParams struct { - // The rate of arrivals (a.k.a. lambda parameter of the exp distribution). - OfferedLoad float64 `protobuf:"fixed64,1,opt,name=offered_load,json=offeredLoad,proto3" json:"offered_load,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PoissonParams) Reset() { *m = PoissonParams{} } -func (m *PoissonParams) String() string { return proto.CompactTextString(m) } -func (*PoissonParams) ProtoMessage() {} -func (*PoissonParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{0} -} -func (m *PoissonParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PoissonParams.Unmarshal(m, b) -} -func (m *PoissonParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PoissonParams.Marshal(b, m, deterministic) -} -func (dst *PoissonParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_PoissonParams.Merge(dst, src) -} -func (m *PoissonParams) XXX_Size() int { - return xxx_messageInfo_PoissonParams.Size(m) -} -func (m *PoissonParams) XXX_DiscardUnknown() { - xxx_messageInfo_PoissonParams.DiscardUnknown(m) -} - -var xxx_messageInfo_PoissonParams proto.InternalMessageInfo - -func (m *PoissonParams) GetOfferedLoad() float64 { - if m != nil { - return m.OfferedLoad - } - return 0 -} - -type UniformParams struct { - InterarrivalLo float64 `protobuf:"fixed64,1,opt,name=interarrival_lo,json=interarrivalLo,proto3" json:"interarrival_lo,omitempty"` - InterarrivalHi float64 `protobuf:"fixed64,2,opt,name=interarrival_hi,json=interarrivalHi,proto3" json:"interarrival_hi,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UniformParams) Reset() { *m = UniformParams{} } -func (m *UniformParams) String() string { return proto.CompactTextString(m) } -func (*UniformParams) ProtoMessage() {} -func (*UniformParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{1} -} -func (m *UniformParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UniformParams.Unmarshal(m, b) -} -func (m *UniformParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UniformParams.Marshal(b, m, deterministic) -} -func (dst *UniformParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_UniformParams.Merge(dst, src) -} -func (m *UniformParams) XXX_Size() int { - return xxx_messageInfo_UniformParams.Size(m) -} -func (m *UniformParams) XXX_DiscardUnknown() { - xxx_messageInfo_UniformParams.DiscardUnknown(m) -} - -var xxx_messageInfo_UniformParams proto.InternalMessageInfo - -func (m *UniformParams) GetInterarrivalLo() float64 { - if m != nil { - return m.InterarrivalLo - } - return 0 -} - -func (m *UniformParams) GetInterarrivalHi() float64 { - if m != nil { - return m.InterarrivalHi - } - return 0 -} - -type DeterministicParams struct { - OfferedLoad float64 `protobuf:"fixed64,1,opt,name=offered_load,json=offeredLoad,proto3" json:"offered_load,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DeterministicParams) Reset() { *m = DeterministicParams{} } -func (m *DeterministicParams) String() string { return proto.CompactTextString(m) } -func (*DeterministicParams) ProtoMessage() {} -func (*DeterministicParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{2} -} -func (m *DeterministicParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DeterministicParams.Unmarshal(m, b) -} -func (m *DeterministicParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DeterministicParams.Marshal(b, m, deterministic) -} -func (dst *DeterministicParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_DeterministicParams.Merge(dst, src) -} -func (m *DeterministicParams) XXX_Size() int { - return xxx_messageInfo_DeterministicParams.Size(m) -} -func (m *DeterministicParams) XXX_DiscardUnknown() { - xxx_messageInfo_DeterministicParams.DiscardUnknown(m) -} - -var xxx_messageInfo_DeterministicParams proto.InternalMessageInfo - -func (m *DeterministicParams) GetOfferedLoad() float64 { - if m != nil { - return m.OfferedLoad - } - return 0 -} - -type ParetoParams struct { - InterarrivalBase float64 `protobuf:"fixed64,1,opt,name=interarrival_base,json=interarrivalBase,proto3" json:"interarrival_base,omitempty"` - Alpha float64 `protobuf:"fixed64,2,opt,name=alpha,proto3" json:"alpha,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ParetoParams) Reset() { *m = ParetoParams{} } -func (m *ParetoParams) String() string { return proto.CompactTextString(m) } -func (*ParetoParams) ProtoMessage() {} -func (*ParetoParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{3} -} -func (m *ParetoParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ParetoParams.Unmarshal(m, b) -} -func (m *ParetoParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ParetoParams.Marshal(b, m, deterministic) -} -func (dst *ParetoParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_ParetoParams.Merge(dst, src) -} -func (m *ParetoParams) XXX_Size() int { - return xxx_messageInfo_ParetoParams.Size(m) -} -func (m *ParetoParams) XXX_DiscardUnknown() { - xxx_messageInfo_ParetoParams.DiscardUnknown(m) -} - -var xxx_messageInfo_ParetoParams proto.InternalMessageInfo - -func (m *ParetoParams) GetInterarrivalBase() float64 { - if m != nil { - return m.InterarrivalBase - } - return 0 -} - -func (m *ParetoParams) GetAlpha() float64 { - if m != nil { - return m.Alpha - } - return 0 -} - -// Once an RPC finishes, immediately start a new one. -// No configuration parameters needed. -type ClosedLoopParams struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClosedLoopParams) Reset() { *m = ClosedLoopParams{} } -func (m *ClosedLoopParams) String() string { return proto.CompactTextString(m) } -func (*ClosedLoopParams) ProtoMessage() {} -func (*ClosedLoopParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{4} -} -func (m *ClosedLoopParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClosedLoopParams.Unmarshal(m, b) -} -func (m *ClosedLoopParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClosedLoopParams.Marshal(b, m, deterministic) -} -func (dst *ClosedLoopParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClosedLoopParams.Merge(dst, src) -} -func (m *ClosedLoopParams) XXX_Size() int { - return xxx_messageInfo_ClosedLoopParams.Size(m) -} -func (m *ClosedLoopParams) XXX_DiscardUnknown() { - xxx_messageInfo_ClosedLoopParams.DiscardUnknown(m) -} - -var xxx_messageInfo_ClosedLoopParams proto.InternalMessageInfo - -type LoadParams struct { - // Types that are valid to be assigned to Load: - // *LoadParams_ClosedLoop - // *LoadParams_Poisson - // *LoadParams_Uniform - // *LoadParams_Determ - // *LoadParams_Pareto - Load isLoadParams_Load `protobuf_oneof:"load"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadParams) Reset() { *m = LoadParams{} } -func (m *LoadParams) String() string { return proto.CompactTextString(m) } -func (*LoadParams) ProtoMessage() {} -func (*LoadParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{5} -} -func (m *LoadParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadParams.Unmarshal(m, b) -} -func (m *LoadParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadParams.Marshal(b, m, deterministic) -} -func (dst *LoadParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadParams.Merge(dst, src) -} -func (m *LoadParams) XXX_Size() int { - return xxx_messageInfo_LoadParams.Size(m) -} -func (m *LoadParams) XXX_DiscardUnknown() { - xxx_messageInfo_LoadParams.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadParams proto.InternalMessageInfo - -type isLoadParams_Load interface { - isLoadParams_Load() -} - -type LoadParams_ClosedLoop struct { - ClosedLoop *ClosedLoopParams `protobuf:"bytes,1,opt,name=closed_loop,json=closedLoop,proto3,oneof"` -} -type LoadParams_Poisson struct { - Poisson *PoissonParams `protobuf:"bytes,2,opt,name=poisson,proto3,oneof"` -} -type LoadParams_Uniform struct { - Uniform *UniformParams `protobuf:"bytes,3,opt,name=uniform,proto3,oneof"` -} -type LoadParams_Determ struct { - Determ *DeterministicParams `protobuf:"bytes,4,opt,name=determ,proto3,oneof"` -} -type LoadParams_Pareto struct { - Pareto *ParetoParams `protobuf:"bytes,5,opt,name=pareto,proto3,oneof"` -} - -func (*LoadParams_ClosedLoop) isLoadParams_Load() {} -func (*LoadParams_Poisson) isLoadParams_Load() {} -func (*LoadParams_Uniform) isLoadParams_Load() {} -func (*LoadParams_Determ) isLoadParams_Load() {} -func (*LoadParams_Pareto) isLoadParams_Load() {} - -func (m *LoadParams) GetLoad() isLoadParams_Load { - if m != nil { - return m.Load - } - return nil -} - -func (m *LoadParams) GetClosedLoop() *ClosedLoopParams { - if x, ok := m.GetLoad().(*LoadParams_ClosedLoop); ok { - return x.ClosedLoop - } - return nil -} - -func (m *LoadParams) GetPoisson() *PoissonParams { - if x, ok := m.GetLoad().(*LoadParams_Poisson); ok { - return x.Poisson - } - return nil -} - -func (m *LoadParams) GetUniform() *UniformParams { - if x, ok := m.GetLoad().(*LoadParams_Uniform); ok { - return x.Uniform - } - return nil -} - -func (m *LoadParams) GetDeterm() *DeterministicParams { - if x, ok := m.GetLoad().(*LoadParams_Determ); ok { - return x.Determ - } - return nil -} - -func (m *LoadParams) GetPareto() *ParetoParams { - if x, ok := m.GetLoad().(*LoadParams_Pareto); ok { - return x.Pareto - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadParams) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadParams_OneofMarshaler, _LoadParams_OneofUnmarshaler, _LoadParams_OneofSizer, []interface{}{ - (*LoadParams_ClosedLoop)(nil), - (*LoadParams_Poisson)(nil), - (*LoadParams_Uniform)(nil), - (*LoadParams_Determ)(nil), - (*LoadParams_Pareto)(nil), - } -} - -func _LoadParams_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadParams) - // load - switch x := m.Load.(type) { - case *LoadParams_ClosedLoop: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClosedLoop); err != nil { - return err - } - case *LoadParams_Poisson: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Poisson); err != nil { - return err - } - case *LoadParams_Uniform: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Uniform); err != nil { - return err - } - case *LoadParams_Determ: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Determ); err != nil { - return err - } - case *LoadParams_Pareto: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Pareto); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadParams.Load has unexpected type %T", x) - } - return nil -} - -func _LoadParams_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadParams) - switch tag { - case 1: // load.closed_loop - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClosedLoopParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_ClosedLoop{msg} - return true, err - case 2: // load.poisson - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(PoissonParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Poisson{msg} - return true, err - case 3: // load.uniform - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(UniformParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Uniform{msg} - return true, err - case 4: // load.determ - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(DeterministicParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Determ{msg} - return true, err - case 5: // load.pareto - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ParetoParams) - err := b.DecodeMessage(msg) - m.Load = &LoadParams_Pareto{msg} - return true, err - default: - return false, nil - } -} - -func _LoadParams_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadParams) - // load - switch x := m.Load.(type) { - case *LoadParams_ClosedLoop: - s := proto.Size(x.ClosedLoop) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Poisson: - s := proto.Size(x.Poisson) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Uniform: - s := proto.Size(x.Uniform) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Determ: - s := proto.Size(x.Determ) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadParams_Pareto: - s := proto.Size(x.Pareto) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// presence of SecurityParams implies use of TLS -type SecurityParams struct { - UseTestCa bool `protobuf:"varint,1,opt,name=use_test_ca,json=useTestCa,proto3" json:"use_test_ca,omitempty"` - ServerHostOverride string `protobuf:"bytes,2,opt,name=server_host_override,json=serverHostOverride,proto3" json:"server_host_override,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SecurityParams) Reset() { *m = SecurityParams{} } -func (m *SecurityParams) String() string { return proto.CompactTextString(m) } -func (*SecurityParams) ProtoMessage() {} -func (*SecurityParams) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{6} -} -func (m *SecurityParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SecurityParams.Unmarshal(m, b) -} -func (m *SecurityParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SecurityParams.Marshal(b, m, deterministic) -} -func (dst *SecurityParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_SecurityParams.Merge(dst, src) -} -func (m *SecurityParams) XXX_Size() int { - return xxx_messageInfo_SecurityParams.Size(m) -} -func (m *SecurityParams) XXX_DiscardUnknown() { - xxx_messageInfo_SecurityParams.DiscardUnknown(m) -} - -var xxx_messageInfo_SecurityParams proto.InternalMessageInfo - -func (m *SecurityParams) GetUseTestCa() bool { - if m != nil { - return m.UseTestCa - } - return false -} - -func (m *SecurityParams) GetServerHostOverride() string { - if m != nil { - return m.ServerHostOverride - } - return "" -} - -type ClientConfig struct { - // List of targets to connect to. At least one target needs to be specified. - ServerTargets []string `protobuf:"bytes,1,rep,name=server_targets,json=serverTargets,proto3" json:"server_targets,omitempty"` - ClientType ClientType `protobuf:"varint,2,opt,name=client_type,json=clientType,proto3,enum=grpc.testing.ClientType" json:"client_type,omitempty"` - SecurityParams *SecurityParams `protobuf:"bytes,3,opt,name=security_params,json=securityParams,proto3" json:"security_params,omitempty"` - // How many concurrent RPCs to start for each channel. - // For synchronous client, use a separate thread for each outstanding RPC. - OutstandingRpcsPerChannel int32 `protobuf:"varint,4,opt,name=outstanding_rpcs_per_channel,json=outstandingRpcsPerChannel,proto3" json:"outstanding_rpcs_per_channel,omitempty"` - // Number of independent client channels to create. - // i-th channel will connect to server_target[i % server_targets.size()] - ClientChannels int32 `protobuf:"varint,5,opt,name=client_channels,json=clientChannels,proto3" json:"client_channels,omitempty"` - // Only for async client. Number of threads to use to start/manage RPCs. - AsyncClientThreads int32 `protobuf:"varint,7,opt,name=async_client_threads,json=asyncClientThreads,proto3" json:"async_client_threads,omitempty"` - RpcType RpcType `protobuf:"varint,8,opt,name=rpc_type,json=rpcType,proto3,enum=grpc.testing.RpcType" json:"rpc_type,omitempty"` - // The requested load for the entire client (aggregated over all the threads). - LoadParams *LoadParams `protobuf:"bytes,10,opt,name=load_params,json=loadParams,proto3" json:"load_params,omitempty"` - PayloadConfig *PayloadConfig `protobuf:"bytes,11,opt,name=payload_config,json=payloadConfig,proto3" json:"payload_config,omitempty"` - HistogramParams *HistogramParams `protobuf:"bytes,12,opt,name=histogram_params,json=histogramParams,proto3" json:"histogram_params,omitempty"` - // Specify the cores we should run the client on, if desired - CoreList []int32 `protobuf:"varint,13,rep,packed,name=core_list,json=coreList,proto3" json:"core_list,omitempty"` - CoreLimit int32 `protobuf:"varint,14,opt,name=core_limit,json=coreLimit,proto3" json:"core_limit,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientConfig) Reset() { *m = ClientConfig{} } -func (m *ClientConfig) String() string { return proto.CompactTextString(m) } -func (*ClientConfig) ProtoMessage() {} -func (*ClientConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{7} -} -func (m *ClientConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientConfig.Unmarshal(m, b) -} -func (m *ClientConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientConfig.Marshal(b, m, deterministic) -} -func (dst *ClientConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientConfig.Merge(dst, src) -} -func (m *ClientConfig) XXX_Size() int { - return xxx_messageInfo_ClientConfig.Size(m) -} -func (m *ClientConfig) XXX_DiscardUnknown() { - xxx_messageInfo_ClientConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientConfig proto.InternalMessageInfo - -func (m *ClientConfig) GetServerTargets() []string { - if m != nil { - return m.ServerTargets - } - return nil -} - -func (m *ClientConfig) GetClientType() ClientType { - if m != nil { - return m.ClientType - } - return ClientType_SYNC_CLIENT -} - -func (m *ClientConfig) GetSecurityParams() *SecurityParams { - if m != nil { - return m.SecurityParams - } - return nil -} - -func (m *ClientConfig) GetOutstandingRpcsPerChannel() int32 { - if m != nil { - return m.OutstandingRpcsPerChannel - } - return 0 -} - -func (m *ClientConfig) GetClientChannels() int32 { - if m != nil { - return m.ClientChannels - } - return 0 -} - -func (m *ClientConfig) GetAsyncClientThreads() int32 { - if m != nil { - return m.AsyncClientThreads - } - return 0 -} - -func (m *ClientConfig) GetRpcType() RpcType { - if m != nil { - return m.RpcType - } - return RpcType_UNARY -} - -func (m *ClientConfig) GetLoadParams() *LoadParams { - if m != nil { - return m.LoadParams - } - return nil -} - -func (m *ClientConfig) GetPayloadConfig() *PayloadConfig { - if m != nil { - return m.PayloadConfig - } - return nil -} - -func (m *ClientConfig) GetHistogramParams() *HistogramParams { - if m != nil { - return m.HistogramParams - } - return nil -} - -func (m *ClientConfig) GetCoreList() []int32 { - if m != nil { - return m.CoreList - } - return nil -} - -func (m *ClientConfig) GetCoreLimit() int32 { - if m != nil { - return m.CoreLimit - } - return 0 -} - -type ClientStatus struct { - Stats *ClientStats `protobuf:"bytes,1,opt,name=stats,proto3" json:"stats,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStatus) Reset() { *m = ClientStatus{} } -func (m *ClientStatus) String() string { return proto.CompactTextString(m) } -func (*ClientStatus) ProtoMessage() {} -func (*ClientStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{8} -} -func (m *ClientStatus) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStatus.Unmarshal(m, b) -} -func (m *ClientStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStatus.Marshal(b, m, deterministic) -} -func (dst *ClientStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStatus.Merge(dst, src) -} -func (m *ClientStatus) XXX_Size() int { - return xxx_messageInfo_ClientStatus.Size(m) -} -func (m *ClientStatus) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStatus proto.InternalMessageInfo - -func (m *ClientStatus) GetStats() *ClientStats { - if m != nil { - return m.Stats - } - return nil -} - -// Request current stats -type Mark struct { - // if true, the stats will be reset after taking their snapshot. - Reset_ bool `protobuf:"varint,1,opt,name=reset,proto3" json:"reset,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Mark) Reset() { *m = Mark{} } -func (m *Mark) String() string { return proto.CompactTextString(m) } -func (*Mark) ProtoMessage() {} -func (*Mark) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{9} -} -func (m *Mark) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Mark.Unmarshal(m, b) -} -func (m *Mark) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Mark.Marshal(b, m, deterministic) -} -func (dst *Mark) XXX_Merge(src proto.Message) { - xxx_messageInfo_Mark.Merge(dst, src) -} -func (m *Mark) XXX_Size() int { - return xxx_messageInfo_Mark.Size(m) -} -func (m *Mark) XXX_DiscardUnknown() { - xxx_messageInfo_Mark.DiscardUnknown(m) -} - -var xxx_messageInfo_Mark proto.InternalMessageInfo - -func (m *Mark) GetReset_() bool { - if m != nil { - return m.Reset_ - } - return false -} - -type ClientArgs struct { - // Types that are valid to be assigned to Argtype: - // *ClientArgs_Setup - // *ClientArgs_Mark - Argtype isClientArgs_Argtype `protobuf_oneof:"argtype"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientArgs) Reset() { *m = ClientArgs{} } -func (m *ClientArgs) String() string { return proto.CompactTextString(m) } -func (*ClientArgs) ProtoMessage() {} -func (*ClientArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{10} -} -func (m *ClientArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientArgs.Unmarshal(m, b) -} -func (m *ClientArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientArgs.Marshal(b, m, deterministic) -} -func (dst *ClientArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientArgs.Merge(dst, src) -} -func (m *ClientArgs) XXX_Size() int { - return xxx_messageInfo_ClientArgs.Size(m) -} -func (m *ClientArgs) XXX_DiscardUnknown() { - xxx_messageInfo_ClientArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientArgs proto.InternalMessageInfo - -type isClientArgs_Argtype interface { - isClientArgs_Argtype() -} - -type ClientArgs_Setup struct { - Setup *ClientConfig `protobuf:"bytes,1,opt,name=setup,proto3,oneof"` -} -type ClientArgs_Mark struct { - Mark *Mark `protobuf:"bytes,2,opt,name=mark,proto3,oneof"` -} - -func (*ClientArgs_Setup) isClientArgs_Argtype() {} -func (*ClientArgs_Mark) isClientArgs_Argtype() {} - -func (m *ClientArgs) GetArgtype() isClientArgs_Argtype { - if m != nil { - return m.Argtype - } - return nil -} - -func (m *ClientArgs) GetSetup() *ClientConfig { - if x, ok := m.GetArgtype().(*ClientArgs_Setup); ok { - return x.Setup - } - return nil -} - -func (m *ClientArgs) GetMark() *Mark { - if x, ok := m.GetArgtype().(*ClientArgs_Mark); ok { - return x.Mark - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ClientArgs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ClientArgs_OneofMarshaler, _ClientArgs_OneofUnmarshaler, _ClientArgs_OneofSizer, []interface{}{ - (*ClientArgs_Setup)(nil), - (*ClientArgs_Mark)(nil), - } -} - -func _ClientArgs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ClientArgs) - // argtype - switch x := m.Argtype.(type) { - case *ClientArgs_Setup: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Setup); err != nil { - return err - } - case *ClientArgs_Mark: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Mark); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ClientArgs.Argtype has unexpected type %T", x) - } - return nil -} - -func _ClientArgs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ClientArgs) - switch tag { - case 1: // argtype.setup - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientConfig) - err := b.DecodeMessage(msg) - m.Argtype = &ClientArgs_Setup{msg} - return true, err - case 2: // argtype.mark - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Mark) - err := b.DecodeMessage(msg) - m.Argtype = &ClientArgs_Mark{msg} - return true, err - default: - return false, nil - } -} - -func _ClientArgs_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ClientArgs) - // argtype - switch x := m.Argtype.(type) { - case *ClientArgs_Setup: - s := proto.Size(x.Setup) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ClientArgs_Mark: - s := proto.Size(x.Mark) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type ServerConfig struct { - ServerType ServerType `protobuf:"varint,1,opt,name=server_type,json=serverType,proto3,enum=grpc.testing.ServerType" json:"server_type,omitempty"` - SecurityParams *SecurityParams `protobuf:"bytes,2,opt,name=security_params,json=securityParams,proto3" json:"security_params,omitempty"` - // Port on which to listen. Zero means pick unused port. - Port int32 `protobuf:"varint,4,opt,name=port,proto3" json:"port,omitempty"` - // Only for async server. Number of threads used to serve the requests. - AsyncServerThreads int32 `protobuf:"varint,7,opt,name=async_server_threads,json=asyncServerThreads,proto3" json:"async_server_threads,omitempty"` - // Specify the number of cores to limit server to, if desired - CoreLimit int32 `protobuf:"varint,8,opt,name=core_limit,json=coreLimit,proto3" json:"core_limit,omitempty"` - // payload config, used in generic server - PayloadConfig *PayloadConfig `protobuf:"bytes,9,opt,name=payload_config,json=payloadConfig,proto3" json:"payload_config,omitempty"` - // Specify the cores we should run the server on, if desired - CoreList []int32 `protobuf:"varint,10,rep,packed,name=core_list,json=coreList,proto3" json:"core_list,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerConfig) Reset() { *m = ServerConfig{} } -func (m *ServerConfig) String() string { return proto.CompactTextString(m) } -func (*ServerConfig) ProtoMessage() {} -func (*ServerConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{11} -} -func (m *ServerConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerConfig.Unmarshal(m, b) -} -func (m *ServerConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerConfig.Marshal(b, m, deterministic) -} -func (dst *ServerConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerConfig.Merge(dst, src) -} -func (m *ServerConfig) XXX_Size() int { - return xxx_messageInfo_ServerConfig.Size(m) -} -func (m *ServerConfig) XXX_DiscardUnknown() { - xxx_messageInfo_ServerConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerConfig proto.InternalMessageInfo - -func (m *ServerConfig) GetServerType() ServerType { - if m != nil { - return m.ServerType - } - return ServerType_SYNC_SERVER -} - -func (m *ServerConfig) GetSecurityParams() *SecurityParams { - if m != nil { - return m.SecurityParams - } - return nil -} - -func (m *ServerConfig) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *ServerConfig) GetAsyncServerThreads() int32 { - if m != nil { - return m.AsyncServerThreads - } - return 0 -} - -func (m *ServerConfig) GetCoreLimit() int32 { - if m != nil { - return m.CoreLimit - } - return 0 -} - -func (m *ServerConfig) GetPayloadConfig() *PayloadConfig { - if m != nil { - return m.PayloadConfig - } - return nil -} - -func (m *ServerConfig) GetCoreList() []int32 { - if m != nil { - return m.CoreList - } - return nil -} - -type ServerArgs struct { - // Types that are valid to be assigned to Argtype: - // *ServerArgs_Setup - // *ServerArgs_Mark - Argtype isServerArgs_Argtype `protobuf_oneof:"argtype"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerArgs) Reset() { *m = ServerArgs{} } -func (m *ServerArgs) String() string { return proto.CompactTextString(m) } -func (*ServerArgs) ProtoMessage() {} -func (*ServerArgs) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{12} -} -func (m *ServerArgs) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerArgs.Unmarshal(m, b) -} -func (m *ServerArgs) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerArgs.Marshal(b, m, deterministic) -} -func (dst *ServerArgs) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerArgs.Merge(dst, src) -} -func (m *ServerArgs) XXX_Size() int { - return xxx_messageInfo_ServerArgs.Size(m) -} -func (m *ServerArgs) XXX_DiscardUnknown() { - xxx_messageInfo_ServerArgs.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerArgs proto.InternalMessageInfo - -type isServerArgs_Argtype interface { - isServerArgs_Argtype() -} - -type ServerArgs_Setup struct { - Setup *ServerConfig `protobuf:"bytes,1,opt,name=setup,proto3,oneof"` -} -type ServerArgs_Mark struct { - Mark *Mark `protobuf:"bytes,2,opt,name=mark,proto3,oneof"` -} - -func (*ServerArgs_Setup) isServerArgs_Argtype() {} -func (*ServerArgs_Mark) isServerArgs_Argtype() {} - -func (m *ServerArgs) GetArgtype() isServerArgs_Argtype { - if m != nil { - return m.Argtype - } - return nil -} - -func (m *ServerArgs) GetSetup() *ServerConfig { - if x, ok := m.GetArgtype().(*ServerArgs_Setup); ok { - return x.Setup - } - return nil -} - -func (m *ServerArgs) GetMark() *Mark { - if x, ok := m.GetArgtype().(*ServerArgs_Mark); ok { - return x.Mark - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerArgs) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerArgs_OneofMarshaler, _ServerArgs_OneofUnmarshaler, _ServerArgs_OneofSizer, []interface{}{ - (*ServerArgs_Setup)(nil), - (*ServerArgs_Mark)(nil), - } -} - -func _ServerArgs_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerArgs) - // argtype - switch x := m.Argtype.(type) { - case *ServerArgs_Setup: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Setup); err != nil { - return err - } - case *ServerArgs_Mark: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Mark); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ServerArgs.Argtype has unexpected type %T", x) - } - return nil -} - -func _ServerArgs_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerArgs) - switch tag { - case 1: // argtype.setup - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerConfig) - err := b.DecodeMessage(msg) - m.Argtype = &ServerArgs_Setup{msg} - return true, err - case 2: // argtype.mark - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Mark) - err := b.DecodeMessage(msg) - m.Argtype = &ServerArgs_Mark{msg} - return true, err - default: - return false, nil - } -} - -func _ServerArgs_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerArgs) - // argtype - switch x := m.Argtype.(type) { - case *ServerArgs_Setup: - s := proto.Size(x.Setup) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerArgs_Mark: - s := proto.Size(x.Mark) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type ServerStatus struct { - Stats *ServerStats `protobuf:"bytes,1,opt,name=stats,proto3" json:"stats,omitempty"` - // the port bound by the server - Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` - // Number of cores available to the server - Cores int32 `protobuf:"varint,3,opt,name=cores,proto3" json:"cores,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerStatus) Reset() { *m = ServerStatus{} } -func (m *ServerStatus) String() string { return proto.CompactTextString(m) } -func (*ServerStatus) ProtoMessage() {} -func (*ServerStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{13} -} -func (m *ServerStatus) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerStatus.Unmarshal(m, b) -} -func (m *ServerStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerStatus.Marshal(b, m, deterministic) -} -func (dst *ServerStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerStatus.Merge(dst, src) -} -func (m *ServerStatus) XXX_Size() int { - return xxx_messageInfo_ServerStatus.Size(m) -} -func (m *ServerStatus) XXX_DiscardUnknown() { - xxx_messageInfo_ServerStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerStatus proto.InternalMessageInfo - -func (m *ServerStatus) GetStats() *ServerStats { - if m != nil { - return m.Stats - } - return nil -} - -func (m *ServerStatus) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *ServerStatus) GetCores() int32 { - if m != nil { - return m.Cores - } - return 0 -} - -type CoreRequest struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CoreRequest) Reset() { *m = CoreRequest{} } -func (m *CoreRequest) String() string { return proto.CompactTextString(m) } -func (*CoreRequest) ProtoMessage() {} -func (*CoreRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{14} -} -func (m *CoreRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CoreRequest.Unmarshal(m, b) -} -func (m *CoreRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CoreRequest.Marshal(b, m, deterministic) -} -func (dst *CoreRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoreRequest.Merge(dst, src) -} -func (m *CoreRequest) XXX_Size() int { - return xxx_messageInfo_CoreRequest.Size(m) -} -func (m *CoreRequest) XXX_DiscardUnknown() { - xxx_messageInfo_CoreRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_CoreRequest proto.InternalMessageInfo - -type CoreResponse struct { - // Number of cores available on the server - Cores int32 `protobuf:"varint,1,opt,name=cores,proto3" json:"cores,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CoreResponse) Reset() { *m = CoreResponse{} } -func (m *CoreResponse) String() string { return proto.CompactTextString(m) } -func (*CoreResponse) ProtoMessage() {} -func (*CoreResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{15} -} -func (m *CoreResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CoreResponse.Unmarshal(m, b) -} -func (m *CoreResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CoreResponse.Marshal(b, m, deterministic) -} -func (dst *CoreResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CoreResponse.Merge(dst, src) -} -func (m *CoreResponse) XXX_Size() int { - return xxx_messageInfo_CoreResponse.Size(m) -} -func (m *CoreResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CoreResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CoreResponse proto.InternalMessageInfo - -func (m *CoreResponse) GetCores() int32 { - if m != nil { - return m.Cores - } - return 0 -} - -type Void struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Void) Reset() { *m = Void{} } -func (m *Void) String() string { return proto.CompactTextString(m) } -func (*Void) ProtoMessage() {} -func (*Void) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{16} -} -func (m *Void) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Void.Unmarshal(m, b) -} -func (m *Void) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Void.Marshal(b, m, deterministic) -} -func (dst *Void) XXX_Merge(src proto.Message) { - xxx_messageInfo_Void.Merge(dst, src) -} -func (m *Void) XXX_Size() int { - return xxx_messageInfo_Void.Size(m) -} -func (m *Void) XXX_DiscardUnknown() { - xxx_messageInfo_Void.DiscardUnknown(m) -} - -var xxx_messageInfo_Void proto.InternalMessageInfo - -// A single performance scenario: input to qps_json_driver -type Scenario struct { - // Human readable name for this scenario - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Client configuration - ClientConfig *ClientConfig `protobuf:"bytes,2,opt,name=client_config,json=clientConfig,proto3" json:"client_config,omitempty"` - // Number of clients to start for the test - NumClients int32 `protobuf:"varint,3,opt,name=num_clients,json=numClients,proto3" json:"num_clients,omitempty"` - // Server configuration - ServerConfig *ServerConfig `protobuf:"bytes,4,opt,name=server_config,json=serverConfig,proto3" json:"server_config,omitempty"` - // Number of servers to start for the test - NumServers int32 `protobuf:"varint,5,opt,name=num_servers,json=numServers,proto3" json:"num_servers,omitempty"` - // Warmup period, in seconds - WarmupSeconds int32 `protobuf:"varint,6,opt,name=warmup_seconds,json=warmupSeconds,proto3" json:"warmup_seconds,omitempty"` - // Benchmark time, in seconds - BenchmarkSeconds int32 `protobuf:"varint,7,opt,name=benchmark_seconds,json=benchmarkSeconds,proto3" json:"benchmark_seconds,omitempty"` - // Number of workers to spawn locally (usually zero) - SpawnLocalWorkerCount int32 `protobuf:"varint,8,opt,name=spawn_local_worker_count,json=spawnLocalWorkerCount,proto3" json:"spawn_local_worker_count,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Scenario) Reset() { *m = Scenario{} } -func (m *Scenario) String() string { return proto.CompactTextString(m) } -func (*Scenario) ProtoMessage() {} -func (*Scenario) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{17} -} -func (m *Scenario) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Scenario.Unmarshal(m, b) -} -func (m *Scenario) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Scenario.Marshal(b, m, deterministic) -} -func (dst *Scenario) XXX_Merge(src proto.Message) { - xxx_messageInfo_Scenario.Merge(dst, src) -} -func (m *Scenario) XXX_Size() int { - return xxx_messageInfo_Scenario.Size(m) -} -func (m *Scenario) XXX_DiscardUnknown() { - xxx_messageInfo_Scenario.DiscardUnknown(m) -} - -var xxx_messageInfo_Scenario proto.InternalMessageInfo - -func (m *Scenario) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Scenario) GetClientConfig() *ClientConfig { - if m != nil { - return m.ClientConfig - } - return nil -} - -func (m *Scenario) GetNumClients() int32 { - if m != nil { - return m.NumClients - } - return 0 -} - -func (m *Scenario) GetServerConfig() *ServerConfig { - if m != nil { - return m.ServerConfig - } - return nil -} - -func (m *Scenario) GetNumServers() int32 { - if m != nil { - return m.NumServers - } - return 0 -} - -func (m *Scenario) GetWarmupSeconds() int32 { - if m != nil { - return m.WarmupSeconds - } - return 0 -} - -func (m *Scenario) GetBenchmarkSeconds() int32 { - if m != nil { - return m.BenchmarkSeconds - } - return 0 -} - -func (m *Scenario) GetSpawnLocalWorkerCount() int32 { - if m != nil { - return m.SpawnLocalWorkerCount - } - return 0 -} - -// A set of scenarios to be run with qps_json_driver -type Scenarios struct { - Scenarios []*Scenario `protobuf:"bytes,1,rep,name=scenarios,proto3" json:"scenarios,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Scenarios) Reset() { *m = Scenarios{} } -func (m *Scenarios) String() string { return proto.CompactTextString(m) } -func (*Scenarios) ProtoMessage() {} -func (*Scenarios) Descriptor() ([]byte, []int) { - return fileDescriptor_control_63d6a60a9ad7e299, []int{18} -} -func (m *Scenarios) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Scenarios.Unmarshal(m, b) -} -func (m *Scenarios) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Scenarios.Marshal(b, m, deterministic) -} -func (dst *Scenarios) XXX_Merge(src proto.Message) { - xxx_messageInfo_Scenarios.Merge(dst, src) -} -func (m *Scenarios) XXX_Size() int { - return xxx_messageInfo_Scenarios.Size(m) -} -func (m *Scenarios) XXX_DiscardUnknown() { - xxx_messageInfo_Scenarios.DiscardUnknown(m) -} - -var xxx_messageInfo_Scenarios proto.InternalMessageInfo - -func (m *Scenarios) GetScenarios() []*Scenario { - if m != nil { - return m.Scenarios - } - return nil -} - -func init() { - proto.RegisterType((*PoissonParams)(nil), "grpc.testing.PoissonParams") - proto.RegisterType((*UniformParams)(nil), "grpc.testing.UniformParams") - proto.RegisterType((*DeterministicParams)(nil), "grpc.testing.DeterministicParams") - proto.RegisterType((*ParetoParams)(nil), "grpc.testing.ParetoParams") - proto.RegisterType((*ClosedLoopParams)(nil), "grpc.testing.ClosedLoopParams") - proto.RegisterType((*LoadParams)(nil), "grpc.testing.LoadParams") - proto.RegisterType((*SecurityParams)(nil), "grpc.testing.SecurityParams") - proto.RegisterType((*ClientConfig)(nil), "grpc.testing.ClientConfig") - proto.RegisterType((*ClientStatus)(nil), "grpc.testing.ClientStatus") - proto.RegisterType((*Mark)(nil), "grpc.testing.Mark") - proto.RegisterType((*ClientArgs)(nil), "grpc.testing.ClientArgs") - proto.RegisterType((*ServerConfig)(nil), "grpc.testing.ServerConfig") - proto.RegisterType((*ServerArgs)(nil), "grpc.testing.ServerArgs") - proto.RegisterType((*ServerStatus)(nil), "grpc.testing.ServerStatus") - proto.RegisterType((*CoreRequest)(nil), "grpc.testing.CoreRequest") - proto.RegisterType((*CoreResponse)(nil), "grpc.testing.CoreResponse") - proto.RegisterType((*Void)(nil), "grpc.testing.Void") - proto.RegisterType((*Scenario)(nil), "grpc.testing.Scenario") - proto.RegisterType((*Scenarios)(nil), "grpc.testing.Scenarios") - proto.RegisterEnum("grpc.testing.ClientType", ClientType_name, ClientType_value) - proto.RegisterEnum("grpc.testing.ServerType", ServerType_name, ServerType_value) - proto.RegisterEnum("grpc.testing.RpcType", RpcType_name, RpcType_value) -} - -func init() { proto.RegisterFile("control.proto", fileDescriptor_control_63d6a60a9ad7e299) } - -var fileDescriptor_control_63d6a60a9ad7e299 = []byte{ - // 1179 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0x6f, 0x6f, 0xdb, 0xb6, - 0x13, 0xb6, 0x1d, 0xdb, 0xb1, 0x4e, 0xb6, 0xe3, 0x1f, 0x7f, 0xe9, 0xa0, 0xa6, 0x69, 0x97, 0x6a, - 0x1b, 0x16, 0x64, 0x40, 0x5a, 0x78, 0x05, 0xba, 0x62, 0x2f, 0x02, 0xc7, 0x33, 0xea, 0x00, 0x69, - 0x96, 0xd1, 0x69, 0x87, 0xbe, 0x12, 0x18, 0x99, 0xb1, 0x85, 0xc8, 0xa2, 0x46, 0x52, 0x09, 0xf2, - 0x15, 0xf6, 0x99, 0xf6, 0x39, 0xf6, 0x35, 0xf6, 0x15, 0x06, 0xfe, 0x91, 0x23, 0xb9, 0x06, 0x9a, - 0x6d, 0xef, 0xc4, 0xbb, 0xe7, 0xe1, 0x91, 0xf7, 0xdc, 0x1d, 0x05, 0x9d, 0x90, 0x25, 0x92, 0xb3, - 0xf8, 0x30, 0xe5, 0x4c, 0x32, 0xd4, 0x9e, 0xf1, 0x34, 0x3c, 0x94, 0x54, 0xc8, 0x28, 0x99, 0xed, - 0x74, 0x53, 0x72, 0x17, 0x33, 0x32, 0x15, 0xc6, 0xbb, 0xe3, 0x0a, 0x49, 0xa4, 0x5d, 0xf8, 0x7d, - 0xe8, 0x9c, 0xb3, 0x48, 0x08, 0x96, 0x9c, 0x13, 0x4e, 0x16, 0x02, 0x3d, 0x87, 0x36, 0xbb, 0xba, - 0xa2, 0x9c, 0x4e, 0x03, 0x45, 0xf2, 0xaa, 0x7b, 0xd5, 0xfd, 0x2a, 0x76, 0xad, 0xed, 0x94, 0x91, - 0xa9, 0x4f, 0xa0, 0xf3, 0x3e, 0x89, 0xae, 0x18, 0x5f, 0x58, 0xce, 0xb7, 0xb0, 0x15, 0x25, 0x92, - 0x72, 0xc2, 0x79, 0x74, 0x43, 0xe2, 0x20, 0x66, 0x96, 0xd6, 0x2d, 0x9a, 0x4f, 0xd9, 0x27, 0xc0, - 0x79, 0xe4, 0xd5, 0x3e, 0x05, 0x8e, 0x23, 0xff, 0x07, 0xf8, 0xff, 0x4f, 0x54, 0x52, 0xbe, 0x88, - 0x92, 0x48, 0xc8, 0x28, 0x7c, 0xf8, 0xe1, 0x7e, 0x81, 0xf6, 0x39, 0xe1, 0x54, 0x32, 0x4b, 0xf9, - 0x0e, 0xfe, 0x57, 0x0a, 0x79, 0x49, 0x04, 0xb5, 0xbc, 0x5e, 0xd1, 0x71, 0x4c, 0x04, 0x45, 0xdb, - 0xd0, 0x20, 0x71, 0x3a, 0x27, 0xf6, 0x54, 0x66, 0xe1, 0x23, 0xe8, 0x0d, 0x63, 0x26, 0x54, 0x00, - 0x96, 0x9a, 0x6d, 0xfd, 0x3f, 0x6a, 0x00, 0x2a, 0x9e, 0x8d, 0x32, 0x00, 0x37, 0xd4, 0x90, 0x20, - 0x66, 0x2c, 0xd5, 0xfb, 0xbb, 0xfd, 0x67, 0x87, 0x45, 0x1d, 0x0e, 0x57, 0xf7, 0x18, 0x57, 0x30, - 0x84, 0x4b, 0x1b, 0x7a, 0x0d, 0x9b, 0xa9, 0x51, 0x42, 0x47, 0x77, 0xfb, 0x4f, 0xca, 0xf4, 0x92, - 0x4c, 0xe3, 0x0a, 0xce, 0xd1, 0x8a, 0x98, 0x19, 0x39, 0xbc, 0x8d, 0x75, 0xc4, 0x92, 0x56, 0x8a, - 0x68, 0xd1, 0xe8, 0x47, 0x68, 0x4e, 0x75, 0x92, 0xbd, 0xba, 0xe6, 0x3d, 0x2f, 0xf3, 0xd6, 0x08, - 0x30, 0xae, 0x60, 0x4b, 0x41, 0xaf, 0xa0, 0x99, 0xea, 0x3c, 0x7b, 0x0d, 0x4d, 0xde, 0x59, 0x39, - 0x6d, 0x41, 0x03, 0xc5, 0x32, 0xd8, 0xe3, 0x26, 0xd4, 0x95, 0x70, 0xfe, 0x25, 0x74, 0x27, 0x34, - 0xcc, 0x78, 0x24, 0xef, 0x6c, 0x06, 0x9f, 0x81, 0x9b, 0x09, 0x1a, 0x28, 0x7e, 0x10, 0x12, 0x9d, - 0xc1, 0x16, 0x76, 0x32, 0x41, 0x2f, 0xa8, 0x90, 0x43, 0x82, 0x5e, 0xc2, 0xb6, 0xa0, 0xfc, 0x86, - 0xf2, 0x60, 0xce, 0x84, 0x0c, 0xd8, 0x0d, 0xe5, 0x3c, 0x9a, 0x52, 0x9d, 0x2b, 0x07, 0x23, 0xe3, - 0x1b, 0x33, 0x21, 0x7f, 0xb6, 0x1e, 0xff, 0xf7, 0x06, 0xb4, 0x87, 0x71, 0x44, 0x13, 0x39, 0x64, - 0xc9, 0x55, 0x34, 0x43, 0xdf, 0x40, 0xd7, 0x6e, 0x21, 0x09, 0x9f, 0x51, 0x29, 0xbc, 0xea, 0xde, - 0xc6, 0xbe, 0x83, 0x3b, 0xc6, 0x7a, 0x61, 0x8c, 0xe8, 0x8d, 0xd2, 0x52, 0xd1, 0x02, 0x79, 0x97, - 0x9a, 0x00, 0xdd, 0xbe, 0xb7, 0xaa, 0xa5, 0x02, 0x5c, 0xdc, 0xa5, 0x54, 0x69, 0x98, 0x7f, 0xa3, - 0x11, 0x6c, 0x09, 0x7b, 0xad, 0x20, 0xd5, 0xf7, 0xb2, 0x92, 0xec, 0x96, 0xe9, 0xe5, 0xbb, 0xe3, - 0xae, 0x28, 0xe7, 0xe2, 0x08, 0x76, 0x59, 0x26, 0x85, 0x24, 0xc9, 0x34, 0x4a, 0x66, 0x01, 0x4f, - 0x43, 0x11, 0xa4, 0x94, 0x07, 0xe1, 0x9c, 0x24, 0x09, 0x8d, 0xb5, 0x5c, 0x0d, 0xfc, 0xb8, 0x80, - 0xc1, 0x69, 0x28, 0xce, 0x29, 0x1f, 0x1a, 0x80, 0xea, 0x33, 0x7b, 0x05, 0x4b, 0x11, 0x5a, 0xa5, - 0x06, 0xee, 0x1a, 0xb3, 0xc5, 0x09, 0x95, 0x55, 0x22, 0xee, 0x92, 0x30, 0xc8, 0x6f, 0x3c, 0xe7, - 0x94, 0x4c, 0x85, 0xb7, 0xa9, 0xd1, 0x48, 0xfb, 0xec, 0x5d, 0x8d, 0x07, 0xbd, 0x84, 0x16, 0x4f, - 0x43, 0x93, 0x9a, 0x96, 0x4e, 0xcd, 0xa3, 0xf2, 0xdd, 0x70, 0x1a, 0xea, 0xbc, 0x6c, 0x72, 0xf3, - 0xa1, 0xf2, 0xa9, 0x34, 0xcf, 0x13, 0x02, 0x3a, 0x21, 0x2b, 0xf9, 0xbc, 0x6f, 0x25, 0x0c, 0xf1, - 0x7d, 0x5b, 0x1d, 0x43, 0x3e, 0xbc, 0x82, 0x50, 0x6b, 0xe8, 0xb9, 0x6b, 0x5b, 0xc3, 0x60, 0x8c, - 0xcc, 0xb8, 0x93, 0x16, 0x97, 0x68, 0x0c, 0xbd, 0x79, 0x24, 0x24, 0x9b, 0x71, 0xb2, 0xc8, 0xcf, - 0xd0, 0xd6, 0xbb, 0x3c, 0x2d, 0xef, 0x32, 0xce, 0x51, 0xf6, 0x20, 0x5b, 0xf3, 0xb2, 0x01, 0x3d, - 0x01, 0x27, 0x64, 0x9c, 0x06, 0x71, 0x24, 0xa4, 0xd7, 0xd9, 0xdb, 0xd8, 0x6f, 0xe0, 0x96, 0x32, - 0x9c, 0x46, 0x42, 0xa2, 0xa7, 0x00, 0xd6, 0xb9, 0x88, 0xa4, 0xd7, 0xd5, 0xf9, 0x73, 0x8c, 0x77, - 0x11, 0x49, 0xff, 0x28, 0xaf, 0xc5, 0x89, 0x24, 0x32, 0x13, 0xe8, 0x05, 0x34, 0xf4, 0x18, 0xb6, - 0xa3, 0xe2, 0xf1, 0xba, 0xf2, 0x52, 0x50, 0x81, 0x0d, 0xce, 0xdf, 0x85, 0xfa, 0x3b, 0xc2, 0xaf, - 0xd5, 0x88, 0xe2, 0x54, 0x50, 0x69, 0x3b, 0xc4, 0x2c, 0xfc, 0x0c, 0xc0, 0x70, 0x06, 0x7c, 0x26, - 0x50, 0x1f, 0x1a, 0x82, 0xca, 0x2c, 0x9f, 0x43, 0x3b, 0xeb, 0x36, 0x37, 0xd9, 0x19, 0x57, 0xb0, - 0x81, 0xa2, 0x7d, 0xa8, 0x2f, 0x08, 0xbf, 0xb6, 0xb3, 0x07, 0x95, 0x29, 0x2a, 0xf2, 0xb8, 0x82, - 0x35, 0xe2, 0xd8, 0x81, 0x4d, 0xc2, 0x67, 0xaa, 0x00, 0xfc, 0x3f, 0x6b, 0xd0, 0x9e, 0xe8, 0xe6, - 0xb1, 0xc9, 0x7e, 0x03, 0x6e, 0xde, 0x62, 0xaa, 0x40, 0xaa, 0xeb, 0x7a, 0xc7, 0x10, 0x4c, 0xef, - 0x88, 0xe5, 0xf7, 0xba, 0xde, 0xa9, 0xfd, 0x8b, 0xde, 0x41, 0x50, 0x4f, 0x19, 0x97, 0xb6, 0x47, - 0xf4, 0xf7, 0x7d, 0x95, 0xe7, 0x67, 0x5b, 0x53, 0xe5, 0xf6, 0x54, 0xb6, 0xca, 0xcb, 0x6a, 0xb6, - 0x56, 0xd4, 0x5c, 0x53, 0x97, 0xce, 0x3f, 0xae, 0xcb, 0x52, 0x35, 0x41, 0xb9, 0x9a, 0x94, 0x9e, - 0xe6, 0x40, 0x0f, 0xd0, 0xb3, 0x28, 0xc0, 0x7f, 0xd4, 0x33, 0xca, 0xe5, 0x7c, 0x50, 0x95, 0xde, - 0x43, 0xf3, 0x2a, 0x5d, 0x66, 0xbf, 0x56, 0xc8, 0xfe, 0x36, 0x34, 0xd4, 0xbd, 0xcc, 0x28, 0x6c, - 0x60, 0xb3, 0xf0, 0x3b, 0xe0, 0x0e, 0x19, 0xa7, 0x98, 0xfe, 0x96, 0x51, 0x21, 0xfd, 0xaf, 0xa1, - 0x6d, 0x96, 0x22, 0x65, 0x89, 0x79, 0x89, 0x0d, 0xa9, 0x5a, 0x24, 0x35, 0xa1, 0xfe, 0x81, 0x45, - 0x53, 0xff, 0xaf, 0x1a, 0xb4, 0x26, 0x21, 0x4d, 0x08, 0x8f, 0x98, 0x8a, 0x99, 0x90, 0x85, 0x29, - 0x36, 0x07, 0xeb, 0x6f, 0x74, 0x04, 0x9d, 0x7c, 0x00, 0x1a, 0x7d, 0x6a, 0x9f, 0xeb, 0x04, 0xdc, - 0x0e, 0x8b, 0x6f, 0xc5, 0x97, 0xe0, 0x26, 0xd9, 0xc2, 0x8e, 0xc5, 0xfc, 0xe8, 0x90, 0x64, 0x0b, - 0xc3, 0x51, 0x33, 0xda, 0x3e, 0x1b, 0x79, 0x84, 0xfa, 0xe7, 0xb4, 0xc1, 0x6d, 0x51, 0x6c, 0x15, - 0x1b, 0xc1, 0xd8, 0xf2, 0xf9, 0xac, 0x22, 0x18, 0x8e, 0x50, 0xcf, 0xd5, 0x2d, 0xe1, 0x8b, 0x2c, - 0x0d, 0x04, 0x0d, 0x59, 0x32, 0x15, 0x5e, 0x53, 0x63, 0x3a, 0xc6, 0x3a, 0x31, 0x46, 0xf5, 0x83, - 0x73, 0x49, 0x93, 0x70, 0xae, 0xb4, 0x5c, 0x22, 0x4d, 0x65, 0xf7, 0x96, 0x8e, 0x1c, 0xfc, 0x1a, - 0x3c, 0x91, 0x92, 0xdb, 0x24, 0x88, 0x59, 0x48, 0xe2, 0xe0, 0x96, 0xf1, 0x6b, 0x7d, 0x83, 0x2c, - 0xc9, 0xab, 0xfc, 0x91, 0xf6, 0x9f, 0x2a, 0xf7, 0xaf, 0xda, 0x3b, 0x54, 0x4e, 0x7f, 0x00, 0x4e, - 0x9e, 0x70, 0x81, 0x5e, 0x81, 0x23, 0xf2, 0x85, 0x7e, 0x43, 0xdd, 0xfe, 0x17, 0x2b, 0xf7, 0xb6, - 0x6e, 0x7c, 0x0f, 0x3c, 0x78, 0x91, 0xcf, 0x28, 0xdd, 0xee, 0x5b, 0xe0, 0x4e, 0x3e, 0x9e, 0x0d, - 0x83, 0xe1, 0xe9, 0xc9, 0xe8, 0xec, 0xa2, 0x57, 0x41, 0x3d, 0x68, 0x0f, 0x8a, 0x96, 0xea, 0xc1, - 0x49, 0xde, 0x04, 0x25, 0xc2, 0x64, 0x84, 0x3f, 0x8c, 0x70, 0x91, 0x60, 0x2d, 0x55, 0xe4, 0xc1, - 0xb6, 0xb1, 0xbc, 0x1d, 0x9d, 0x8d, 0xf0, 0xc9, 0xd2, 0x53, 0x3b, 0xf8, 0x0a, 0x36, 0xed, 0xbb, - 0x84, 0x1c, 0x68, 0xbc, 0x3f, 0x1b, 0xe0, 0x8f, 0xbd, 0x0a, 0xea, 0x80, 0x33, 0xb9, 0xc0, 0xa3, - 0xc1, 0xbb, 0x93, 0xb3, 0xb7, 0xbd, 0xea, 0x65, 0x53, 0xff, 0x12, 0x7f, 0xff, 0x77, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x75, 0x59, 0xf4, 0x03, 0x4e, 0x0b, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/control.proto b/examples/google.golang.org/grpc/benchmark/grpc_testing/control.proto deleted file mode 100755 index 9379ef4..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/control.proto +++ /dev/null @@ -1,186 +0,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. - -syntax = "proto3"; - -import "payloads.proto"; -import "stats.proto"; - -package grpc.testing; - -enum ClientType { - SYNC_CLIENT = 0; - ASYNC_CLIENT = 1; -} - -enum ServerType { - SYNC_SERVER = 0; - ASYNC_SERVER = 1; - ASYNC_GENERIC_SERVER = 2; -} - -enum RpcType { - UNARY = 0; - STREAMING = 1; -} - -// Parameters of poisson process distribution, which is a good representation -// of activity coming in from independent identical stationary sources. -message PoissonParams { - // The rate of arrivals (a.k.a. lambda parameter of the exp distribution). - double offered_load = 1; -} - -message UniformParams { - double interarrival_lo = 1; - double interarrival_hi = 2; -} - -message DeterministicParams { - double offered_load = 1; -} - -message ParetoParams { - double interarrival_base = 1; - double alpha = 2; -} - -// Once an RPC finishes, immediately start a new one. -// No configuration parameters needed. -message ClosedLoopParams { -} - -message LoadParams { - oneof load { - ClosedLoopParams closed_loop = 1; - PoissonParams poisson = 2; - UniformParams uniform = 3; - DeterministicParams determ = 4; - ParetoParams pareto = 5; - }; -} - -// presence of SecurityParams implies use of TLS -message SecurityParams { - bool use_test_ca = 1; - string server_host_override = 2; -} - -message ClientConfig { - // List of targets to connect to. At least one target needs to be specified. - repeated string server_targets = 1; - ClientType client_type = 2; - SecurityParams security_params = 3; - // How many concurrent RPCs to start for each channel. - // For synchronous client, use a separate thread for each outstanding RPC. - int32 outstanding_rpcs_per_channel = 4; - // Number of independent client channels to create. - // i-th channel will connect to server_target[i % server_targets.size()] - int32 client_channels = 5; - // Only for async client. Number of threads to use to start/manage RPCs. - int32 async_client_threads = 7; - RpcType rpc_type = 8; - // The requested load for the entire client (aggregated over all the threads). - LoadParams load_params = 10; - PayloadConfig payload_config = 11; - HistogramParams histogram_params = 12; - - // Specify the cores we should run the client on, if desired - repeated int32 core_list = 13; - int32 core_limit = 14; -} - -message ClientStatus { - ClientStats stats = 1; -} - -// Request current stats -message Mark { - // if true, the stats will be reset after taking their snapshot. - bool reset = 1; -} - -message ClientArgs { - oneof argtype { - ClientConfig setup = 1; - Mark mark = 2; - } -} - -message ServerConfig { - ServerType server_type = 1; - SecurityParams security_params = 2; - // Port on which to listen. Zero means pick unused port. - int32 port = 4; - // Only for async server. Number of threads used to serve the requests. - 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 - PayloadConfig payload_config = 9; - - // Specify the cores we should run the server on, if desired - repeated int32 core_list = 10; -} - -message ServerArgs { - oneof argtype { - ServerConfig setup = 1; - Mark mark = 2; - } -} - -message ServerStatus { - ServerStats stats = 1; - // the port bound by the server - int32 port = 2; - // Number of cores available to the server - int32 cores = 3; -} - -message CoreRequest { -} - -message CoreResponse { - // Number of cores available on the server - int32 cores = 1; -} - -message Void { -} - -// A single performance scenario: input to qps_json_driver -message Scenario { - // Human readable name for this scenario - string name = 1; - // Client configuration - ClientConfig client_config = 2; - // Number of clients to start for the test - int32 num_clients = 3; - // Server configuration - ServerConfig server_config = 4; - // Number of servers to start for the test - int32 num_servers = 5; - // Warmup period, in seconds - int32 warmup_seconds = 6; - // Benchmark time, in seconds - int32 benchmark_seconds = 7; - // Number of workers to spawn locally (usually zero) - int32 spawn_local_worker_count = 8; -} - -// A set of scenarios to be run with qps_json_driver -message Scenarios { - repeated Scenario scenarios = 1; -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go b/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go deleted file mode 100755 index 9354eea..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.pb.go +++ /dev/null @@ -1,731 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: messages.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{0} -} - -// Compression algorithms -type CompressionType int32 - -const ( - // No compression - CompressionType_NONE CompressionType = 0 - CompressionType_GZIP CompressionType = 1 - CompressionType_DEFLATE CompressionType = 2 -) - -var CompressionType_name = map[int32]string{ - 0: "NONE", - 1: "GZIP", - 2: "DEFLATE", -} -var CompressionType_value = map[string]int32{ - "NONE": 0, - "GZIP": 1, - "DEFLATE": 2, -} - -func (x CompressionType) String() string { - return proto.EnumName(CompressionType_name, int32(x)) -} -func (CompressionType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{1} -} - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type PayloadType `protobuf:"varint,1,opt,name=type,proto3,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{0} -} -func (m *Payload) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Payload.Unmarshal(m, b) -} -func (m *Payload) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Payload.Marshal(b, m, deterministic) -} -func (dst *Payload) XXX_Merge(src proto.Message) { - xxx_messageInfo_Payload.Merge(dst, src) -} -func (m *Payload) XXX_Size() int { - return xxx_messageInfo_Payload.Size(m) -} -func (m *Payload) XXX_DiscardUnknown() { - xxx_messageInfo_Payload.DiscardUnknown(m) -} - -var xxx_messageInfo_Payload proto.InternalMessageInfo - -func (m *Payload) GetType() PayloadType { - if m != nil { - return m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -type EchoStatus struct { - Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoStatus) Reset() { *m = EchoStatus{} } -func (m *EchoStatus) String() string { return proto.CompactTextString(m) } -func (*EchoStatus) ProtoMessage() {} -func (*EchoStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{1} -} -func (m *EchoStatus) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoStatus.Unmarshal(m, b) -} -func (m *EchoStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoStatus.Marshal(b, m, deterministic) -} -func (dst *EchoStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoStatus.Merge(dst, src) -} -func (m *EchoStatus) XXX_Size() int { - return xxx_messageInfo_EchoStatus.Size(m) -} -func (m *EchoStatus) XXX_DiscardUnknown() { - xxx_messageInfo_EchoStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoStatus proto.InternalMessageInfo - -func (m *EchoStatus) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *EchoStatus) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize,proto3" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername,proto3" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope,proto3" json:"fill_oauth_scope,omitempty"` - // Compression algorithm to be used by the server for the response (stream) - ResponseCompression CompressionType `protobuf:"varint,6,opt,name=response_compression,json=responseCompression,proto3,enum=grpc.testing.CompressionType" json:"response_compression,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{2} -} -func (m *SimpleRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleRequest.Unmarshal(m, b) -} -func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic) -} -func (dst *SimpleRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleRequest.Merge(dst, src) -} -func (m *SimpleRequest) XXX_Size() int { - return xxx_messageInfo_SimpleRequest.Size(m) -} -func (m *SimpleRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil { - return m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil { - return m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil { - return m.FillOauthScope - } - return false -} - -func (m *SimpleRequest) GetResponseCompression() CompressionType { - if m != nil { - return m.ResponseCompression - } - return CompressionType_NONE -} - -func (m *SimpleRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - // OAuth scope. - OauthScope string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope,proto3" json:"oauth_scope,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{3} -} -func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) -} -func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) -} -func (dst *SimpleResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleResponse.Merge(dst, src) -} -func (m *SimpleResponse) XXX_Size() int { - return xxx_messageInfo_SimpleResponse.Size(m) -} -func (m *SimpleResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil { - return m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{4} -} -func (m *StreamingInputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallRequest.Unmarshal(m, b) -} -func (m *StreamingInputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallRequest.Merge(dst, src) -} -func (m *StreamingInputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallRequest.Size(m) -} -func (m *StreamingInputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallRequest proto.InternalMessageInfo - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize,proto3" json:"aggregated_payload_size,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{5} -} -func (m *StreamingInputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallResponse.Unmarshal(m, b) -} -func (m *StreamingInputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallResponse.Merge(dst, src) -} -func (m *StreamingInputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallResponse.Size(m) -} -func (m *StreamingInputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallResponse proto.InternalMessageInfo - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil { - return m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size int32 `protobuf:"varint,1,opt,name=size,proto3" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs,proto3" json:"interval_us,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{6} -} -func (m *ResponseParameters) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseParameters.Unmarshal(m, b) -} -func (m *ResponseParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseParameters.Marshal(b, m, deterministic) -} -func (dst *ResponseParameters) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseParameters.Merge(dst, src) -} -func (m *ResponseParameters) XXX_Size() int { - return xxx_messageInfo_ResponseParameters.Size(m) -} -func (m *ResponseParameters) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseParameters.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseParameters proto.InternalMessageInfo - -func (m *ResponseParameters) GetSize() int32 { - if m != nil { - return m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil { - return m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters,proto3" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - // Compression algorithm to be used by the server for the response (stream) - ResponseCompression CompressionType `protobuf:"varint,6,opt,name=response_compression,json=responseCompression,proto3,enum=grpc.testing.CompressionType" json:"response_compression,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{7} -} -func (m *StreamingOutputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallRequest.Unmarshal(m, b) -} -func (m *StreamingOutputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallRequest.Merge(dst, src) -} -func (m *StreamingOutputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallRequest.Size(m) -} -func (m *StreamingOutputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallRequest proto.InternalMessageInfo - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *StreamingOutputCallRequest) GetResponseCompression() CompressionType { - if m != nil { - return m.ResponseCompression - } - return CompressionType_NONE -} - -func (m *StreamingOutputCallRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{8} -} -func (m *StreamingOutputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallResponse.Unmarshal(m, b) -} -func (m *StreamingOutputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallResponse.Merge(dst, src) -} -func (m *StreamingOutputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallResponse.Size(m) -} -func (m *StreamingOutputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallResponse proto.InternalMessageInfo - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// For reconnect interop test only. -// Client tells server what reconnection parameters it used. -type ReconnectParams struct { - MaxReconnectBackoffMs int32 `protobuf:"varint,1,opt,name=max_reconnect_backoff_ms,json=maxReconnectBackoffMs,proto3" json:"max_reconnect_backoff_ms,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReconnectParams) Reset() { *m = ReconnectParams{} } -func (m *ReconnectParams) String() string { return proto.CompactTextString(m) } -func (*ReconnectParams) ProtoMessage() {} -func (*ReconnectParams) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{9} -} -func (m *ReconnectParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReconnectParams.Unmarshal(m, b) -} -func (m *ReconnectParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReconnectParams.Marshal(b, m, deterministic) -} -func (dst *ReconnectParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReconnectParams.Merge(dst, src) -} -func (m *ReconnectParams) XXX_Size() int { - return xxx_messageInfo_ReconnectParams.Size(m) -} -func (m *ReconnectParams) XXX_DiscardUnknown() { - xxx_messageInfo_ReconnectParams.DiscardUnknown(m) -} - -var xxx_messageInfo_ReconnectParams proto.InternalMessageInfo - -func (m *ReconnectParams) GetMaxReconnectBackoffMs() int32 { - if m != nil { - return m.MaxReconnectBackoffMs - } - return 0 -} - -// For reconnect interop test only. -// Server tells client whether its reconnects are following the spec and the -// reconnect backoffs it saw. -type ReconnectInfo struct { - Passed bool `protobuf:"varint,1,opt,name=passed,proto3" json:"passed,omitempty"` - BackoffMs []int32 `protobuf:"varint,2,rep,packed,name=backoff_ms,json=backoffMs,proto3" json:"backoff_ms,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ReconnectInfo) Reset() { *m = ReconnectInfo{} } -func (m *ReconnectInfo) String() string { return proto.CompactTextString(m) } -func (*ReconnectInfo) ProtoMessage() {} -func (*ReconnectInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_5c70222ad96bf232, []int{10} -} -func (m *ReconnectInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ReconnectInfo.Unmarshal(m, b) -} -func (m *ReconnectInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ReconnectInfo.Marshal(b, m, deterministic) -} -func (dst *ReconnectInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ReconnectInfo.Merge(dst, src) -} -func (m *ReconnectInfo) XXX_Size() int { - return xxx_messageInfo_ReconnectInfo.Size(m) -} -func (m *ReconnectInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ReconnectInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ReconnectInfo proto.InternalMessageInfo - -func (m *ReconnectInfo) GetPassed() bool { - if m != nil { - return m.Passed - } - return false -} - -func (m *ReconnectInfo) GetBackoffMs() []int32 { - if m != nil { - return m.BackoffMs - } - return nil -} - -func init() { - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*EchoStatus)(nil), "grpc.testing.EchoStatus") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterType((*ReconnectParams)(nil), "grpc.testing.ReconnectParams") - proto.RegisterType((*ReconnectInfo)(nil), "grpc.testing.ReconnectInfo") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) - proto.RegisterEnum("grpc.testing.CompressionType", CompressionType_name, CompressionType_value) -} - -func init() { proto.RegisterFile("messages.proto", fileDescriptor_messages_5c70222ad96bf232) } - -var fileDescriptor_messages_5c70222ad96bf232 = []byte{ - // 652 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x6f, 0xd3, 0x40, - 0x10, 0xc5, 0xf9, 0xee, 0x24, 0x4d, 0xa3, 0x85, 0x82, 0x5b, 0x54, 0x11, 0x99, 0x4b, 0x54, 0x89, - 0x20, 0x05, 0x09, 0x24, 0x0e, 0xa0, 0xb4, 0x4d, 0x51, 0x50, 0x9a, 0x84, 0x75, 0x7b, 0xe1, 0x62, - 0x6d, 0x9c, 0x8d, 0x6b, 0x11, 0x7b, 0x8d, 0x77, 0x8d, 0x9a, 0x1e, 0xb8, 0xf3, 0x83, 0xb9, 0xa3, - 0x5d, 0x7f, 0xc4, 0x69, 0x7b, 0x68, 0xe1, 0xc2, 0x6d, 0xf7, 0xed, 0x9b, 0x97, 0x79, 0x33, 0xcf, - 0x0a, 0x34, 0x3d, 0xca, 0x39, 0x71, 0x28, 0xef, 0x06, 0x21, 0x13, 0x0c, 0x35, 0x9c, 0x30, 0xb0, - 0xbb, 0x82, 0x72, 0xe1, 0xfa, 0x8e, 0x31, 0x82, 0xea, 0x94, 0xac, 0x96, 0x8c, 0xcc, 0xd1, 0x2b, - 0x28, 0x89, 0x55, 0x40, 0x75, 0xad, 0xad, 0x75, 0x9a, 0xbd, 0xbd, 0x6e, 0x9e, 0xd7, 0x4d, 0x48, - 0xe7, 0xab, 0x80, 0x62, 0x45, 0x43, 0x08, 0x4a, 0x33, 0x36, 0x5f, 0xe9, 0x85, 0xb6, 0xd6, 0x69, - 0x60, 0x75, 0x36, 0xde, 0x03, 0x0c, 0xec, 0x4b, 0x66, 0x0a, 0x22, 0x22, 0x2e, 0x19, 0x36, 0x9b, - 0xc7, 0x82, 0x65, 0xac, 0xce, 0x48, 0x87, 0x6a, 0xd2, 0x8f, 0x2a, 0xdc, 0xc2, 0xe9, 0xd5, 0xf8, - 0x55, 0x84, 0x6d, 0xd3, 0xf5, 0x82, 0x25, 0xc5, 0xf4, 0x7b, 0x44, 0xb9, 0x40, 0x1f, 0x60, 0x3b, - 0xa4, 0x3c, 0x60, 0x3e, 0xa7, 0xd6, 0xfd, 0x3a, 0x6b, 0xa4, 0x7c, 0x79, 0x43, 0x2f, 0x73, 0xf5, - 0xdc, 0xbd, 0x8e, 0x7f, 0xb1, 0xbc, 0x26, 0x99, 0xee, 0x35, 0x45, 0xaf, 0xa1, 0x1a, 0xc4, 0x0a, - 0x7a, 0xb1, 0xad, 0x75, 0xea, 0xbd, 0xdd, 0x3b, 0xe5, 0x71, 0xca, 0x92, 0xaa, 0x0b, 0x77, 0xb9, - 0xb4, 0x22, 0x4e, 0x43, 0x9f, 0x78, 0x54, 0x2f, 0xb5, 0xb5, 0x4e, 0x0d, 0x37, 0x24, 0x78, 0x91, - 0x60, 0xa8, 0x03, 0x2d, 0x45, 0x62, 0x24, 0x12, 0x97, 0x16, 0xb7, 0x59, 0x40, 0xf5, 0xb2, 0xe2, - 0x35, 0x25, 0x3e, 0x91, 0xb0, 0x29, 0x51, 0x34, 0x85, 0x27, 0x59, 0x93, 0x36, 0xf3, 0x82, 0x90, - 0x72, 0xee, 0x32, 0x5f, 0xaf, 0x28, 0xaf, 0x07, 0x9b, 0xcd, 0x1c, 0xaf, 0x09, 0xca, 0xef, 0xe3, - 0xb4, 0x34, 0xf7, 0x80, 0xfa, 0xb0, 0xb3, 0xb6, 0xad, 0x36, 0xa1, 0x57, 0x95, 0x33, 0x7d, 0x53, - 0x6c, 0xbd, 0x29, 0xdc, 0xcc, 0x46, 0xa2, 0xee, 0xc6, 0x4f, 0x68, 0xa6, 0xab, 0x88, 0xf1, 0xfc, - 0x98, 0xb4, 0x7b, 0x8d, 0x69, 0x1f, 0x6a, 0xd9, 0x84, 0xe2, 0x4d, 0x67, 0x77, 0xf4, 0x02, 0xea, - 0xf9, 0xc1, 0x14, 0xd5, 0x33, 0xb0, 0x6c, 0x28, 0xc6, 0x08, 0xf6, 0x4c, 0x11, 0x52, 0xe2, 0xb9, - 0xbe, 0x33, 0xf4, 0x83, 0x48, 0x1c, 0x93, 0xe5, 0x32, 0x8d, 0xc5, 0x43, 0x5b, 0x31, 0xce, 0x61, - 0xff, 0x2e, 0xb5, 0xc4, 0xd9, 0x5b, 0x78, 0x46, 0x1c, 0x27, 0xa4, 0x0e, 0x11, 0x74, 0x6e, 0x25, - 0x35, 0x71, 0x5e, 0xe2, 0xe0, 0xee, 0xae, 0x9f, 0x13, 0x69, 0x19, 0x1c, 0x63, 0x08, 0x28, 0xd5, - 0x98, 0x92, 0x90, 0x78, 0x54, 0xd0, 0x50, 0x65, 0x3e, 0x57, 0xaa, 0xce, 0xd2, 0xae, 0xeb, 0x0b, - 0x1a, 0xfe, 0x20, 0x32, 0x35, 0x49, 0x0a, 0x21, 0x85, 0x2e, 0xb8, 0xf1, 0xbb, 0x90, 0xeb, 0x70, - 0x12, 0x89, 0x1b, 0x86, 0xff, 0xf5, 0x3b, 0xf8, 0x02, 0x59, 0x4e, 0xac, 0x20, 0x6b, 0x55, 0x2f, - 0xb4, 0x8b, 0x9d, 0x7a, 0xaf, 0xbd, 0xa9, 0x72, 0xdb, 0x12, 0x46, 0xe1, 0x6d, 0x9b, 0x0f, 0xfe, - 0x6a, 0xfe, 0xcb, 0x98, 0x8f, 0xe1, 0xf9, 0x9d, 0x63, 0xff, 0xcb, 0xcc, 0x1b, 0x9f, 0x61, 0x07, - 0x53, 0x9b, 0xf9, 0x3e, 0xb5, 0x85, 0x1a, 0x16, 0x47, 0xef, 0x40, 0xf7, 0xc8, 0x95, 0x15, 0xa6, - 0xb0, 0x35, 0x23, 0xf6, 0x37, 0xb6, 0x58, 0x58, 0x1e, 0x4f, 0xe3, 0xe5, 0x91, 0xab, 0xac, 0xea, - 0x28, 0x7e, 0x3d, 0xe3, 0xc6, 0x29, 0x6c, 0x67, 0xe8, 0xd0, 0x5f, 0x30, 0xf4, 0x14, 0x2a, 0x01, - 0xe1, 0x9c, 0xc6, 0xcd, 0xd4, 0x70, 0x72, 0x43, 0x07, 0x00, 0x39, 0x4d, 0xb9, 0xd4, 0x32, 0xde, - 0x9a, 0xa5, 0x3a, 0x87, 0x1f, 0xa1, 0x9e, 0x4b, 0x06, 0x6a, 0x41, 0xe3, 0x78, 0x72, 0x36, 0xc5, - 0x03, 0xd3, 0xec, 0x1f, 0x8d, 0x06, 0xad, 0x47, 0x08, 0x41, 0xf3, 0x62, 0xbc, 0x81, 0x69, 0x08, - 0xa0, 0x82, 0xfb, 0xe3, 0x93, 0xc9, 0x59, 0xab, 0x70, 0xd8, 0x83, 0x9d, 0x1b, 0xfb, 0x40, 0x35, - 0x28, 0x8d, 0x27, 0x63, 0x59, 0x5c, 0x83, 0xd2, 0xa7, 0xaf, 0xc3, 0x69, 0x4b, 0x43, 0x75, 0xa8, - 0x9e, 0x0c, 0x4e, 0x47, 0xfd, 0xf3, 0x41, 0xab, 0x30, 0xab, 0xa8, 0xbf, 0x9a, 0x37, 0x7f, 0x02, - 0x00, 0x00, 0xff, 0xff, 0xc2, 0x6a, 0xce, 0x1e, 0x7c, 0x06, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.proto b/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.proto deleted file mode 100755 index bd83f09..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/messages.proto +++ /dev/null @@ -1,157 +0,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. - -// Message definitions to be used by integration test service definitions. - -syntax = "proto3"; - -package grpc.testing; - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// Compression algorithms -enum CompressionType { - // No compression - NONE = 0; - GZIP = 1; - DEFLATE = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - PayloadType type = 1; - // Primary contents of payload. - bytes body = 2; -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -message EchoStatus { - int32 code = 1; - string message = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 response_size = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Whether SimpleResponse should include username. - bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - bool fill_oauth_scope = 5; - - // Compression algorithm to be used by the server for the response (stream) - CompressionType response_compression = 6; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - Payload payload = 1; - // The user the request came from, for verifying authentication was - // successful when the client expected it. - string username = 2; - // OAuth scope. - string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Compression algorithm to be used by the server for the response (stream) - CompressionType response_compression = 6; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - Payload payload = 1; -} - -// For reconnect interop test only. -// Client tells server what reconnection parameters it used. -message ReconnectParams { - int32 max_reconnect_backoff_ms = 1; -} - -// For reconnect interop test only. -// Server tells client whether its reconnects are following the spec and the -// reconnect backoffs it saw. -message ReconnectInfo { - bool passed = 1; - repeated int32 backoff_ms = 2; -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go b/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go deleted file mode 100755 index 1882fe7..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.pb.go +++ /dev/null @@ -1,344 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: payloads.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ByteBufferParams struct { - ReqSize int32 `protobuf:"varint,1,opt,name=req_size,json=reqSize,proto3" json:"req_size,omitempty"` - RespSize int32 `protobuf:"varint,2,opt,name=resp_size,json=respSize,proto3" json:"resp_size,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ByteBufferParams) Reset() { *m = ByteBufferParams{} } -func (m *ByteBufferParams) String() string { return proto.CompactTextString(m) } -func (*ByteBufferParams) ProtoMessage() {} -func (*ByteBufferParams) Descriptor() ([]byte, []int) { - return fileDescriptor_payloads_3abc71de35f06c83, []int{0} -} -func (m *ByteBufferParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ByteBufferParams.Unmarshal(m, b) -} -func (m *ByteBufferParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ByteBufferParams.Marshal(b, m, deterministic) -} -func (dst *ByteBufferParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_ByteBufferParams.Merge(dst, src) -} -func (m *ByteBufferParams) XXX_Size() int { - return xxx_messageInfo_ByteBufferParams.Size(m) -} -func (m *ByteBufferParams) XXX_DiscardUnknown() { - xxx_messageInfo_ByteBufferParams.DiscardUnknown(m) -} - -var xxx_messageInfo_ByteBufferParams proto.InternalMessageInfo - -func (m *ByteBufferParams) GetReqSize() int32 { - if m != nil { - return m.ReqSize - } - return 0 -} - -func (m *ByteBufferParams) GetRespSize() int32 { - if m != nil { - return m.RespSize - } - return 0 -} - -type SimpleProtoParams struct { - ReqSize int32 `protobuf:"varint,1,opt,name=req_size,json=reqSize,proto3" json:"req_size,omitempty"` - RespSize int32 `protobuf:"varint,2,opt,name=resp_size,json=respSize,proto3" json:"resp_size,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleProtoParams) Reset() { *m = SimpleProtoParams{} } -func (m *SimpleProtoParams) String() string { return proto.CompactTextString(m) } -func (*SimpleProtoParams) ProtoMessage() {} -func (*SimpleProtoParams) Descriptor() ([]byte, []int) { - return fileDescriptor_payloads_3abc71de35f06c83, []int{1} -} -func (m *SimpleProtoParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleProtoParams.Unmarshal(m, b) -} -func (m *SimpleProtoParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleProtoParams.Marshal(b, m, deterministic) -} -func (dst *SimpleProtoParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleProtoParams.Merge(dst, src) -} -func (m *SimpleProtoParams) XXX_Size() int { - return xxx_messageInfo_SimpleProtoParams.Size(m) -} -func (m *SimpleProtoParams) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleProtoParams.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleProtoParams proto.InternalMessageInfo - -func (m *SimpleProtoParams) GetReqSize() int32 { - if m != nil { - return m.ReqSize - } - return 0 -} - -func (m *SimpleProtoParams) GetRespSize() int32 { - if m != nil { - return m.RespSize - } - return 0 -} - -type ComplexProtoParams struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ComplexProtoParams) Reset() { *m = ComplexProtoParams{} } -func (m *ComplexProtoParams) String() string { return proto.CompactTextString(m) } -func (*ComplexProtoParams) ProtoMessage() {} -func (*ComplexProtoParams) Descriptor() ([]byte, []int) { - return fileDescriptor_payloads_3abc71de35f06c83, []int{2} -} -func (m *ComplexProtoParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ComplexProtoParams.Unmarshal(m, b) -} -func (m *ComplexProtoParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ComplexProtoParams.Marshal(b, m, deterministic) -} -func (dst *ComplexProtoParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_ComplexProtoParams.Merge(dst, src) -} -func (m *ComplexProtoParams) XXX_Size() int { - return xxx_messageInfo_ComplexProtoParams.Size(m) -} -func (m *ComplexProtoParams) XXX_DiscardUnknown() { - xxx_messageInfo_ComplexProtoParams.DiscardUnknown(m) -} - -var xxx_messageInfo_ComplexProtoParams proto.InternalMessageInfo - -type PayloadConfig struct { - // Types that are valid to be assigned to Payload: - // *PayloadConfig_BytebufParams - // *PayloadConfig_SimpleParams - // *PayloadConfig_ComplexParams - Payload isPayloadConfig_Payload `protobuf_oneof:"payload"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PayloadConfig) Reset() { *m = PayloadConfig{} } -func (m *PayloadConfig) String() string { return proto.CompactTextString(m) } -func (*PayloadConfig) ProtoMessage() {} -func (*PayloadConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_payloads_3abc71de35f06c83, []int{3} -} -func (m *PayloadConfig) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PayloadConfig.Unmarshal(m, b) -} -func (m *PayloadConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PayloadConfig.Marshal(b, m, deterministic) -} -func (dst *PayloadConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_PayloadConfig.Merge(dst, src) -} -func (m *PayloadConfig) XXX_Size() int { - return xxx_messageInfo_PayloadConfig.Size(m) -} -func (m *PayloadConfig) XXX_DiscardUnknown() { - xxx_messageInfo_PayloadConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_PayloadConfig proto.InternalMessageInfo - -type isPayloadConfig_Payload interface { - isPayloadConfig_Payload() -} - -type PayloadConfig_BytebufParams struct { - BytebufParams *ByteBufferParams `protobuf:"bytes,1,opt,name=bytebuf_params,json=bytebufParams,proto3,oneof"` -} -type PayloadConfig_SimpleParams struct { - SimpleParams *SimpleProtoParams `protobuf:"bytes,2,opt,name=simple_params,json=simpleParams,proto3,oneof"` -} -type PayloadConfig_ComplexParams struct { - ComplexParams *ComplexProtoParams `protobuf:"bytes,3,opt,name=complex_params,json=complexParams,proto3,oneof"` -} - -func (*PayloadConfig_BytebufParams) isPayloadConfig_Payload() {} -func (*PayloadConfig_SimpleParams) isPayloadConfig_Payload() {} -func (*PayloadConfig_ComplexParams) isPayloadConfig_Payload() {} - -func (m *PayloadConfig) GetPayload() isPayloadConfig_Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *PayloadConfig) GetBytebufParams() *ByteBufferParams { - if x, ok := m.GetPayload().(*PayloadConfig_BytebufParams); ok { - return x.BytebufParams - } - return nil -} - -func (m *PayloadConfig) GetSimpleParams() *SimpleProtoParams { - if x, ok := m.GetPayload().(*PayloadConfig_SimpleParams); ok { - return x.SimpleParams - } - return nil -} - -func (m *PayloadConfig) GetComplexParams() *ComplexProtoParams { - if x, ok := m.GetPayload().(*PayloadConfig_ComplexParams); ok { - return x.ComplexParams - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*PayloadConfig) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _PayloadConfig_OneofMarshaler, _PayloadConfig_OneofUnmarshaler, _PayloadConfig_OneofSizer, []interface{}{ - (*PayloadConfig_BytebufParams)(nil), - (*PayloadConfig_SimpleParams)(nil), - (*PayloadConfig_ComplexParams)(nil), - } -} - -func _PayloadConfig_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*PayloadConfig) - // payload - switch x := m.Payload.(type) { - case *PayloadConfig_BytebufParams: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.BytebufParams); err != nil { - return err - } - case *PayloadConfig_SimpleParams: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.SimpleParams); err != nil { - return err - } - case *PayloadConfig_ComplexParams: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ComplexParams); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("PayloadConfig.Payload has unexpected type %T", x) - } - return nil -} - -func _PayloadConfig_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*PayloadConfig) - switch tag { - case 1: // payload.bytebuf_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ByteBufferParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_BytebufParams{msg} - return true, err - case 2: // payload.simple_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(SimpleProtoParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_SimpleParams{msg} - return true, err - case 3: // payload.complex_params - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ComplexProtoParams) - err := b.DecodeMessage(msg) - m.Payload = &PayloadConfig_ComplexParams{msg} - return true, err - default: - return false, nil - } -} - -func _PayloadConfig_OneofSizer(msg proto.Message) (n int) { - m := msg.(*PayloadConfig) - // payload - switch x := m.Payload.(type) { - case *PayloadConfig_BytebufParams: - s := proto.Size(x.BytebufParams) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *PayloadConfig_SimpleParams: - s := proto.Size(x.SimpleParams) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *PayloadConfig_ComplexParams: - s := proto.Size(x.ComplexParams) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -func init() { - proto.RegisterType((*ByteBufferParams)(nil), "grpc.testing.ByteBufferParams") - proto.RegisterType((*SimpleProtoParams)(nil), "grpc.testing.SimpleProtoParams") - proto.RegisterType((*ComplexProtoParams)(nil), "grpc.testing.ComplexProtoParams") - proto.RegisterType((*PayloadConfig)(nil), "grpc.testing.PayloadConfig") -} - -func init() { proto.RegisterFile("payloads.proto", fileDescriptor_payloads_3abc71de35f06c83) } - -var fileDescriptor_payloads_3abc71de35f06c83 = []byte{ - // 254 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x48, 0xac, 0xcc, - 0xc9, 0x4f, 0x4c, 0x29, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x49, 0x2f, 0x2a, 0x48, - 0xd6, 0x2b, 0x49, 0x2d, 0x2e, 0xc9, 0xcc, 0x4b, 0x57, 0xf2, 0xe2, 0x12, 0x70, 0xaa, 0x2c, 0x49, - 0x75, 0x2a, 0x4d, 0x4b, 0x4b, 0x2d, 0x0a, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0x16, 0x92, 0xe4, 0xe2, - 0x28, 0x4a, 0x2d, 0x8c, 0x2f, 0xce, 0xac, 0x4a, 0x95, 0x60, 0x54, 0x60, 0xd4, 0x60, 0x0d, 0x62, - 0x2f, 0x4a, 0x2d, 0x0c, 0xce, 0xac, 0x4a, 0x15, 0x92, 0xe6, 0xe2, 0x2c, 0x4a, 0x2d, 0x2e, 0x80, - 0xc8, 0x31, 0x81, 0xe5, 0x38, 0x40, 0x02, 0x20, 0x49, 0x25, 0x6f, 0x2e, 0xc1, 0xe0, 0xcc, 0xdc, - 0x82, 0x9c, 0xd4, 0x00, 0x90, 0x45, 0x14, 0x1a, 0x26, 0xc2, 0x25, 0xe4, 0x9c, 0x0f, 0x32, 0xac, - 0x02, 0xc9, 0x34, 0xa5, 0x6f, 0x8c, 0x5c, 0xbc, 0x01, 0x10, 0xff, 0x38, 0xe7, 0xe7, 0xa5, 0x65, - 0xa6, 0x0b, 0xb9, 0x73, 0xf1, 0x25, 0x55, 0x96, 0xa4, 0x26, 0x95, 0xa6, 0xc5, 0x17, 0x80, 0xd5, - 0x80, 0x6d, 0xe1, 0x36, 0x92, 0xd3, 0x43, 0xf6, 0xa7, 0x1e, 0xba, 0x27, 0x3d, 0x18, 0x82, 0x78, - 0xa1, 0xfa, 0xa0, 0x0e, 0x75, 0xe3, 0xe2, 0x2d, 0x06, 0xbb, 0x1e, 0x66, 0x0e, 0x13, 0xd8, 0x1c, - 0x79, 0x54, 0x73, 0x30, 0x3c, 0xe8, 0xc1, 0x10, 0xc4, 0x03, 0xd1, 0x07, 0x35, 0xc7, 0x93, 0x8b, - 0x2f, 0x19, 0xe2, 0x70, 0x98, 0x41, 0xcc, 0x60, 0x83, 0x14, 0x50, 0x0d, 0xc2, 0xf4, 0x1c, 0xc8, - 0x49, 0x50, 0x9d, 0x10, 0x01, 0x27, 0x4e, 0x2e, 0x76, 0x68, 0xe4, 0x25, 0xb1, 0x81, 0x23, 0xcf, - 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xb0, 0x8c, 0x18, 0x4e, 0xce, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto b/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto deleted file mode 100755 index 5d4871f..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/payloads.proto +++ /dev/null @@ -1,40 +0,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. - -syntax = "proto3"; - -package grpc.testing; - -message ByteBufferParams { - int32 req_size = 1; - int32 resp_size = 2; -} - -message SimpleProtoParams { - int32 req_size = 1; - int32 resp_size = 2; -} - -message ComplexProtoParams { - // TODO (vpai): Fill this in once the details of complex, representative - // protos are decided -} - -message PayloadConfig { - oneof payload { - ByteBufferParams bytebuf_params = 1; - SimpleProtoParams simple_params = 2; - ComplexProtoParams complex_params = 3; - } -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go b/examples/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go deleted file mode 100755 index 5156ae7..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/services.pb.go +++ /dev/null @@ -1,448 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: services.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// BenchmarkServiceClient is the client API for BenchmarkService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type BenchmarkServiceClient interface { - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by one response. - // The server returns the client payload as-is. - StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) -} - -type benchmarkServiceClient struct { - cc *grpc.ClientConn -} - -func NewBenchmarkServiceClient(cc *grpc.ClientConn) BenchmarkServiceClient { - return &benchmarkServiceClient{cc} -} - -func (c *benchmarkServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.BenchmarkService/UnaryCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *benchmarkServiceClient) StreamingCall(ctx context.Context, opts ...grpc.CallOption) (BenchmarkService_StreamingCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_BenchmarkService_serviceDesc.Streams[0], "/grpc.testing.BenchmarkService/StreamingCall", opts...) - if err != nil { - return nil, err - } - x := &benchmarkServiceStreamingCallClient{stream} - return x, nil -} - -type BenchmarkService_StreamingCallClient interface { - Send(*SimpleRequest) error - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type benchmarkServiceStreamingCallClient struct { - grpc.ClientStream -} - -func (x *benchmarkServiceStreamingCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *benchmarkServiceStreamingCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// BenchmarkServiceServer is the server API for BenchmarkService service. -type BenchmarkServiceServer interface { - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by one response. - // The server returns the client payload as-is. - StreamingCall(BenchmarkService_StreamingCallServer) error -} - -func RegisterBenchmarkServiceServer(s *grpc.Server, srv BenchmarkServiceServer) { - s.RegisterService(&_BenchmarkService_serviceDesc, srv) -} - -func _BenchmarkService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BenchmarkServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.BenchmarkService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BenchmarkServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BenchmarkService_StreamingCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(BenchmarkServiceServer).StreamingCall(&benchmarkServiceStreamingCallServer{stream}) -} - -type BenchmarkService_StreamingCallServer interface { - Send(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type benchmarkServiceStreamingCallServer struct { - grpc.ServerStream -} - -func (x *benchmarkServiceStreamingCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *benchmarkServiceStreamingCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _BenchmarkService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.BenchmarkService", - HandlerType: (*BenchmarkServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: _BenchmarkService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingCall", - Handler: _BenchmarkService_StreamingCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "services.proto", -} - -// WorkerServiceClient is the client API for WorkerService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type WorkerServiceClient interface { - // 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. - RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) - // 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. - RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) - // Just return the core count - unary call - CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) - // Quit this worker - QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) -} - -type workerServiceClient struct { - cc *grpc.ClientConn -} - -func NewWorkerServiceClient(cc *grpc.ClientConn) WorkerServiceClient { - return &workerServiceClient{cc} -} - -func (c *workerServiceClient) RunServer(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunServerClient, error) { - stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[0], "/grpc.testing.WorkerService/RunServer", opts...) - if err != nil { - return nil, err - } - x := &workerServiceRunServerClient{stream} - return x, nil -} - -type WorkerService_RunServerClient interface { - Send(*ServerArgs) error - Recv() (*ServerStatus, error) - grpc.ClientStream -} - -type workerServiceRunServerClient struct { - grpc.ClientStream -} - -func (x *workerServiceRunServerClient) Send(m *ServerArgs) error { - return x.ClientStream.SendMsg(m) -} - -func (x *workerServiceRunServerClient) Recv() (*ServerStatus, error) { - m := new(ServerStatus) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *workerServiceClient) RunClient(ctx context.Context, opts ...grpc.CallOption) (WorkerService_RunClientClient, error) { - stream, err := c.cc.NewStream(ctx, &_WorkerService_serviceDesc.Streams[1], "/grpc.testing.WorkerService/RunClient", opts...) - if err != nil { - return nil, err - } - x := &workerServiceRunClientClient{stream} - return x, nil -} - -type WorkerService_RunClientClient interface { - Send(*ClientArgs) error - Recv() (*ClientStatus, error) - grpc.ClientStream -} - -type workerServiceRunClientClient struct { - grpc.ClientStream -} - -func (x *workerServiceRunClientClient) Send(m *ClientArgs) error { - return x.ClientStream.SendMsg(m) -} - -func (x *workerServiceRunClientClient) Recv() (*ClientStatus, error) { - m := new(ClientStatus) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *workerServiceClient) CoreCount(ctx context.Context, in *CoreRequest, opts ...grpc.CallOption) (*CoreResponse, error) { - out := new(CoreResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/CoreCount", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *workerServiceClient) QuitWorker(ctx context.Context, in *Void, opts ...grpc.CallOption) (*Void, error) { - out := new(Void) - err := c.cc.Invoke(ctx, "/grpc.testing.WorkerService/QuitWorker", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// WorkerServiceServer is the server API for WorkerService service. -type WorkerServiceServer interface { - // 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. - RunServer(WorkerService_RunServerServer) error - // 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. - RunClient(WorkerService_RunClientServer) error - // Just return the core count - unary call - CoreCount(context.Context, *CoreRequest) (*CoreResponse, error) - // Quit this worker - QuitWorker(context.Context, *Void) (*Void, error) -} - -func RegisterWorkerServiceServer(s *grpc.Server, srv WorkerServiceServer) { - s.RegisterService(&_WorkerService_serviceDesc, srv) -} - -func _WorkerService_RunServer_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(WorkerServiceServer).RunServer(&workerServiceRunServerServer{stream}) -} - -type WorkerService_RunServerServer interface { - Send(*ServerStatus) error - Recv() (*ServerArgs, error) - grpc.ServerStream -} - -type workerServiceRunServerServer struct { - grpc.ServerStream -} - -func (x *workerServiceRunServerServer) Send(m *ServerStatus) error { - return x.ServerStream.SendMsg(m) -} - -func (x *workerServiceRunServerServer) Recv() (*ServerArgs, error) { - m := new(ServerArgs) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _WorkerService_RunClient_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(WorkerServiceServer).RunClient(&workerServiceRunClientServer{stream}) -} - -type WorkerService_RunClientServer interface { - Send(*ClientStatus) error - Recv() (*ClientArgs, error) - grpc.ServerStream -} - -type workerServiceRunClientServer struct { - grpc.ServerStream -} - -func (x *workerServiceRunClientServer) Send(m *ClientStatus) error { - return x.ServerStream.SendMsg(m) -} - -func (x *workerServiceRunClientServer) Recv() (*ClientArgs, error) { - m := new(ClientArgs) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _WorkerService_CoreCount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CoreRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WorkerServiceServer).CoreCount(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.WorkerService/CoreCount", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WorkerServiceServer).CoreCount(ctx, req.(*CoreRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _WorkerService_QuitWorker_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Void) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WorkerServiceServer).QuitWorker(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.WorkerService/QuitWorker", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WorkerServiceServer).QuitWorker(ctx, req.(*Void)) - } - return interceptor(ctx, in, info, handler) -} - -var _WorkerService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.WorkerService", - HandlerType: (*WorkerServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CoreCount", - Handler: _WorkerService_CoreCount_Handler, - }, - { - MethodName: "QuitWorker", - Handler: _WorkerService_QuitWorker_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "RunServer", - Handler: _WorkerService_RunServer_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "RunClient", - Handler: _WorkerService_RunClient_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "services.proto", -} - -func init() { proto.RegisterFile("services.proto", fileDescriptor_services_bf68f4d7cbd0e0a1) } - -var fileDescriptor_services_bf68f4d7cbd0e0a1 = []byte{ - // 255 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x91, 0xc1, 0x4a, 0xc4, 0x30, - 0x10, 0x86, 0xa9, 0x07, 0xa1, 0xc1, 0x2e, 0x92, 0x93, 0x46, 0x1f, 0xc0, 0x53, 0x91, 0xd5, 0x17, - 0x70, 0x8b, 0x1e, 0x05, 0xb7, 0xa8, 0xe7, 0x58, 0x87, 0x1a, 0x36, 0xcd, 0xd4, 0x99, 0x89, 0xe0, - 0x93, 0xf8, 0x0e, 0x3e, 0xa5, 0xec, 0x66, 0x57, 0xd6, 0x92, 0x9b, 0xc7, 0xf9, 0xbf, 0xe1, 0x23, - 0x7f, 0x46, 0xcd, 0x18, 0xe8, 0xc3, 0x75, 0xc0, 0xf5, 0x48, 0x28, 0xa8, 0x8f, 0x7a, 0x1a, 0xbb, - 0x5a, 0x80, 0xc5, 0x85, 0xde, 0xcc, 0x06, 0x60, 0xb6, 0xfd, 0x8e, 0x9a, 0xaa, 0xc3, 0x20, 0x84, - 0x3e, 0x8d, 0xf3, 0xef, 0x42, 0x1d, 0x2f, 0x20, 0x74, 0x6f, 0x83, 0xa5, 0x55, 0x9b, 0x44, 0xfa, - 0x4e, 0x95, 0x8f, 0xc1, 0xd2, 0x67, 0x63, 0xbd, 0xd7, 0x67, 0xf5, 0xbe, 0xaf, 0x6e, 0xdd, 0x30, - 0x7a, 0x58, 0xc2, 0x7b, 0x04, 0x16, 0x73, 0x9e, 0x87, 0x3c, 0x62, 0x60, 0xd0, 0xf7, 0xaa, 0x6a, - 0x85, 0xc0, 0x0e, 0x2e, 0xf4, 0xff, 0x74, 0x5d, 0x14, 0x97, 0xc5, 0xfc, 0xeb, 0x40, 0x55, 0xcf, - 0x48, 0x2b, 0xa0, 0xdd, 0x4b, 0x6f, 0x55, 0xb9, 0x8c, 0x61, 0x3d, 0x01, 0xe9, 0x93, 0x89, 0x60, - 0x93, 0xde, 0x50, 0xcf, 0xc6, 0xe4, 0x48, 0x2b, 0x56, 0x22, 0xaf, 0xc5, 0x5b, 0x4d, 0xe3, 0x1d, - 0x04, 0x99, 0x6a, 0x52, 0x9a, 0xd3, 0x24, 0xb2, 0xa7, 0x59, 0xa8, 0xb2, 0x41, 0x82, 0x06, 0x63, - 0x10, 0x7d, 0x3a, 0x59, 0x46, 0xfa, 0x6d, 0x6a, 0x72, 0x68, 0xfb, 0x67, 0xd7, 0x4a, 0x3d, 0x44, - 0x27, 0xa9, 0xa6, 0xd6, 0x7f, 0x37, 0x9f, 0xd0, 0xbd, 0x9a, 0x4c, 0xf6, 0x72, 0xb8, 0xb9, 0xe6, - 0xd5, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3b, 0x84, 0x02, 0xe3, 0x0c, 0x02, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/services.proto b/examples/google.golang.org/grpc/benchmark/grpc_testing/services.proto deleted file mode 100755 index f4e7907..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/services.proto +++ /dev/null @@ -1,56 +0,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. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto3"; - -import "messages.proto"; -import "control.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); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc StreamingCall(stream SimpleRequest) returns (stream SimpleResponse); -} - -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/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go b/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go deleted file mode 100755 index abc2aea..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.pb.go +++ /dev/null @@ -1,302 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: stats.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ServerStats struct { - // wall clock time change in seconds since last reset - TimeElapsed float64 `protobuf:"fixed64,1,opt,name=time_elapsed,json=timeElapsed,proto3" json:"time_elapsed,omitempty"` - // change in user time (in seconds) used by the server since last reset - TimeUser float64 `protobuf:"fixed64,2,opt,name=time_user,json=timeUser,proto3" json:"time_user,omitempty"` - // change in server time (in seconds) used by the server process and all - // threads since last reset - TimeSystem float64 `protobuf:"fixed64,3,opt,name=time_system,json=timeSystem,proto3" json:"time_system,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerStats) Reset() { *m = ServerStats{} } -func (m *ServerStats) String() string { return proto.CompactTextString(m) } -func (*ServerStats) ProtoMessage() {} -func (*ServerStats) Descriptor() ([]byte, []int) { - return fileDescriptor_stats_8ba831c0cb3c3440, []int{0} -} -func (m *ServerStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerStats.Unmarshal(m, b) -} -func (m *ServerStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerStats.Marshal(b, m, deterministic) -} -func (dst *ServerStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerStats.Merge(dst, src) -} -func (m *ServerStats) XXX_Size() int { - return xxx_messageInfo_ServerStats.Size(m) -} -func (m *ServerStats) XXX_DiscardUnknown() { - xxx_messageInfo_ServerStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerStats proto.InternalMessageInfo - -func (m *ServerStats) GetTimeElapsed() float64 { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -func (m *ServerStats) GetTimeUser() float64 { - if m != nil { - return m.TimeUser - } - return 0 -} - -func (m *ServerStats) GetTimeSystem() float64 { - if m != nil { - return m.TimeSystem - } - return 0 -} - -// Histogram params based on grpc/support/histogram.c -type HistogramParams struct { - Resolution float64 `protobuf:"fixed64,1,opt,name=resolution,proto3" json:"resolution,omitempty"` - MaxPossible float64 `protobuf:"fixed64,2,opt,name=max_possible,json=maxPossible,proto3" json:"max_possible,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HistogramParams) Reset() { *m = HistogramParams{} } -func (m *HistogramParams) String() string { return proto.CompactTextString(m) } -func (*HistogramParams) ProtoMessage() {} -func (*HistogramParams) Descriptor() ([]byte, []int) { - return fileDescriptor_stats_8ba831c0cb3c3440, []int{1} -} -func (m *HistogramParams) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HistogramParams.Unmarshal(m, b) -} -func (m *HistogramParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HistogramParams.Marshal(b, m, deterministic) -} -func (dst *HistogramParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_HistogramParams.Merge(dst, src) -} -func (m *HistogramParams) XXX_Size() int { - return xxx_messageInfo_HistogramParams.Size(m) -} -func (m *HistogramParams) XXX_DiscardUnknown() { - xxx_messageInfo_HistogramParams.DiscardUnknown(m) -} - -var xxx_messageInfo_HistogramParams proto.InternalMessageInfo - -func (m *HistogramParams) GetResolution() float64 { - if m != nil { - return m.Resolution - } - return 0 -} - -func (m *HistogramParams) GetMaxPossible() float64 { - if m != nil { - return m.MaxPossible - } - return 0 -} - -// Histogram data based on grpc/support/histogram.c -type HistogramData struct { - Bucket []uint32 `protobuf:"varint,1,rep,packed,name=bucket,proto3" json:"bucket,omitempty"` - MinSeen float64 `protobuf:"fixed64,2,opt,name=min_seen,json=minSeen,proto3" json:"min_seen,omitempty"` - MaxSeen float64 `protobuf:"fixed64,3,opt,name=max_seen,json=maxSeen,proto3" json:"max_seen,omitempty"` - Sum float64 `protobuf:"fixed64,4,opt,name=sum,proto3" json:"sum,omitempty"` - SumOfSquares float64 `protobuf:"fixed64,5,opt,name=sum_of_squares,json=sumOfSquares,proto3" json:"sum_of_squares,omitempty"` - Count float64 `protobuf:"fixed64,6,opt,name=count,proto3" json:"count,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HistogramData) Reset() { *m = HistogramData{} } -func (m *HistogramData) String() string { return proto.CompactTextString(m) } -func (*HistogramData) ProtoMessage() {} -func (*HistogramData) Descriptor() ([]byte, []int) { - return fileDescriptor_stats_8ba831c0cb3c3440, []int{2} -} -func (m *HistogramData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HistogramData.Unmarshal(m, b) -} -func (m *HistogramData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HistogramData.Marshal(b, m, deterministic) -} -func (dst *HistogramData) XXX_Merge(src proto.Message) { - xxx_messageInfo_HistogramData.Merge(dst, src) -} -func (m *HistogramData) XXX_Size() int { - return xxx_messageInfo_HistogramData.Size(m) -} -func (m *HistogramData) XXX_DiscardUnknown() { - xxx_messageInfo_HistogramData.DiscardUnknown(m) -} - -var xxx_messageInfo_HistogramData proto.InternalMessageInfo - -func (m *HistogramData) GetBucket() []uint32 { - if m != nil { - return m.Bucket - } - return nil -} - -func (m *HistogramData) GetMinSeen() float64 { - if m != nil { - return m.MinSeen - } - return 0 -} - -func (m *HistogramData) GetMaxSeen() float64 { - if m != nil { - return m.MaxSeen - } - return 0 -} - -func (m *HistogramData) GetSum() float64 { - if m != nil { - return m.Sum - } - return 0 -} - -func (m *HistogramData) GetSumOfSquares() float64 { - if m != nil { - return m.SumOfSquares - } - return 0 -} - -func (m *HistogramData) GetCount() float64 { - if m != nil { - return m.Count - } - return 0 -} - -type ClientStats struct { - // Latency histogram. Data points are in nanoseconds. - Latencies *HistogramData `protobuf:"bytes,1,opt,name=latencies,proto3" json:"latencies,omitempty"` - // See ServerStats for details. - TimeElapsed float64 `protobuf:"fixed64,2,opt,name=time_elapsed,json=timeElapsed,proto3" json:"time_elapsed,omitempty"` - TimeUser float64 `protobuf:"fixed64,3,opt,name=time_user,json=timeUser,proto3" json:"time_user,omitempty"` - TimeSystem float64 `protobuf:"fixed64,4,opt,name=time_system,json=timeSystem,proto3" json:"time_system,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { - return fileDescriptor_stats_8ba831c0cb3c3440, []int{3} -} -func (m *ClientStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStats.Unmarshal(m, b) -} -func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) -} -func (dst *ClientStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStats.Merge(dst, src) -} -func (m *ClientStats) XXX_Size() int { - return xxx_messageInfo_ClientStats.Size(m) -} -func (m *ClientStats) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStats proto.InternalMessageInfo - -func (m *ClientStats) GetLatencies() *HistogramData { - if m != nil { - return m.Latencies - } - return nil -} - -func (m *ClientStats) GetTimeElapsed() float64 { - if m != nil { - return m.TimeElapsed - } - return 0 -} - -func (m *ClientStats) GetTimeUser() float64 { - if m != nil { - return m.TimeUser - } - return 0 -} - -func (m *ClientStats) GetTimeSystem() float64 { - if m != nil { - return m.TimeSystem - } - return 0 -} - -func init() { - proto.RegisterType((*ServerStats)(nil), "grpc.testing.ServerStats") - proto.RegisterType((*HistogramParams)(nil), "grpc.testing.HistogramParams") - proto.RegisterType((*HistogramData)(nil), "grpc.testing.HistogramData") - proto.RegisterType((*ClientStats)(nil), "grpc.testing.ClientStats") -} - -func init() { proto.RegisterFile("stats.proto", fileDescriptor_stats_8ba831c0cb3c3440) } - -var fileDescriptor_stats_8ba831c0cb3c3440 = []byte{ - // 341 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x92, 0xc1, 0x4a, 0xeb, 0x40, - 0x14, 0x86, 0x49, 0xd3, 0xf6, 0xb6, 0x27, 0xed, 0xbd, 0x97, 0x41, 0x24, 0x52, 0xd0, 0x1a, 0x5c, - 0x74, 0x95, 0x85, 0xae, 0x5c, 0xab, 0xe0, 0xce, 0xd2, 0xe8, 0x3a, 0x4c, 0xe3, 0x69, 0x19, 0xcc, - 0xcc, 0xc4, 0x39, 0x33, 0x12, 0x1f, 0x49, 0x7c, 0x49, 0xc9, 0x24, 0x68, 0x55, 0xd0, 0x5d, 0xe6, - 0xfb, 0x7e, 0xe6, 0xe4, 0xe4, 0x0f, 0x44, 0x64, 0xb9, 0xa5, 0xb4, 0x32, 0xda, 0x6a, 0x36, 0xd9, - 0x9a, 0xaa, 0x48, 0x2d, 0x92, 0x15, 0x6a, 0x9b, 0x28, 0x88, 0x32, 0x34, 0x4f, 0x68, 0xb2, 0x26, - 0xc2, 0x8e, 0x61, 0x62, 0x85, 0xc4, 0x1c, 0x4b, 0x5e, 0x11, 0xde, 0xc7, 0xc1, 0x3c, 0x58, 0x04, - 0xab, 0xa8, 0x61, 0x57, 0x2d, 0x62, 0x33, 0x18, 0xfb, 0x88, 0x23, 0x34, 0x71, 0xcf, 0xfb, 0x51, - 0x03, 0xee, 0x08, 0x0d, 0x3b, 0x02, 0x9f, 0xcd, 0xe9, 0x99, 0x2c, 0xca, 0x38, 0xf4, 0x1a, 0x1a, - 0x94, 0x79, 0x92, 0xdc, 0xc2, 0xbf, 0x6b, 0x41, 0x56, 0x6f, 0x0d, 0x97, 0x4b, 0x6e, 0xb8, 0x24, - 0x76, 0x08, 0x60, 0x90, 0x74, 0xe9, 0xac, 0xd0, 0xaa, 0x9b, 0xb8, 0x43, 0x9a, 0x77, 0x92, 0xbc, - 0xce, 0x2b, 0x4d, 0x24, 0xd6, 0x25, 0x76, 0x33, 0x23, 0xc9, 0xeb, 0x65, 0x87, 0x92, 0xd7, 0x00, - 0xa6, 0xef, 0xd7, 0x5e, 0x72, 0xcb, 0xd9, 0x3e, 0x0c, 0xd7, 0xae, 0x78, 0x40, 0x1b, 0x07, 0xf3, - 0x70, 0x31, 0x5d, 0x75, 0x27, 0x76, 0x00, 0x23, 0x29, 0x54, 0x4e, 0x88, 0xaa, 0xbb, 0xe8, 0x8f, - 0x14, 0x2a, 0x43, 0x54, 0x5e, 0xf1, 0xba, 0x55, 0x61, 0xa7, 0x78, 0xed, 0xd5, 0x7f, 0x08, 0xc9, - 0xc9, 0xb8, 0xef, 0x69, 0xf3, 0xc8, 0x4e, 0xe0, 0x2f, 0x39, 0x99, 0xeb, 0x4d, 0x4e, 0x8f, 0x8e, - 0x1b, 0xa4, 0x78, 0xe0, 0xe5, 0x84, 0x9c, 0xbc, 0xd9, 0x64, 0x2d, 0x63, 0x7b, 0x30, 0x28, 0xb4, - 0x53, 0x36, 0x1e, 0x7a, 0xd9, 0x1e, 0x92, 0x97, 0x00, 0xa2, 0x8b, 0x52, 0xa0, 0xb2, 0xed, 0x47, - 0x3f, 0x87, 0x71, 0xc9, 0x2d, 0xaa, 0x42, 0x20, 0xf9, 0xfd, 0xa3, 0xd3, 0x59, 0xba, 0xdb, 0x52, - 0xfa, 0x69, 0xb7, 0xd5, 0x47, 0xfa, 0x5b, 0x5f, 0xbd, 0x5f, 0xfa, 0x0a, 0x7f, 0xee, 0xab, 0xff, - 0xb5, 0xaf, 0xf5, 0xd0, 0xff, 0x34, 0x67, 0x6f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xea, 0x75, 0x34, - 0x90, 0x43, 0x02, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.proto b/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.proto deleted file mode 100755 index baf3610..0000000 --- a/examples/google.golang.org/grpc/benchmark/grpc_testing/stats.proto +++ /dev/null @@ -1,55 +0,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. - -syntax = "proto3"; - -package grpc.testing; - -message ServerStats { - // wall clock time change in seconds since last reset - double time_elapsed = 1; - - // change in user time (in seconds) used by the server since last reset - double time_user = 2; - - // change in server time (in seconds) used by the server process and all - // threads since last reset - double time_system = 3; -} - -// Histogram params based on grpc/support/histogram.c -message HistogramParams { - double resolution = 1; // first bucket is [0, 1 + resolution) - double max_possible = 2; // use enough buckets to allow this value -} - -// Histogram data based on grpc/support/histogram.c -message HistogramData { - repeated uint32 bucket = 1; - double min_seen = 2; - double max_seen = 3; - double sum = 4; - double sum_of_squares = 5; - double count = 6; -} - -message ClientStats { - // Latency histogram. Data points are in nanoseconds. - HistogramData latencies = 1; - - // See ServerStats for details. - double time_elapsed = 2; - double time_user = 3; - double time_system = 4; -} diff --git a/examples/google.golang.org/grpc/benchmark/latency/latency.go b/examples/google.golang.org/grpc/benchmark/latency/latency.go deleted file mode 100755 index 5839a5c..0000000 --- a/examples/google.golang.org/grpc/benchmark/latency/latency.go +++ /dev/null @@ -1,316 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package latency provides wrappers for net.Conn, net.Listener, and -// net.Dialers, designed to interoperate to inject real-world latency into -// network connections. -package latency - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "net" - "time" - - "golang.org/x/net/context" -) - -// Dialer is a function matching the signature of net.Dial. -type Dialer func(network, address string) (net.Conn, error) - -// TimeoutDialer is a function matching the signature of net.DialTimeout. -type TimeoutDialer func(network, address string, timeout time.Duration) (net.Conn, error) - -// ContextDialer is a function matching the signature of -// net.Dialer.DialContext. -type ContextDialer func(ctx context.Context, network, address string) (net.Conn, error) - -// Network represents a network with the given bandwidth, latency, and MTU -// (Maximum Transmission Unit) configuration, and can produce wrappers of -// net.Listeners, net.Conn, and various forms of dialing functions. The -// Listeners and Dialers/Conns on both sides of connections must come from this -// package, but need not be created from the same Network. Latency is computed -// when sending (in Write), and is injected when receiving (in Read). This -// allows senders' Write calls to be non-blocking, as in real-world -// applications. -// -// Note: Latency is injected by the sender specifying the absolute time data -// should be available, and the reader delaying until that time arrives to -// provide the data. This package attempts to counter-act the effects of clock -// drift and existing network latency by measuring the delay between the -// sender's transmission time and the receiver's reception time during startup. -// No attempt is made to measure the existing bandwidth of the connection. -type Network struct { - Kbps int // Kilobits per second; if non-positive, infinite - Latency time.Duration // One-way latency (sending); if non-positive, no delay - MTU int // Bytes per packet; if non-positive, infinite -} - -var ( - //Local simulates local network. - Local = Network{0, 0, 0} - //LAN simulates local area network network. - LAN = Network{100 * 1024, 2 * time.Millisecond, 1500} - //WAN simulates wide area network. - WAN = Network{20 * 1024, 30 * time.Millisecond, 1500} - //Longhaul simulates bad network. - Longhaul = Network{1000 * 1024, 200 * time.Millisecond, 9000} -) - -// Conn returns a net.Conn that wraps c and injects n's latency into that -// connection. This function also imposes latency for connection creation. -// If n's Latency is lower than the measured latency in c, an error is -// returned. -func (n *Network) Conn(c net.Conn) (net.Conn, error) { - start := now() - nc := &conn{Conn: c, network: n, readBuf: new(bytes.Buffer)} - if err := nc.sync(); err != nil { - return nil, err - } - sleep(start.Add(nc.delay).Sub(now())) - return nc, nil -} - -type conn struct { - net.Conn - network *Network - - readBuf *bytes.Buffer // one packet worth of data received - lastSendEnd time.Time // time the previous Write should be fully on the wire - delay time.Duration // desired latency - measured latency -} - -// header is sent before all data transmitted by the application. -type header struct { - ReadTime int64 // Time the reader is allowed to read this packet (UnixNano) - Sz int32 // Size of the data in the packet -} - -func (c *conn) Write(p []byte) (n int, err error) { - tNow := now() - if c.lastSendEnd.Before(tNow) { - c.lastSendEnd = tNow - } - for len(p) > 0 { - pkt := p - if c.network.MTU > 0 && len(pkt) > c.network.MTU { - pkt = pkt[:c.network.MTU] - p = p[c.network.MTU:] - } else { - p = nil - } - if c.network.Kbps > 0 { - if congestion := c.lastSendEnd.Sub(tNow) - c.delay; congestion > 0 { - // The network is full; sleep until this packet can be sent. - sleep(congestion) - tNow = tNow.Add(congestion) - } - } - c.lastSendEnd = c.lastSendEnd.Add(c.network.pktTime(len(pkt))) - hdr := header{ReadTime: c.lastSendEnd.Add(c.delay).UnixNano(), Sz: int32(len(pkt))} - if err := binary.Write(c.Conn, binary.BigEndian, hdr); err != nil { - return n, err - } - x, err := c.Conn.Write(pkt) - n += x - if err != nil { - return n, err - } - } - return n, nil -} - -func (c *conn) Read(p []byte) (n int, err error) { - if c.readBuf.Len() == 0 { - var hdr header - if err := binary.Read(c.Conn, binary.BigEndian, &hdr); err != nil { - return 0, err - } - defer func() { sleep(time.Unix(0, hdr.ReadTime).Sub(now())) }() - - if _, err := io.CopyN(c.readBuf, c.Conn, int64(hdr.Sz)); err != nil { - return 0, err - } - } - // Read from readBuf. - return c.readBuf.Read(p) -} - -// sync does a handshake and then measures the latency on the network in -// coordination with the other side. -func (c *conn) sync() error { - const ( - pingMsg = "syncPing" - warmup = 10 // minimum number of iterations to measure latency - giveUp = 50 // maximum number of iterations to measure latency - accuracy = time.Millisecond // req'd accuracy to stop early - goodRun = 3 // stop early if latency within accuracy this many times - ) - - type syncMsg struct { - SendT int64 // Time sent. If zero, stop. - RecvT int64 // Time received. If zero, fill in and respond. - } - - // A trivial handshake - if err := binary.Write(c.Conn, binary.BigEndian, []byte(pingMsg)); err != nil { - return err - } - var ping [8]byte - if err := binary.Read(c.Conn, binary.BigEndian, &ping); err != nil { - return err - } else if string(ping[:]) != pingMsg { - return fmt.Errorf("malformed handshake message: %v (want %q)", ping, pingMsg) - } - - // Both sides are alive and syncing. Calculate network delay / clock skew. - att := 0 - good := 0 - var latency time.Duration - localDone, remoteDone := false, false - send := true - for !localDone || !remoteDone { - if send { - if err := binary.Write(c.Conn, binary.BigEndian, syncMsg{SendT: now().UnixNano()}); err != nil { - return err - } - att++ - send = false - } - - // Block until we get a syncMsg - m := syncMsg{} - if err := binary.Read(c.Conn, binary.BigEndian, &m); err != nil { - return err - } - - if m.RecvT == 0 { - // Message initiated from other side. - if m.SendT == 0 { - remoteDone = true - continue - } - // Send response. - m.RecvT = now().UnixNano() - if err := binary.Write(c.Conn, binary.BigEndian, m); err != nil { - return err - } - continue - } - - lag := time.Duration(m.RecvT - m.SendT) - latency += lag - avgLatency := latency / time.Duration(att) - if e := lag - avgLatency; e > -accuracy && e < accuracy { - good++ - } else { - good = 0 - } - if att < giveUp && (att < warmup || good < goodRun) { - send = true - continue - } - localDone = true - latency = avgLatency - // Tell the other side we're done. - if err := binary.Write(c.Conn, binary.BigEndian, syncMsg{}); err != nil { - return err - } - } - if c.network.Latency <= 0 { - return nil - } - c.delay = c.network.Latency - latency - if c.delay < 0 { - return fmt.Errorf("measured network latency (%v) higher than desired latency (%v)", latency, c.network.Latency) - } - return nil -} - -// Listener returns a net.Listener that wraps l and injects n's latency in its -// connections. -func (n *Network) Listener(l net.Listener) net.Listener { - return &listener{Listener: l, network: n} -} - -type listener struct { - net.Listener - network *Network -} - -func (l *listener) Accept() (net.Conn, error) { - c, err := l.Listener.Accept() - if err != nil { - return nil, err - } - return l.network.Conn(c) -} - -// Dialer returns a Dialer that wraps d and injects n's latency in its -// connections. n's Latency is also injected to the connection's creation. -func (n *Network) Dialer(d Dialer) Dialer { - return func(network, address string) (net.Conn, error) { - conn, err := d(network, address) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// TimeoutDialer returns a TimeoutDialer that wraps d and injects n's latency -// in its connections. n's Latency is also injected to the connection's -// creation. -func (n *Network) TimeoutDialer(d TimeoutDialer) TimeoutDialer { - return func(network, address string, timeout time.Duration) (net.Conn, error) { - conn, err := d(network, address, timeout) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// ContextDialer returns a ContextDialer that wraps d and injects n's latency -// in its connections. n's Latency is also injected to the connection's -// creation. -func (n *Network) ContextDialer(d ContextDialer) ContextDialer { - return func(ctx context.Context, network, address string) (net.Conn, error) { - conn, err := d(ctx, network, address) - if err != nil { - return nil, err - } - return n.Conn(conn) - } -} - -// pktTime returns the time it takes to transmit one packet of data of size b -// in bytes. -func (n *Network) pktTime(b int) time.Duration { - if n.Kbps <= 0 { - return time.Duration(0) - } - return time.Duration(b) * time.Second / time.Duration(n.Kbps*(1024/8)) -} - -// Wrappers for testing - -var now = time.Now -var sleep = time.Sleep diff --git a/examples/google.golang.org/grpc/benchmark/latency/latency_test.go b/examples/google.golang.org/grpc/benchmark/latency/latency_test.go deleted file mode 100755 index ab2625b..0000000 --- a/examples/google.golang.org/grpc/benchmark/latency/latency_test.go +++ /dev/null @@ -1,353 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package latency - -import ( - "bytes" - "fmt" - "net" - "reflect" - "sync" - "testing" - "time" -) - -// bufConn is a net.Conn implemented by a bytes.Buffer (which is a ReadWriter). -type bufConn struct { - *bytes.Buffer -} - -func (bufConn) Close() error { panic("unimplemented") } -func (bufConn) LocalAddr() net.Addr { panic("unimplemented") } -func (bufConn) RemoteAddr() net.Addr { panic("unimplemented") } -func (bufConn) SetDeadline(t time.Time) error { panic("unimplemneted") } -func (bufConn) SetReadDeadline(t time.Time) error { panic("unimplemneted") } -func (bufConn) SetWriteDeadline(t time.Time) error { panic("unimplemneted") } - -func restoreHooks() func() { - s := sleep - n := now - return func() { - sleep = s - now = n - } -} - -func TestConn(t *testing.T) { - defer restoreHooks()() - - // Constant time. - now = func() time.Time { return time.Unix(123, 456) } - - // Capture sleep times for checking later. - var sleepTimes []time.Duration - sleep = func(t time.Duration) { sleepTimes = append(sleepTimes, t) } - - wantSleeps := func(want ...time.Duration) { - if !reflect.DeepEqual(want, sleepTimes) { - t.Fatalf("sleepTimes = %v; want %v", sleepTimes, want) - } - sleepTimes = nil - } - - // Use a fairly high latency to cause a large BDP and avoid sleeps while - // writing due to simulation of full buffers. - latency := 1 * time.Second - c, err := (&Network{Kbps: 1, Latency: latency, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - wantSleeps(latency) // Connection creation delay. - - // 1 kbps = 128 Bps. Divides evenly by 1 second using nanos. - byteLatency := time.Duration(time.Second / 128) - - write := func(b []byte) { - n, err := c.Write(b) - if n != len(b) || err != nil { - t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b)) - } - } - - write([]byte{1, 2, 3, 4, 5}) // One full packet - pkt1Time := latency + byteLatency*5 - write([]byte{6}) // One partial packet - pkt2Time := pkt1Time + byteLatency - write([]byte{7, 8, 9, 10, 11, 12, 13}) // Two packets - pkt3Time := pkt2Time + byteLatency*5 - pkt4Time := pkt3Time + byteLatency*2 - - // No reads, so no sleeps yet. - wantSleeps() - - read := func(n int, want []byte) { - b := make([]byte, n) - if rd, err := c.Read(b); err != nil || rd != len(want) { - t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil", n, rd, err, len(want)) - } - if !reflect.DeepEqual(b[:len(want)], want) { - t.Fatalf("read %v; want %v", b, want) - } - } - - read(1, []byte{1}) - wantSleeps(pkt1Time) - read(1, []byte{2}) - wantSleeps() - read(3, []byte{3, 4, 5}) - wantSleeps() - read(2, []byte{6}) - wantSleeps(pkt2Time) - read(2, []byte{7, 8}) - wantSleeps(pkt3Time) - read(10, []byte{9, 10, 11}) - wantSleeps() - read(10, []byte{12, 13}) - wantSleeps(pkt4Time) -} - -func TestSync(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - sleep = func(d time.Duration) { tn = tn.Add(d) } - - // Simulate a 20ms latency network, then run sync across that and expect to - // measure 20ms latency, or 10ms additional delay for a 30ms network. - slowConn, err := (&Network{Kbps: 0, Latency: 20 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - c, err := (&Network{Latency: 30 * time.Millisecond}).Conn(slowConn) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - if c.(*conn).delay != 10*time.Millisecond { - t.Fatalf("c.delay = %v; want 10ms", c.(*conn).delay) - } -} - -func TestSyncTooSlow(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - sleep = func(d time.Duration) { tn = tn.Add(d) } - - // Simulate a 10ms latency network, then attempt to simulate a 5ms latency - // network and expect an error. - slowConn, err := (&Network{Kbps: 0, Latency: 10 * time.Millisecond, MTU: 5}).Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - - errWant := "measured network latency (10ms) higher than desired latency (5ms)" - if _, err := (&Network{Latency: 5 * time.Millisecond}).Conn(slowConn); err == nil || err.Error() != errWant { - t.Fatalf("Conn() = _, %q; want _, %q", err, errWant) - } -} - -func TestListenerAndDialer(t *testing.T) { - defer restoreHooks()() - - tn := time.Unix(123, 0) - startTime := tn - mu := &sync.Mutex{} - now = func() time.Time { - mu.Lock() - defer mu.Unlock() - return tn - } - - // Use a fairly high latency to cause a large BDP and avoid sleeps while - // writing due to simulation of full buffers. - n := &Network{Kbps: 2, Latency: 1 * time.Second, MTU: 10} - // 2 kbps = .25 kBps = 256 Bps - byteLatency := func(n int) time.Duration { - return time.Duration(n) * time.Second / 256 - } - - // Create a real listener and wrap it. - l, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Unexpected error creating listener: %v", err) - } - defer l.Close() - l = n.Listener(l) - - var serverConn net.Conn - var scErr error - scDone := make(chan struct{}) - go func() { - serverConn, scErr = l.Accept() - close(scDone) - }() - - // Create a dialer and use it. - clientConn, err := n.TimeoutDialer(net.DialTimeout)("tcp", l.Addr().String(), 2*time.Second) - if err != nil { - t.Fatalf("Unexpected error dialing: %v", err) - } - defer clientConn.Close() - - // Block until server's Conn is available. - <-scDone - if scErr != nil { - t.Fatalf("Unexpected error listening: %v", scErr) - } - defer serverConn.Close() - - // sleep (only) advances tn. Done after connections established so sync detects zero delay. - sleep = func(d time.Duration) { - mu.Lock() - defer mu.Unlock() - if d > 0 { - tn = tn.Add(d) - } - } - - seq := func(a, b int) []byte { - buf := make([]byte, b-a) - for i := 0; i < b-a; i++ { - buf[i] = byte(i + a) - } - return buf - } - - pkt1 := seq(0, 10) - pkt2 := seq(10, 30) - pkt3 := seq(30, 35) - - write := func(c net.Conn, b []byte) { - n, err := c.Write(b) - if n != len(b) || err != nil { - t.Fatalf("c.Write(%v) = %v, %v; want %v, nil", b, n, err, len(b)) - } - } - - write(serverConn, pkt1) - write(serverConn, pkt2) - write(serverConn, pkt3) - write(clientConn, pkt3) - write(clientConn, pkt1) - write(clientConn, pkt2) - - if tn != startTime { - t.Fatalf("unexpected sleep in write; tn = %v; want %v", tn, startTime) - } - - read := func(c net.Conn, n int, want []byte, timeWant time.Time) { - b := make([]byte, n) - if rd, err := c.Read(b); err != nil || rd != len(want) { - t.Fatalf("c.Read(<%v bytes>) = %v, %v; want %v, nil (read: %v)", n, rd, err, len(want), b[:rd]) - } - if !reflect.DeepEqual(b[:len(want)], want) { - t.Fatalf("read %v; want %v", b, want) - } - if !tn.Equal(timeWant) { - t.Errorf("tn after read(%v) = %v; want %v", want, tn, timeWant) - } - } - - read(clientConn, len(pkt1)+1, pkt1, startTime.Add(n.Latency+byteLatency(len(pkt1)))) - read(serverConn, len(pkt3)+1, pkt3, tn) // tn was advanced by the above read; pkt3 is shorter than pkt1 - - read(clientConn, len(pkt2), pkt2[:10], startTime.Add(n.Latency+byteLatency(len(pkt1)+10))) - read(clientConn, len(pkt2), pkt2[10:], startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2)))) - read(clientConn, len(pkt3), pkt3, startTime.Add(n.Latency+byteLatency(len(pkt1)+len(pkt2)+len(pkt3)))) - - read(serverConn, len(pkt1), pkt1, tn) // tn already past the arrival time due to prior reads - read(serverConn, len(pkt2), pkt2[:10], tn) - read(serverConn, len(pkt2), pkt2[10:], tn) - - // Sleep awhile and make sure the read happens disregarding previous writes - // (lastSendEnd handling). - sleep(10 * time.Second) - write(clientConn, pkt1) - read(serverConn, len(pkt1), pkt1, tn.Add(n.Latency+byteLatency(len(pkt1)))) - - // Send, sleep longer than the network delay, then make sure the read happens - // instantly. - write(serverConn, pkt1) - sleep(10 * time.Second) - read(clientConn, len(pkt1), pkt1, tn) -} - -func TestBufferBloat(t *testing.T) { - defer restoreHooks()() - - // Infinitely fast CPU: time doesn't pass unless sleep is called. - tn := time.Unix(123, 0) - now = func() time.Time { return tn } - // Capture sleep times for checking later. - var sleepTimes []time.Duration - sleep = func(d time.Duration) { - sleepTimes = append(sleepTimes, d) - tn = tn.Add(d) - } - - wantSleeps := func(want ...time.Duration) error { - if !reflect.DeepEqual(want, sleepTimes) { - return fmt.Errorf("sleepTimes = %v; want %v", sleepTimes, want) - } - sleepTimes = nil - return nil - } - - n := &Network{Kbps: 8 /* 1KBps */, Latency: time.Second, MTU: 8} - bdpBytes := (n.Kbps * 1024 / 8) * int(n.Latency/time.Second) // 1024 - c, err := n.Conn(bufConn{&bytes.Buffer{}}) - if err != nil { - t.Fatalf("Unexpected error creating connection: %v", err) - } - wantSleeps(n.Latency) // Connection creation delay. - - write := func(n int, sleeps ...time.Duration) { - if wt, err := c.Write(make([]byte, n)); err != nil || wt != n { - t.Fatalf("c.Write(<%v bytes>) = %v, %v; want %v, nil", n, wt, err, n) - } - if err := wantSleeps(sleeps...); err != nil { - t.Fatalf("After writing %v bytes: %v", n, err) - } - } - - read := func(n int, sleeps ...time.Duration) { - if rd, err := c.Read(make([]byte, n)); err != nil || rd != n { - t.Fatalf("c.Read(_) = %v, %v; want %v, nil", rd, err, n) - } - if err := wantSleeps(sleeps...); err != nil { - t.Fatalf("After reading %v bytes: %v", n, err) - } - } - - write(8) // No reads and buffer not full, so no sleeps yet. - read(8, time.Second+n.pktTime(8)) - - write(bdpBytes) // Fill the buffer. - write(1) // We can send one extra packet even when the buffer is full. - write(n.MTU, n.pktTime(1)) // Make sure we sleep to clear the previous write. - write(1, n.pktTime(n.MTU)) - write(n.MTU+1, n.pktTime(1), n.pktTime(n.MTU)) - - tn = tn.Add(10 * time.Second) // Wait long enough for the buffer to clear. - write(bdpBytes) // No sleeps required. -} diff --git a/examples/google.golang.org/grpc/benchmark/primitives/code_string_test.go b/examples/google.golang.org/grpc/benchmark/primitives/code_string_test.go deleted file mode 100755 index 51b1ee4..0000000 --- a/examples/google.golang.org/grpc/benchmark/primitives/code_string_test.go +++ /dev/null @@ -1,135 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package primitives_test - -import ( - "strconv" - "testing" - - "google.golang.org/grpc/codes" -) - -type codeBench uint32 - -const ( - OK codeBench = iota - Canceled - Unknown - InvalidArgument - DeadlineExceeded - NotFound - AlreadyExists - PermissionDenied - ResourceExhausted - FailedPrecondition - Aborted - OutOfRange - Unimplemented - Internal - Unavailable - DataLoss - Unauthenticated -) - -// The following String() function was generated by stringer. -const _Code_name = "OKCanceledUnknownInvalidArgumentDeadlineExceededNotFoundAlreadyExistsPermissionDeniedResourceExhaustedFailedPreconditionAbortedOutOfRangeUnimplementedInternalUnavailableDataLossUnauthenticated" - -var _Code_index = [...]uint8{0, 2, 10, 17, 32, 48, 56, 69, 85, 102, 120, 127, 137, 150, 158, 169, 177, 192} - -func (i codeBench) String() string { - if i >= codeBench(len(_Code_index)-1) { - return "Code(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Code_name[_Code_index[i]:_Code_index[i+1]] -} - -var nameMap = map[codeBench]string{ - OK: "OK", - Canceled: "Canceled", - Unknown: "Unknown", - InvalidArgument: "InvalidArgument", - DeadlineExceeded: "DeadlineExceeded", - NotFound: "NotFound", - AlreadyExists: "AlreadyExists", - PermissionDenied: "PermissionDenied", - ResourceExhausted: "ResourceExhausted", - FailedPrecondition: "FailedPrecondition", - Aborted: "Aborted", - OutOfRange: "OutOfRange", - Unimplemented: "Unimplemented", - Internal: "Internal", - Unavailable: "Unavailable", - DataLoss: "DataLoss", - Unauthenticated: "Unauthenticated", -} - -func (i codeBench) StringUsingMap() string { - if s, ok := nameMap[i]; ok { - return s - } - return "Code(" + strconv.FormatInt(int64(i), 10) + ")" -} - -func BenchmarkCodeStringStringer(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := codeBench(uint32(i % 17)) - _ = c.String() - } - b.StopTimer() -} - -func BenchmarkCodeStringMap(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := codeBench(uint32(i % 17)) - _ = c.StringUsingMap() - } - b.StopTimer() -} - -// codes.Code.String() does a switch. -func BenchmarkCodeStringSwitch(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := codes.Code(uint32(i % 17)) - _ = c.String() - } - b.StopTimer() -} - -// Testing all codes (0<=c<=16) and also one overflow (17). -func BenchmarkCodeStringStringerWithOverflow(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := codeBench(uint32(i % 18)) - _ = c.String() - } - b.StopTimer() -} - -// Testing all codes (0<=c<=16) and also one overflow (17). -func BenchmarkCodeStringSwitchWithOverflow(b *testing.B) { - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := codes.Code(uint32(i % 18)) - _ = c.String() - } - b.StopTimer() -} diff --git a/examples/google.golang.org/grpc/benchmark/primitives/context_test.go b/examples/google.golang.org/grpc/benchmark/primitives/context_test.go deleted file mode 100755 index e1d6c04..0000000 --- a/examples/google.golang.org/grpc/benchmark/primitives/context_test.go +++ /dev/null @@ -1,120 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package primitives_test - -import ( - "testing" - "time" - - "golang.org/x/net/context" -) - -func BenchmarkCancelContextErrNoErr(b *testing.B) { - ctx, cancel := context.WithCancel(context.Background()) - for i := 0; i < b.N; i++ { - if err := ctx.Err(); err != nil { - b.Fatal("error") - } - } - cancel() -} - -func BenchmarkCancelContextErrGotErr(b *testing.B) { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - for i := 0; i < b.N; i++ { - if err := ctx.Err(); err == nil { - b.Fatal("error") - } - } -} - -func BenchmarkCancelContextChannelNoErr(b *testing.B) { - ctx, cancel := context.WithCancel(context.Background()) - for i := 0; i < b.N; i++ { - select { - case <-ctx.Done(): - b.Fatal("error: ctx.Done():", ctx.Err()) - default: - } - } - cancel() -} - -func BenchmarkCancelContextChannelGotErr(b *testing.B) { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - for i := 0; i < b.N; i++ { - select { - case <-ctx.Done(): - if err := ctx.Err(); err == nil { - b.Fatal("error") - } - default: - b.Fatal("error: !ctx.Done()") - } - } -} - -func BenchmarkTimerContextErrNoErr(b *testing.B) { - ctx, cancel := context.WithTimeout(context.Background(), 24*time.Hour) - for i := 0; i < b.N; i++ { - if err := ctx.Err(); err != nil { - b.Fatal("error") - } - } - cancel() -} - -func BenchmarkTimerContextErrGotErr(b *testing.B) { - ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond) - cancel() - for i := 0; i < b.N; i++ { - if err := ctx.Err(); err == nil { - b.Fatal("error") - } - } -} - -func BenchmarkTimerContextChannelNoErr(b *testing.B) { - ctx, cancel := context.WithTimeout(context.Background(), 24*time.Hour) - for i := 0; i < b.N; i++ { - select { - case <-ctx.Done(): - b.Fatal("error: ctx.Done():", ctx.Err()) - default: - } - } - cancel() -} - -func BenchmarkTimerContextChannelGotErr(b *testing.B) { - ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond) - cancel() - for i := 0; i < b.N; i++ { - select { - case <-ctx.Done(): - if err := ctx.Err(); err == nil { - b.Fatal("error") - } - default: - b.Fatal("error: !ctx.Done()") - } - } -} diff --git a/examples/google.golang.org/grpc/benchmark/primitives/primitives_test.go b/examples/google.golang.org/grpc/benchmark/primitives/primitives_test.go deleted file mode 100755 index 846813d..0000000 --- a/examples/google.golang.org/grpc/benchmark/primitives/primitives_test.go +++ /dev/null @@ -1,403 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package primitives_test contains benchmarks for various synchronization primitives -// available in Go. -package primitives_test - -import ( - "fmt" - "sync" - "sync/atomic" - "testing" - "time" - "unsafe" -) - -func BenchmarkSelectClosed(b *testing.B) { - c := make(chan struct{}) - close(c) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - select { - case <-c: - x++ - default: - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkSelectOpen(b *testing.B) { - c := make(chan struct{}) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - select { - case <-c: - default: - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicBool(b *testing.B) { - c := int32(0) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if atomic.LoadInt32(&c) == 0 { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicValueLoad(b *testing.B) { - c := atomic.Value{} - c.Store(0) - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if c.Load().(int) == 0 { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicValueStore(b *testing.B) { - c := atomic.Value{} - v := 123 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Store(v) - } - b.StopTimer() -} - -func BenchmarkMutex(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Lock() - x++ - c.Unlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkRWMutex(b *testing.B) { - c := sync.RWMutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.RLock() - x++ - c.RUnlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkRWMutexW(b *testing.B) { - c := sync.RWMutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Lock() - x++ - c.Unlock() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - defer c.Unlock() - x++ - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithClosureDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - defer func() { c.Unlock() }() - x++ - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkMutexWithoutDefer(b *testing.B) { - c := sync.Mutex{} - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - func() { - c.Lock() - x++ - c.Unlock() - }() - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkAtomicAddInt64(b *testing.B) { - var c int64 - b.ResetTimer() - for i := 0; i < b.N; i++ { - atomic.AddInt64(&c, 1) - } - b.StopTimer() - if c != int64(b.N) { - b.Fatal("error") - } -} - -func BenchmarkAtomicTimeValueStore(b *testing.B) { - var c atomic.Value - t := time.Now() - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Store(t) - } - b.StopTimer() -} - -func BenchmarkAtomic16BValueStore(b *testing.B) { - var c atomic.Value - t := struct { - a int64 - b int64 - }{ - 123, 123, - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Store(t) - } - b.StopTimer() -} - -func BenchmarkAtomic32BValueStore(b *testing.B) { - var c atomic.Value - t := struct { - a int64 - b int64 - c int64 - d int64 - }{ - 123, 123, 123, 123, - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Store(t) - } - b.StopTimer() -} - -func BenchmarkAtomicPointerStore(b *testing.B) { - t := 123 - var up unsafe.Pointer - b.ResetTimer() - for i := 0; i < b.N; i++ { - atomic.StorePointer(&up, unsafe.Pointer(&t)) - } - b.StopTimer() -} - -func BenchmarkAtomicTimePointerStore(b *testing.B) { - t := time.Now() - var up unsafe.Pointer - b.ResetTimer() - for i := 0; i < b.N; i++ { - atomic.StorePointer(&up, unsafe.Pointer(&t)) - } - b.StopTimer() -} - -func BenchmarkStoreContentionWithAtomic(b *testing.B) { - t := 123 - var c unsafe.Pointer - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - atomic.StorePointer(&c, unsafe.Pointer(&t)) - } - }) -} - -func BenchmarkStoreContentionWithMutex(b *testing.B) { - t := 123 - var mu sync.Mutex - var c int - - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - mu.Lock() - c = t - mu.Unlock() - } - }) - _ = c -} - -type dummyStruct struct { - a int64 - b time.Time -} - -func BenchmarkStructStoreContention(b *testing.B) { - d := dummyStruct{} - dp := unsafe.Pointer(&d) - t := time.Now() - for _, j := range []int{100000000, 10000, 0} { - for _, i := range []int{100000, 10} { - b.Run(fmt.Sprintf("CAS/%v/%v", j, i), func(b *testing.B) { - b.SetParallelism(i) - b.RunParallel(func(pb *testing.PB) { - n := &dummyStruct{ - b: t, - } - for pb.Next() { - for y := 0; y < j; y++ { - } - for { - v := (*dummyStruct)(atomic.LoadPointer(&dp)) - n.a = v.a + 1 - if atomic.CompareAndSwapPointer(&dp, unsafe.Pointer(v), unsafe.Pointer(n)) { - n = v - break - } - } - } - }) - }) - } - } - - var mu sync.Mutex - for _, j := range []int{100000000, 10000, 0} { - for _, i := range []int{100000, 10} { - b.Run(fmt.Sprintf("Mutex/%v/%v", j, i), func(b *testing.B) { - b.SetParallelism(i) - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - for y := 0; y < j; y++ { - } - mu.Lock() - d.a++ - d.b = t - mu.Unlock() - } - }) - }) - } - } -} - -type myFooer struct{} - -func (myFooer) Foo() {} - -type fooer interface { - Foo() -} - -func BenchmarkInterfaceTypeAssertion(b *testing.B) { - // Call a separate function to avoid compiler optimizations. - runInterfaceTypeAssertion(b, myFooer{}) -} - -func runInterfaceTypeAssertion(b *testing.B, fer interface{}) { - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, ok := fer.(fooer); ok { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} - -func BenchmarkStructTypeAssertion(b *testing.B) { - // Call a separate function to avoid compiler optimizations. - runStructTypeAssertion(b, myFooer{}) -} - -func runStructTypeAssertion(b *testing.B, fer interface{}) { - x := 0 - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, ok := fer.(myFooer); ok { - x++ - } - } - b.StopTimer() - if x != b.N { - b.Fatal("error") - } -} diff --git a/examples/google.golang.org/grpc/benchmark/run_bench.sh b/examples/google.golang.org/grpc/benchmark/run_bench.sh deleted file mode 100755 index 045de16..0000000 --- a/examples/google.golang.org/grpc/benchmark/run_bench.sh +++ /dev/null @@ -1,187 +0,0 @@ -#!/bin/bash - -rpcs=(1) -conns=(1) -warmup=10 -dur=10 -reqs=(1) -resps=(1) -rpc_types=(unary) - -# idx[0] = idx value for rpcs -# idx[1] = idx value for conns -# idx[2] = idx value for reqs -# idx[3] = idx value for resps -# idx[4] = idx value for rpc_types -idx=(0 0 0 0 0) -idx_max=(1 1 1 1 1) - -inc() -{ - for i in $(seq $((${#idx[@]}-1)) -1 0); do - idx[${i}]=$((${idx[${i}]}+1)) - if [ ${idx[${i}]} == ${idx_max[${i}]} ]; then - idx[${i}]=0 - else - break - fi - done - local fin - fin=1 - # Check to see if we have looped back to the beginning. - for v in ${idx[@]}; do - if [ ${v} != 0 ]; then - fin=0 - break - fi - done - if [ ${fin} == 1 ]; then - rm -Rf ${out_dir} - clean_and_die 0 - fi -} - -clean_and_die() { - rm -Rf ${out_dir} - exit $1 -} - -run(){ - local nr - nr=${rpcs[${idx[0]}]} - local nc - nc=${conns[${idx[1]}]} - req_sz=${reqs[${idx[2]}]} - resp_sz=${resps[${idx[3]}]} - r_type=${rpc_types[${idx[4]}]} - # Following runs one benchmark - base_port=50051 - delta=0 - test_name="r_"${nr}"_c_"${nc}"_req_"${req_sz}"_resp_"${resp_sz}"_"${r_type}"_"$(date +%s) - echo "================================================================================" - echo ${test_name} - while : - do - port=$((${base_port}+${delta})) - - # Launch the server in background - ${out_dir}/server --port=${port} --test_name="Server_"${test_name}& - server_pid=$(echo $!) - - # Launch the client - ${out_dir}/client --port=${port} --d=${dur} --w=${warmup} --r=${nr} --c=${nc} --req=${req_sz} --resp=${resp_sz} --rpc_type=${r_type} --test_name="client_"${test_name} - client_status=$(echo $?) - - kill ${server_pid} - wait ${server_pid} - - if [ ${client_status} == 0 ]; then - break - fi - - delta=$((${delta}+1)) - if [ ${delta} == 10 ]; then - echo "Continuous 10 failed runs. Exiting now." - rm -Rf ${out_dir} - clean_and_die 1 - fi - done - -} - -set_param(){ - local argname=$1 - shift - local idx=$1 - shift - if [ $# -eq 0 ]; then - echo "${argname} not specified" - exit 1 - fi - PARAM=($(echo $1 | sed 's/,/ /g')) - if [ ${idx} -lt 0 ]; then - return - fi - idx_max[${idx}]=${#PARAM[@]} -} - -while [ $# -gt 0 ]; do - case "$1" in - -r) - shift - set_param "number of rpcs" 0 $1 - rpcs=(${PARAM[@]}) - shift - ;; - -c) - shift - set_param "number of connections" 1 $1 - conns=(${PARAM[@]}) - shift - ;; - -w) - shift - set_param "warm-up period" -1 $1 - warmup=${PARAM} - shift - ;; - -d) - shift - set_param "duration" -1 $1 - dur=${PARAM} - shift - ;; - -req) - shift - set_param "request size" 2 $1 - reqs=(${PARAM[@]}) - shift - ;; - -resp) - shift - set_param "response size" 3 $1 - resps=(${PARAM[@]}) - shift - ;; - -rpc_type) - shift - set_param "rpc type" 4 $1 - rpc_types=(${PARAM[@]}) - shift - ;; - -h|--help) - echo "Following are valid options:" - echo - echo "-h, --help show brief help" - echo "-w warm-up duration in seconds, default value is 10" - echo "-d benchmark duration in seconds, default value is 60" - echo "" - echo "Each of the following can have multiple comma separated values." - echo "" - echo "-r number of RPCs, default value is 1" - echo "-c number of Connections, default value is 1" - echo "-req req size in bytes, default value is 1" - echo "-resp resp size in bytes, default value is 1" - echo "-rpc_type valid values are unary|streaming, default is unary" - ;; - *) - echo "Incorrect option $1" - exit 1 - ;; - esac -done - -# Build server and client -out_dir=$(mktemp -d oss_benchXXX) - -go build -o ${out_dir}/server $GOPATH/src/google.golang.org/grpc/benchmark/server/main.go && go build -o ${out_dir}/client $GOPATH/src/google.golang.org/grpc/benchmark/client/main.go -if [ $? != 0 ]; then - clean_and_die 1 -fi - - -while : -do - run - inc -done diff --git a/examples/google.golang.org/grpc/benchmark/server/main.go b/examples/google.golang.org/grpc/benchmark/server/main.go deleted file mode 100755 index 253657e..0000000 --- a/examples/google.golang.org/grpc/benchmark/server/main.go +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "fmt" - "net" - _ "net/http/pprof" - "os" - "os/signal" - "runtime" - "runtime/pprof" - "syscall" - "time" - - "golang.org/x/sys/unix" - "google.golang.org/grpc/benchmark" - "google.golang.org/grpc/grpclog" -) - -var ( - port = flag.String("port", "50051", "Localhost port to listen on.") - testName = flag.String("test_name", "", "Name of the test used for creating profiles.") -) - -func main() { - flag.Parse() - if *testName == "" { - grpclog.Fatalf("test name not set") - } - lis, err := net.Listen("tcp", ":"+*port) - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - defer lis.Close() - - cf, err := os.Create("/tmp/" + *testName + ".cpu") - if err != nil { - grpclog.Fatalf("Failed to create file: %v", err) - } - defer cf.Close() - pprof.StartCPUProfile(cf) - cpuBeg := getCPUTime() - // Launch server in a separate goroutine. - stop := benchmark.StartServer(benchmark.ServerInfo{Type: "protobuf", Listener: lis}) - // Wait on OS terminate signal. - ch := make(chan os.Signal, 1) - signal.Notify(ch, syscall.SIGTERM) - <-ch - cpu := time.Duration(getCPUTime() - cpuBeg) - stop() - pprof.StopCPUProfile() - mf, err := os.Create("/tmp/" + *testName + ".mem") - if err != nil { - grpclog.Fatalf("Failed to create file: %v", err) - } - defer mf.Close() - runtime.GC() // materialize all statistics - if err := pprof.WriteHeapProfile(mf); err != nil { - grpclog.Fatalf("Failed to write memory profile: %v", err) - } - fmt.Println("Server CPU utilization:", cpu) - fmt.Println("Server CPU profile:", cf.Name()) - fmt.Println("Server Mem Profile:", mf.Name()) -} - -func getCPUTime() int64 { - var ts unix.Timespec - if err := unix.ClockGettime(unix.CLOCK_PROCESS_CPUTIME_ID, &ts); err != nil { - grpclog.Fatal(err) - } - return ts.Nano() -} diff --git a/examples/google.golang.org/grpc/benchmark/stats/histogram.go b/examples/google.golang.org/grpc/benchmark/stats/histogram.go deleted file mode 100755 index f038d26..0000000 --- a/examples/google.golang.org/grpc/benchmark/stats/histogram.go +++ /dev/null @@ -1,222 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bytes" - "fmt" - "io" - "log" - "math" - "strconv" - "strings" -) - -// Histogram accumulates values in the form of a histogram with -// exponentially increased bucket sizes. -type Histogram struct { - // Count is the total number of values added to the histogram. - Count int64 - // Sum is the sum of all the values added to the histogram. - Sum int64 - // SumOfSquares is the sum of squares of all values. - SumOfSquares int64 - // Min is the minimum of all the values added to the histogram. - Min int64 - // Max is the maximum of all the values added to the histogram. - Max int64 - // Buckets contains all the buckets of the histogram. - Buckets []HistogramBucket - - opts HistogramOptions - logBaseBucketSize float64 - oneOverLogOnePlusGrowthFactor float64 -} - -// HistogramOptions contains the parameters that define the histogram's buckets. -// The first bucket of the created histogram (with index 0) contains [min, min+n) -// where n = BaseBucketSize, min = MinValue. -// Bucket i (i>=1) contains [min + n * m^(i-1), min + n * m^i), where m = 1+GrowthFactor. -// The type of the values is int64. -type HistogramOptions struct { - // NumBuckets is the number of buckets. - NumBuckets int - // GrowthFactor is the growth factor of the buckets. A value of 0.1 - // indicates that bucket N+1 will be 10% larger than bucket N. - GrowthFactor float64 - // BaseBucketSize is the size of the first bucket. - BaseBucketSize float64 - // MinValue is the lower bound of the first bucket. - MinValue int64 -} - -// HistogramBucket represents one histogram bucket. -type HistogramBucket struct { - // LowBound is the lower bound of the bucket. - LowBound float64 - // Count is the number of values in the bucket. - Count int64 -} - -// NewHistogram returns a pointer to a new Histogram object that was created -// with the provided options. -func NewHistogram(opts HistogramOptions) *Histogram { - if opts.NumBuckets == 0 { - opts.NumBuckets = 32 - } - if opts.BaseBucketSize == 0.0 { - opts.BaseBucketSize = 1.0 - } - h := Histogram{ - Buckets: make([]HistogramBucket, opts.NumBuckets), - Min: math.MaxInt64, - Max: math.MinInt64, - - opts: opts, - logBaseBucketSize: math.Log(opts.BaseBucketSize), - oneOverLogOnePlusGrowthFactor: 1 / math.Log(1+opts.GrowthFactor), - } - m := 1.0 + opts.GrowthFactor - delta := opts.BaseBucketSize - h.Buckets[0].LowBound = float64(opts.MinValue) - for i := 1; i < opts.NumBuckets; i++ { - h.Buckets[i].LowBound = float64(opts.MinValue) + delta - delta = delta * m - } - return &h -} - -// Print writes textual output of the histogram values. -func (h *Histogram) Print(w io.Writer) { - h.PrintWithUnit(w, 1) -} - -// PrintWithUnit writes textual output of the histogram values . -// Data in histogram is divided by a Unit before print. -func (h *Histogram) PrintWithUnit(w io.Writer, unit float64) { - avg := float64(h.Sum) / float64(h.Count) - fmt.Fprintf(w, "Count: %d Min: %5.1f Max: %5.1f Avg: %.2f\n", h.Count, float64(h.Min)/unit, float64(h.Max)/unit, avg/unit) - fmt.Fprintf(w, "%s\n", strings.Repeat("-", 60)) - if h.Count <= 0 { - return - } - - maxBucketDigitLen := len(strconv.FormatFloat(h.Buckets[len(h.Buckets)-1].LowBound, 'f', 6, 64)) - if maxBucketDigitLen < 3 { - // For "inf". - maxBucketDigitLen = 3 - } - maxCountDigitLen := len(strconv.FormatInt(h.Count, 10)) - percentMulti := 100 / float64(h.Count) - - accCount := int64(0) - for i, b := range h.Buckets { - fmt.Fprintf(w, "[%*f, ", maxBucketDigitLen, b.LowBound/unit) - if i+1 < len(h.Buckets) { - fmt.Fprintf(w, "%*f)", maxBucketDigitLen, h.Buckets[i+1].LowBound/unit) - } else { - fmt.Fprintf(w, "%*s)", maxBucketDigitLen, "inf") - } - - accCount += b.Count - fmt.Fprintf(w, " %*d %5.1f%% %5.1f%%", maxCountDigitLen, b.Count, float64(b.Count)*percentMulti, float64(accCount)*percentMulti) - - const barScale = 0.1 - barLength := int(float64(b.Count)*percentMulti*barScale + 0.5) - fmt.Fprintf(w, " %s\n", strings.Repeat("#", barLength)) - } -} - -// String returns the textual output of the histogram values as string. -func (h *Histogram) String() string { - var b bytes.Buffer - h.Print(&b) - return b.String() -} - -// Clear resets all the content of histogram. -func (h *Histogram) Clear() { - h.Count = 0 - h.Sum = 0 - h.SumOfSquares = 0 - h.Min = math.MaxInt64 - h.Max = math.MinInt64 - for i := range h.Buckets { - h.Buckets[i].Count = 0 - } -} - -// Opts returns a copy of the options used to create the Histogram. -func (h *Histogram) Opts() HistogramOptions { - return h.opts -} - -// Add adds a value to the histogram. -func (h *Histogram) Add(value int64) error { - bucket, err := h.findBucket(value) - if err != nil { - return err - } - h.Buckets[bucket].Count++ - h.Count++ - h.Sum += value - h.SumOfSquares += value * value - if value < h.Min { - h.Min = value - } - if value > h.Max { - h.Max = value - } - return nil -} - -func (h *Histogram) findBucket(value int64) (int, error) { - delta := float64(value - h.opts.MinValue) - var b int - if delta >= h.opts.BaseBucketSize { - // b = log_{1+growthFactor} (delta / baseBucketSize) + 1 - // = log(delta / baseBucketSize) / log(1+growthFactor) + 1 - // = (log(delta) - log(baseBucketSize)) * (1 / log(1+growthFactor)) + 1 - b = int((math.Log(delta)-h.logBaseBucketSize)*h.oneOverLogOnePlusGrowthFactor + 1) - } - if b >= len(h.Buckets) { - return 0, fmt.Errorf("no bucket for value: %d", value) - } - return b, nil -} - -// Merge takes another histogram h2, and merges its content into h. -// The two histograms must be created by equivalent HistogramOptions. -func (h *Histogram) Merge(h2 *Histogram) { - if h.opts != h2.opts { - log.Fatalf("failed to merge histograms, created by inequivalent options") - } - h.Count += h2.Count - h.Sum += h2.Sum - h.SumOfSquares += h2.SumOfSquares - if h2.Min < h.Min { - h.Min = h2.Min - } - if h2.Max > h.Max { - h.Max = h2.Max - } - for i, b := range h2.Buckets { - h.Buckets[i].Count += b.Count - } -} diff --git a/examples/google.golang.org/grpc/benchmark/stats/stats.go b/examples/google.golang.org/grpc/benchmark/stats/stats.go deleted file mode 100755 index 041d247..0000000 --- a/examples/google.golang.org/grpc/benchmark/stats/stats.go +++ /dev/null @@ -1,302 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bytes" - "fmt" - "io" - "math" - "sort" - "strconv" - "time" -) - -// Features contains most fields for a benchmark -type Features struct { - NetworkMode string - EnableTrace bool - Latency time.Duration - Kbps int - Mtu int - MaxConcurrentCalls int - ReqSizeBytes int - RespSizeBytes int - EnableCompressor bool - EnableChannelz bool -} - -// String returns the textual output of the Features as string. -func (f Features) String() string { - return fmt.Sprintf("traceMode_%t-latency_%s-kbps_%#v-MTU_%#v-maxConcurrentCalls_"+ - "%#v-reqSize_%#vB-respSize_%#vB-Compressor_%t", f.EnableTrace, - f.Latency.String(), f.Kbps, f.Mtu, f.MaxConcurrentCalls, f.ReqSizeBytes, f.RespSizeBytes, f.EnableCompressor) -} - -// ConciseString returns the concise textual output of the Features as string, skipping -// setting with default value. -func (f Features) ConciseString() string { - noneEmptyPos := []bool{f.EnableTrace, f.Latency != 0, f.Kbps != 0, f.Mtu != 0, true, true, true, f.EnableCompressor, f.EnableChannelz} - return PartialPrintString(noneEmptyPos, f, false) -} - -// PartialPrintString can print certain features with different format. -func PartialPrintString(noneEmptyPos []bool, f Features, shared bool) string { - s := "" - var ( - prefix, suffix, linker string - isNetwork bool - ) - if shared { - suffix = "\n" - linker = ": " - } else { - prefix = "-" - linker = "_" - } - if noneEmptyPos[0] { - s += fmt.Sprintf("%sTrace%s%t%s", prefix, linker, f.EnableTrace, suffix) - } - if shared && f.NetworkMode != "" { - s += fmt.Sprintf("Network: %s \n", f.NetworkMode) - isNetwork = true - } - if !isNetwork { - if noneEmptyPos[1] { - s += fmt.Sprintf("%slatency%s%s%s", prefix, linker, f.Latency.String(), suffix) - } - if noneEmptyPos[2] { - s += fmt.Sprintf("%skbps%s%#v%s", prefix, linker, f.Kbps, suffix) - } - if noneEmptyPos[3] { - s += fmt.Sprintf("%sMTU%s%#v%s", prefix, linker, f.Mtu, suffix) - } - } - if noneEmptyPos[4] { - s += fmt.Sprintf("%sCallers%s%#v%s", prefix, linker, f.MaxConcurrentCalls, suffix) - } - if noneEmptyPos[5] { - s += fmt.Sprintf("%sreqSize%s%#vB%s", prefix, linker, f.ReqSizeBytes, suffix) - } - if noneEmptyPos[6] { - s += fmt.Sprintf("%srespSize%s%#vB%s", prefix, linker, f.RespSizeBytes, suffix) - } - if noneEmptyPos[7] { - s += fmt.Sprintf("%sCompressor%s%t%s", prefix, linker, f.EnableCompressor, suffix) - } - if noneEmptyPos[8] { - s += fmt.Sprintf("%sChannelz%s%t%s", prefix, linker, f.EnableChannelz, suffix) - } - return s -} - -type percentLatency struct { - Percent int - Value time.Duration -} - -// BenchResults records features and result of a benchmark. -type BenchResults struct { - RunMode string - Features Features - Latency []percentLatency - Operations int - NsPerOp int64 - AllocedBytesPerOp int64 - AllocsPerOp int64 - SharedPosion []bool -} - -// SetBenchmarkResult sets features of benchmark and basic results. -func (stats *Stats) SetBenchmarkResult(mode string, features Features, o int, allocdBytes, allocs int64, sharedPos []bool) { - stats.result.RunMode = mode - stats.result.Features = features - stats.result.Operations = o - stats.result.AllocedBytesPerOp = allocdBytes - stats.result.AllocsPerOp = allocs - stats.result.SharedPosion = sharedPos -} - -// GetBenchmarkResults returns the result of the benchmark including features and result. -func (stats *Stats) GetBenchmarkResults() BenchResults { - return stats.result -} - -// BenchString output latency stats as the format as time + unit. -func (stats *Stats) BenchString() string { - stats.maybeUpdate() - s := stats.result - res := s.RunMode + "-" + s.Features.String() + ": \n" - if len(s.Latency) != 0 { - var statsUnit = s.Latency[0].Value - var timeUnit = fmt.Sprintf("%v", statsUnit)[1:] - for i := 1; i < len(s.Latency)-1; i++ { - res += fmt.Sprintf("%d_Latency: %s %s \t", s.Latency[i].Percent, - strconv.FormatFloat(float64(s.Latency[i].Value)/float64(statsUnit), 'f', 4, 64), timeUnit) - } - res += fmt.Sprintf("Avg latency: %s %s \t", - strconv.FormatFloat(float64(s.Latency[len(s.Latency)-1].Value)/float64(statsUnit), 'f', 4, 64), timeUnit) - } - res += fmt.Sprintf("Count: %v \t", s.Operations) - res += fmt.Sprintf("%v Bytes/op\t", s.AllocedBytesPerOp) - res += fmt.Sprintf("%v Allocs/op\t", s.AllocsPerOp) - - return res -} - -// Stats is a simple helper for gathering additional statistics like histogram -// during benchmarks. This is not thread safe. -type Stats struct { - numBuckets int - unit time.Duration - min, max int64 - histogram *Histogram - - durations durationSlice - dirty bool - - sortLatency bool - result BenchResults -} - -type durationSlice []time.Duration - -// NewStats creates a new Stats instance. If numBuckets is not positive, -// the default value (16) will be used. -func NewStats(numBuckets int) *Stats { - if numBuckets <= 0 { - numBuckets = 16 - } - return &Stats{ - // Use one more bucket for the last unbounded bucket. - numBuckets: numBuckets + 1, - durations: make(durationSlice, 0, 100000), - } -} - -// Add adds an elapsed time per operation to the stats. -func (stats *Stats) Add(d time.Duration) { - stats.durations = append(stats.durations, d) - stats.dirty = true -} - -// Clear resets the stats, removing all values. -func (stats *Stats) Clear() { - stats.durations = stats.durations[:0] - stats.histogram = nil - stats.dirty = false - stats.result = BenchResults{} -} - -//Sort method for durations -func (a durationSlice) Len() int { return len(a) } -func (a durationSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a durationSlice) Less(i, j int) bool { return a[i] < a[j] } -func max(a, b int64) int64 { - if a > b { - return a - } - return b -} - -// maybeUpdate updates internal stat data if there was any newly added -// stats since this was updated. -func (stats *Stats) maybeUpdate() { - if !stats.dirty { - return - } - - if stats.sortLatency { - sort.Sort(stats.durations) - stats.min = int64(stats.durations[0]) - stats.max = int64(stats.durations[len(stats.durations)-1]) - } - - stats.min = math.MaxInt64 - stats.max = 0 - for _, d := range stats.durations { - if stats.min > int64(d) { - stats.min = int64(d) - } - if stats.max < int64(d) { - stats.max = int64(d) - } - } - - // Use the largest unit that can represent the minimum time duration. - stats.unit = time.Nanosecond - for _, u := range []time.Duration{time.Microsecond, time.Millisecond, time.Second} { - if stats.min <= int64(u) { - break - } - stats.unit = u - } - - numBuckets := stats.numBuckets - if n := int(stats.max - stats.min + 1); n < numBuckets { - numBuckets = n - } - stats.histogram = NewHistogram(HistogramOptions{ - NumBuckets: numBuckets, - // max-min(lower bound of last bucket) = (1 + growthFactor)^(numBuckets-2) * baseBucketSize. - GrowthFactor: math.Pow(float64(stats.max-stats.min), 1/float64(numBuckets-2)) - 1, - BaseBucketSize: 1.0, - MinValue: stats.min}) - - for _, d := range stats.durations { - stats.histogram.Add(int64(d)) - } - - stats.dirty = false - - if stats.durations.Len() != 0 { - var percentToObserve = []int{50, 90, 99} - // First data record min unit from the latency result. - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: -1, Value: stats.unit}) - for _, position := range percentToObserve { - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: position, Value: stats.durations[max(stats.histogram.Count*int64(position)/100-1, 0)]}) - } - // Last data record the average latency. - avg := float64(stats.histogram.Sum) / float64(stats.histogram.Count) - stats.result.Latency = append(stats.result.Latency, percentLatency{Percent: -1, Value: time.Duration(avg)}) - } -} - -// SortLatency blocks the output -func (stats *Stats) SortLatency() { - stats.sortLatency = true -} - -// Print writes textual output of the Stats. -func (stats *Stats) Print(w io.Writer) { - stats.maybeUpdate() - if stats.histogram == nil { - fmt.Fprint(w, "Histogram (empty)\n") - } else { - fmt.Fprintf(w, "Histogram (unit: %s)\n", fmt.Sprintf("%v", stats.unit)[1:]) - stats.histogram.PrintWithUnit(w, float64(stats.unit)) - } -} - -// String returns the textual output of the Stats as string. -func (stats *Stats) String() string { - var b bytes.Buffer - stats.Print(&b) - return b.String() -} diff --git a/examples/google.golang.org/grpc/benchmark/stats/util.go b/examples/google.golang.org/grpc/benchmark/stats/util.go deleted file mode 100755 index f3bb3a3..0000000 --- a/examples/google.golang.org/grpc/benchmark/stats/util.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats - -import ( - "bufio" - "bytes" - "fmt" - "os" - "runtime" - "sort" - "strings" - "sync" - "testing" -) - -var ( - curB *testing.B - curBenchName string - curStats map[string]*Stats - - orgStdout *os.File - nextOutPos int - - injectCond *sync.Cond - injectDone chan struct{} -) - -// AddStats adds a new unnamed Stats instance to the current benchmark. You need -// to run benchmarks by calling RunTestMain() to inject the stats to the -// benchmark results. If numBuckets is not positive, the default value (16) will -// be used. Please note that this calls b.ResetTimer() since it may be blocked -// until the previous benchmark stats is printed out. So AddStats() should -// typically be called at the very beginning of each benchmark function. -func AddStats(b *testing.B, numBuckets int) *Stats { - return AddStatsWithName(b, "", numBuckets) -} - -// AddStatsWithName adds a new named Stats instance to the current benchmark. -// With this, you can add multiple stats in a single benchmark. You need -// to run benchmarks by calling RunTestMain() to inject the stats to the -// benchmark results. If numBuckets is not positive, the default value (16) will -// be used. Please note that this calls b.ResetTimer() since it may be blocked -// until the previous benchmark stats is printed out. So AddStatsWithName() -// should typically be called at the very beginning of each benchmark function. -func AddStatsWithName(b *testing.B, name string, numBuckets int) *Stats { - var benchName string - for i := 1; ; i++ { - pc, _, _, ok := runtime.Caller(i) - if !ok { - panic("benchmark function not found") - } - p := strings.Split(runtime.FuncForPC(pc).Name(), ".") - benchName = p[len(p)-1] - if strings.HasPrefix(benchName, "run") { - break - } - } - procs := runtime.GOMAXPROCS(-1) - if procs != 1 { - benchName = fmt.Sprintf("%s-%d", benchName, procs) - } - - stats := NewStats(numBuckets) - - if injectCond != nil { - // We need to wait until the previous benchmark stats is printed out. - injectCond.L.Lock() - for curB != nil && curBenchName != benchName { - injectCond.Wait() - } - - curB = b - curBenchName = benchName - curStats[name] = stats - - injectCond.L.Unlock() - } - - b.ResetTimer() - return stats -} - -// RunTestMain runs the tests with enabling injection of benchmark stats. It -// returns an exit code to pass to os.Exit. -func RunTestMain(m *testing.M) int { - startStatsInjector() - defer stopStatsInjector() - return m.Run() -} - -// startStatsInjector starts stats injection to benchmark results. -func startStatsInjector() { - orgStdout = os.Stdout - r, w, _ := os.Pipe() - os.Stdout = w - nextOutPos = 0 - - resetCurBenchStats() - - injectCond = sync.NewCond(&sync.Mutex{}) - injectDone = make(chan struct{}) - go func() { - defer close(injectDone) - - scanner := bufio.NewScanner(r) - scanner.Split(splitLines) - for scanner.Scan() { - injectStatsIfFinished(scanner.Text()) - } - if err := scanner.Err(); err != nil { - panic(err) - } - }() -} - -// stopStatsInjector stops stats injection and restores os.Stdout. -func stopStatsInjector() { - os.Stdout.Close() - <-injectDone - injectCond = nil - os.Stdout = orgStdout -} - -// splitLines is a split function for a bufio.Scanner that returns each line -// of text, teeing texts to the original stdout even before each line ends. -func splitLines(data []byte, eof bool) (advance int, token []byte, err error) { - if eof && len(data) == 0 { - return 0, nil, nil - } - - if i := bytes.IndexByte(data, '\n'); i >= 0 { - orgStdout.Write(data[nextOutPos : i+1]) - nextOutPos = 0 - return i + 1, data[0:i], nil - } - - orgStdout.Write(data[nextOutPos:]) - nextOutPos = len(data) - - if eof { - // This is a final, non-terminated line. Return it. - return len(data), data, nil - } - - return 0, nil, nil -} - -// injectStatsIfFinished prints out the stats if the current benchmark finishes. -func injectStatsIfFinished(line string) { - injectCond.L.Lock() - defer injectCond.L.Unlock() - // We assume that the benchmark results start with "Benchmark". - if curB == nil || !strings.HasPrefix(line, "Benchmark") { - return - } - - if !curB.Failed() { - // Output all stats in alphabetical order. - names := make([]string, 0, len(curStats)) - for name := range curStats { - names = append(names, name) - } - sort.Strings(names) - for _, name := range names { - stats := curStats[name] - // The output of stats starts with a header like "Histogram (unit: ms)" - // followed by statistical properties and the buckets. Add the stats name - // if it is a named stats and indent them as Go testing outputs. - lines := strings.Split(stats.String(), "\n") - if n := len(lines); n > 0 { - if name != "" { - name = ": " + name - } - fmt.Fprintf(orgStdout, "--- %s%s\n", lines[0], name) - for _, line := range lines[1 : n-1] { - fmt.Fprintf(orgStdout, "\t%s\n", line) - } - } - } - } - - resetCurBenchStats() - injectCond.Signal() -} - -// resetCurBenchStats resets the current benchmark stats. -func resetCurBenchStats() { - curB = nil - curBenchName = "" - curStats = make(map[string]*Stats) -} diff --git a/examples/google.golang.org/grpc/benchmark/worker/benchmark_client.go b/examples/google.golang.org/grpc/benchmark/worker/benchmark_client.go deleted file mode 100755 index 56cf087..0000000 --- a/examples/google.golang.org/grpc/benchmark/worker/benchmark_client.go +++ /dev/null @@ -1,391 +0,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. - * - */ - -package main - -import ( - "flag" - "math" - "runtime" - "sync" - "syscall" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/benchmark/stats" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" - "google.golang.org/grpc/testdata" -) - -var caFile = flag.String("ca_file", "", "The file containing the CA root cert file") - -type lockingHistogram struct { - mu sync.Mutex - histogram *stats.Histogram -} - -func (h *lockingHistogram) add(value int64) { - h.mu.Lock() - defer h.mu.Unlock() - h.histogram.Add(value) -} - -// swap sets h.histogram to new, and returns its old value. -func (h *lockingHistogram) swap(new *stats.Histogram) *stats.Histogram { - h.mu.Lock() - defer h.mu.Unlock() - old := h.histogram - h.histogram = new - return old -} - -func (h *lockingHistogram) mergeInto(merged *stats.Histogram) { - h.mu.Lock() - defer h.mu.Unlock() - merged.Merge(h.histogram) -} - -type benchmarkClient struct { - closeConns func() - stop chan bool - lastResetTime time.Time - histogramOptions stats.HistogramOptions - lockingHistograms []lockingHistogram - rusageLastReset *syscall.Rusage -} - -func printClientConfig(config *testpb.ClientConfig) { - // Some config options are ignored: - // - client type: - // will always create sync client - // - async client threads. - // - core list - grpclog.Infof(" * client type: %v (ignored, always creates sync client)", config.ClientType) - grpclog.Infof(" * async client threads: %v (ignored)", config.AsyncClientThreads) - // TODO: use cores specified by CoreList when setting list of cores is supported in go. - grpclog.Infof(" * core list: %v (ignored)", config.CoreList) - - grpclog.Infof(" - security params: %v", config.SecurityParams) - grpclog.Infof(" - core limit: %v", config.CoreLimit) - grpclog.Infof(" - payload config: %v", config.PayloadConfig) - grpclog.Infof(" - rpcs per chann: %v", config.OutstandingRpcsPerChannel) - grpclog.Infof(" - channel number: %v", config.ClientChannels) - grpclog.Infof(" - load params: %v", config.LoadParams) - grpclog.Infof(" - rpc type: %v", config.RpcType) - grpclog.Infof(" - histogram params: %v", config.HistogramParams) - grpclog.Infof(" - server targets: %v", config.ServerTargets) -} - -func setupClientEnv(config *testpb.ClientConfig) { - // Use all cpu cores available on machine by default. - // TODO: Revisit this for the optimal default setup. - if config.CoreLimit > 0 { - runtime.GOMAXPROCS(int(config.CoreLimit)) - } else { - runtime.GOMAXPROCS(runtime.NumCPU()) - } -} - -// createConns creates connections according to given config. -// It returns the connections and corresponding function to close them. -// It returns non-nil error if there is anything wrong. -func createConns(config *testpb.ClientConfig) ([]*grpc.ClientConn, func(), error) { - var opts []grpc.DialOption - - // Sanity check for client type. - switch config.ClientType { - case testpb.ClientType_SYNC_CLIENT: - case testpb.ClientType_ASYNC_CLIENT: - default: - return nil, nil, status.Errorf(codes.InvalidArgument, "unknown client type: %v", config.ClientType) - } - - // Check and set security options. - if config.SecurityParams != nil { - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err := credentials.NewClientTLSFromFile(*caFile, config.SecurityParams.ServerHostOverride) - if err != nil { - return nil, nil, status.Errorf(codes.InvalidArgument, "failed to create TLS credentials %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - - // Use byteBufCodec if it is required. - if config.PayloadConfig != nil { - switch config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - opts = append(opts, grpc.WithDefaultCallOptions(grpc.CallCustomCodec(byteBufCodec{}))) - case *testpb.PayloadConfig_SimpleParams: - default: - return nil, nil, status.Errorf(codes.InvalidArgument, "unknown payload config: %v", config.PayloadConfig) - } - } - - // Create connections. - connCount := int(config.ClientChannels) - conns := make([]*grpc.ClientConn, connCount) - for connIndex := 0; connIndex < connCount; connIndex++ { - conns[connIndex] = benchmark.NewClientConn(config.ServerTargets[connIndex%len(config.ServerTargets)], opts...) - } - - return conns, func() { - for _, conn := range conns { - conn.Close() - } - }, nil -} - -func performRPCs(config *testpb.ClientConfig, conns []*grpc.ClientConn, bc *benchmarkClient) error { - // Read payload size and type from config. - var ( - payloadReqSize, payloadRespSize int - payloadType string - ) - if config.PayloadConfig != nil { - switch c := config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - payloadReqSize = int(c.BytebufParams.ReqSize) - payloadRespSize = int(c.BytebufParams.RespSize) - payloadType = "bytebuf" - case *testpb.PayloadConfig_SimpleParams: - payloadReqSize = int(c.SimpleParams.ReqSize) - payloadRespSize = int(c.SimpleParams.RespSize) - payloadType = "protobuf" - default: - return status.Errorf(codes.InvalidArgument, "unknown payload config: %v", config.PayloadConfig) - } - } - - // TODO add open loop distribution. - switch config.LoadParams.Load.(type) { - case *testpb.LoadParams_ClosedLoop: - case *testpb.LoadParams_Poisson: - return status.Errorf(codes.Unimplemented, "unsupported load params: %v", config.LoadParams) - default: - return status.Errorf(codes.InvalidArgument, "unknown load params: %v", config.LoadParams) - } - - rpcCountPerConn := int(config.OutstandingRpcsPerChannel) - - switch config.RpcType { - case testpb.RpcType_UNARY: - bc.doCloseLoopUnary(conns, rpcCountPerConn, payloadReqSize, payloadRespSize) - // TODO open loop. - case testpb.RpcType_STREAMING: - bc.doCloseLoopStreaming(conns, rpcCountPerConn, payloadReqSize, payloadRespSize, payloadType) - // TODO open loop. - default: - return status.Errorf(codes.InvalidArgument, "unknown rpc type: %v", config.RpcType) - } - - return nil -} - -func startBenchmarkClient(config *testpb.ClientConfig) (*benchmarkClient, error) { - printClientConfig(config) - - // Set running environment like how many cores to use. - setupClientEnv(config) - - conns, closeConns, err := createConns(config) - if err != nil { - return nil, err - } - - rusage := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusage) - - rpcCountPerConn := int(config.OutstandingRpcsPerChannel) - bc := &benchmarkClient{ - histogramOptions: stats.HistogramOptions{ - NumBuckets: int(math.Log(config.HistogramParams.MaxPossible)/math.Log(1+config.HistogramParams.Resolution)) + 1, - GrowthFactor: config.HistogramParams.Resolution, - BaseBucketSize: (1 + config.HistogramParams.Resolution), - MinValue: 0, - }, - lockingHistograms: make([]lockingHistogram, rpcCountPerConn*len(conns)), - - stop: make(chan bool), - lastResetTime: time.Now(), - closeConns: closeConns, - rusageLastReset: rusage, - } - - if err = performRPCs(config, conns, bc); err != nil { - // Close all connections if performRPCs failed. - closeConns() - return nil, err - } - - return bc, nil -} - -func (bc *benchmarkClient) doCloseLoopUnary(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int) { - for ic, conn := range conns { - client := testpb.NewBenchmarkServiceClient(conn) - // For each connection, create rpcCountPerConn goroutines to do rpc. - for j := 0; j < rpcCountPerConn; j++ { - // Create histogram for each goroutine. - idx := ic*rpcCountPerConn + j - bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) - // Start goroutine on the created mutex and histogram. - go func(idx int) { - // TODO: do warm up if necessary. - // Now relying on worker client to reserve time to do warm up. - // The worker client needs to wait for some time after client is created, - // before starting benchmark. - done := make(chan bool) - for { - go func() { - start := time.Now() - if err := benchmark.DoUnaryCall(client, reqSize, respSize); err != nil { - select { - case <-bc.stop: - case done <- false: - } - return - } - elapse := time.Since(start) - bc.lockingHistograms[idx].add(int64(elapse)) - select { - case <-bc.stop: - case done <- true: - } - }() - select { - case <-bc.stop: - return - case <-done: - } - } - }(idx) - } - } -} - -func (bc *benchmarkClient) doCloseLoopStreaming(conns []*grpc.ClientConn, rpcCountPerConn int, reqSize int, respSize int, payloadType string) { - var doRPC func(testpb.BenchmarkService_StreamingCallClient, int, int) error - if payloadType == "bytebuf" { - doRPC = benchmark.DoByteBufStreamingRoundTrip - } else { - doRPC = benchmark.DoStreamingRoundTrip - } - for ic, conn := range conns { - // For each connection, create rpcCountPerConn goroutines to do rpc. - for j := 0; j < rpcCountPerConn; j++ { - c := testpb.NewBenchmarkServiceClient(conn) - stream, err := c.StreamingCall(context.Background()) - if err != nil { - grpclog.Fatalf("%v.StreamingCall(_) = _, %v", c, err) - } - // Create histogram for each goroutine. - idx := ic*rpcCountPerConn + j - bc.lockingHistograms[idx].histogram = stats.NewHistogram(bc.histogramOptions) - // Start goroutine on the created mutex and histogram. - go func(idx int) { - // TODO: do warm up if necessary. - // Now relying on worker client to reserve time to do warm up. - // The worker client needs to wait for some time after client is created, - // before starting benchmark. - for { - start := time.Now() - if err := doRPC(stream, reqSize, respSize); err != nil { - return - } - elapse := time.Since(start) - bc.lockingHistograms[idx].add(int64(elapse)) - select { - case <-bc.stop: - return - default: - } - } - }(idx) - } - } -} - -// getStats returns the stats for benchmark client. -// It resets lastResetTime and all histograms if argument reset is true. -func (bc *benchmarkClient) getStats(reset bool) *testpb.ClientStats { - var wallTimeElapsed, uTimeElapsed, sTimeElapsed float64 - mergedHistogram := stats.NewHistogram(bc.histogramOptions) - latestRusage := new(syscall.Rusage) - - if reset { - // Merging histogram may take some time. - // Put all histograms aside and merge later. - toMerge := make([]*stats.Histogram, len(bc.lockingHistograms)) - for i := range bc.lockingHistograms { - toMerge[i] = bc.lockingHistograms[i].swap(stats.NewHistogram(bc.histogramOptions)) - } - - for i := 0; i < len(toMerge); i++ { - mergedHistogram.Merge(toMerge[i]) - } - - wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() - syscall.Getrusage(syscall.RUSAGE_SELF, latestRusage) - uTimeElapsed, sTimeElapsed = cpuTimeDiff(bc.rusageLastReset, latestRusage) - - bc.rusageLastReset = latestRusage - bc.lastResetTime = time.Now() - } else { - // Merge only, not reset. - for i := range bc.lockingHistograms { - bc.lockingHistograms[i].mergeInto(mergedHistogram) - } - - wallTimeElapsed = time.Since(bc.lastResetTime).Seconds() - syscall.Getrusage(syscall.RUSAGE_SELF, latestRusage) - uTimeElapsed, sTimeElapsed = cpuTimeDiff(bc.rusageLastReset, latestRusage) - } - - b := make([]uint32, len(mergedHistogram.Buckets)) - for i, v := range mergedHistogram.Buckets { - b[i] = uint32(v.Count) - } - return &testpb.ClientStats{ - Latencies: &testpb.HistogramData{ - Bucket: b, - MinSeen: float64(mergedHistogram.Min), - MaxSeen: float64(mergedHistogram.Max), - Sum: float64(mergedHistogram.Sum), - SumOfSquares: float64(mergedHistogram.SumOfSquares), - Count: float64(mergedHistogram.Count), - }, - TimeElapsed: wallTimeElapsed, - TimeUser: uTimeElapsed, - TimeSystem: sTimeElapsed, - } -} - -func (bc *benchmarkClient) shutdown() { - close(bc.stop) - bc.closeConns() -} diff --git a/examples/google.golang.org/grpc/benchmark/worker/benchmark_server.go b/examples/google.golang.org/grpc/benchmark/worker/benchmark_server.go deleted file mode 100755 index 9b1f676..0000000 --- a/examples/google.golang.org/grpc/benchmark/worker/benchmark_server.go +++ /dev/null @@ -1,188 +0,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. - * - */ - -package main - -import ( - "flag" - "fmt" - "net" - "runtime" - "strconv" - "strings" - "sync" - "syscall" - "time" - - "google.golang.org/grpc" - "google.golang.org/grpc/benchmark" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" - "google.golang.org/grpc/testdata" -) - -var ( - certFile = flag.String("tls_cert_file", "", "The TLS cert file") - keyFile = flag.String("tls_key_file", "", "The TLS key file") -) - -type benchmarkServer struct { - port int - cores int - closeFunc func() - mu sync.RWMutex - lastResetTime time.Time - rusageLastReset *syscall.Rusage -} - -func printServerConfig(config *testpb.ServerConfig) { - // Some config options are ignored: - // - server type: - // will always start sync server - // - async server threads - // - core list - grpclog.Infof(" * server type: %v (ignored, always starts sync server)", config.ServerType) - grpclog.Infof(" * async server threads: %v (ignored)", config.AsyncServerThreads) - // TODO: use cores specified by CoreList when setting list of cores is supported in go. - grpclog.Infof(" * core list: %v (ignored)", config.CoreList) - - grpclog.Infof(" - security params: %v", config.SecurityParams) - grpclog.Infof(" - core limit: %v", config.CoreLimit) - grpclog.Infof(" - port: %v", config.Port) - grpclog.Infof(" - payload config: %v", config.PayloadConfig) -} - -func startBenchmarkServer(config *testpb.ServerConfig, serverPort int) (*benchmarkServer, error) { - printServerConfig(config) - - // Use all cpu cores available on machine by default. - // TODO: Revisit this for the optimal default setup. - numOfCores := runtime.NumCPU() - if config.CoreLimit > 0 { - numOfCores = int(config.CoreLimit) - } - runtime.GOMAXPROCS(numOfCores) - - var opts []grpc.ServerOption - - // Sanity check for server type. - switch config.ServerType { - case testpb.ServerType_SYNC_SERVER: - case testpb.ServerType_ASYNC_SERVER: - case testpb.ServerType_ASYNC_GENERIC_SERVER: - default: - return nil, status.Errorf(codes.InvalidArgument, "unknown server type: %v", config.ServerType) - } - - // Set security options. - if config.SecurityParams != nil { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - grpclog.Fatalf("failed to generate credentials %v", err) - } - opts = append(opts, grpc.Creds(creds)) - } - - // Priority: config.Port > serverPort > default (0). - port := int(config.Port) - if port == 0 { - port = serverPort - } - lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - if err != nil { - grpclog.Fatalf("Failed to listen: %v", err) - } - addr := lis.Addr().String() - - // Create different benchmark server according to config. - var closeFunc func() - if config.PayloadConfig != nil { - switch payload := config.PayloadConfig.Payload.(type) { - case *testpb.PayloadConfig_BytebufParams: - opts = append(opts, grpc.CustomCodec(byteBufCodec{})) - closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Type: "bytebuf", - Metadata: payload.BytebufParams.RespSize, - Listener: lis, - }, opts...) - case *testpb.PayloadConfig_SimpleParams: - closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Type: "protobuf", - Listener: lis, - }, opts...) - case *testpb.PayloadConfig_ComplexParams: - return nil, status.Errorf(codes.Unimplemented, "unsupported payload config: %v", config.PayloadConfig) - default: - return nil, status.Errorf(codes.InvalidArgument, "unknown payload config: %v", config.PayloadConfig) - } - } else { - // Start protobuf server if payload config is nil. - closeFunc = benchmark.StartServer(benchmark.ServerInfo{ - Type: "protobuf", - Listener: lis, - }, opts...) - } - - grpclog.Infof("benchmark server listening at %v", addr) - addrSplitted := strings.Split(addr, ":") - p, err := strconv.Atoi(addrSplitted[len(addrSplitted)-1]) - if err != nil { - grpclog.Fatalf("failed to get port number from server address: %v", err) - } - - rusage := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusage) - - return &benchmarkServer{ - port: p, - cores: numOfCores, - closeFunc: closeFunc, - lastResetTime: time.Now(), - rusageLastReset: rusage, - }, nil -} - -// getStats returns the stats for benchmark server. -// It resets lastResetTime if argument reset is true. -func (bs *benchmarkServer) getStats(reset bool) *testpb.ServerStats { - bs.mu.RLock() - defer bs.mu.RUnlock() - wallTimeElapsed := time.Since(bs.lastResetTime).Seconds() - rusageLatest := new(syscall.Rusage) - syscall.Getrusage(syscall.RUSAGE_SELF, rusageLatest) - uTimeElapsed, sTimeElapsed := cpuTimeDiff(bs.rusageLastReset, rusageLatest) - - if reset { - bs.lastResetTime = time.Now() - bs.rusageLastReset = rusageLatest - } - return &testpb.ServerStats{ - TimeElapsed: wallTimeElapsed, - TimeUser: uTimeElapsed, - TimeSystem: sTimeElapsed, - } -} diff --git a/examples/google.golang.org/grpc/benchmark/worker/main.go b/examples/google.golang.org/grpc/benchmark/worker/main.go deleted file mode 100755 index 3d2fd61..0000000 --- a/examples/google.golang.org/grpc/benchmark/worker/main.go +++ /dev/null @@ -1,230 +0,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. - * - */ - -package main - -import ( - "flag" - "fmt" - "io" - "net" - "net/http" - _ "net/http/pprof" - "runtime" - "strconv" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - testpb "google.golang.org/grpc/benchmark/grpc_testing" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -var ( - driverPort = flag.Int("driver_port", 10000, "port for communication with driver") - serverPort = flag.Int("server_port", 0, "port for benchmark server if not specified by server config message") - pprofPort = flag.Int("pprof_port", -1, "Port for pprof debug server to listen on. Pprof server doesn't start if unset") - blockProfRate = flag.Int("block_prof_rate", 0, "fraction of goroutine blocking events to report in blocking profile") -) - -type byteBufCodec struct { -} - -func (byteBufCodec) Marshal(v interface{}) ([]byte, error) { - b, ok := v.(*[]byte) - if !ok { - return nil, fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) - } - return *b, nil -} - -func (byteBufCodec) Unmarshal(data []byte, v interface{}) error { - b, ok := v.(*[]byte) - if !ok { - return fmt.Errorf("failed to marshal: %v is not type of *[]byte", v) - } - *b = data - return nil -} - -func (byteBufCodec) String() string { - return "bytebuffer" -} - -// workerServer implements WorkerService rpc handlers. -// It can create benchmarkServer or benchmarkClient on demand. -type workerServer struct { - stop chan<- bool - serverPort int -} - -func (s *workerServer) RunServer(stream testpb.WorkerService_RunServerServer) error { - var bs *benchmarkServer - defer func() { - // Close benchmark server when stream ends. - grpclog.Infof("closing benchmark server") - if bs != nil { - bs.closeFunc() - } - }() - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - var out *testpb.ServerStatus - switch argtype := in.Argtype.(type) { - case *testpb.ServerArgs_Setup: - grpclog.Infof("server setup received:") - if bs != nil { - grpclog.Infof("server setup received when server already exists, closing the existing server") - bs.closeFunc() - } - bs, err = startBenchmarkServer(argtype.Setup, s.serverPort) - if err != nil { - return err - } - out = &testpb.ServerStatus{ - Stats: bs.getStats(false), - Port: int32(bs.port), - Cores: int32(bs.cores), - } - - case *testpb.ServerArgs_Mark: - grpclog.Infof("server mark received:") - grpclog.Infof(" - %v", argtype) - if bs == nil { - return status.Error(codes.InvalidArgument, "server does not exist when mark received") - } - out = &testpb.ServerStatus{ - Stats: bs.getStats(argtype.Mark.Reset_), - Port: int32(bs.port), - Cores: int32(bs.cores), - } - } - - if err := stream.Send(out); err != nil { - return err - } - } -} - -func (s *workerServer) RunClient(stream testpb.WorkerService_RunClientServer) error { - var bc *benchmarkClient - defer func() { - // Shut down benchmark client when stream ends. - grpclog.Infof("shuting down benchmark client") - if bc != nil { - bc.shutdown() - } - }() - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - var out *testpb.ClientStatus - switch t := in.Argtype.(type) { - case *testpb.ClientArgs_Setup: - grpclog.Infof("client setup received:") - if bc != nil { - grpclog.Infof("client setup received when client already exists, shuting down the existing client") - bc.shutdown() - } - bc, err = startBenchmarkClient(t.Setup) - if err != nil { - return err - } - out = &testpb.ClientStatus{ - Stats: bc.getStats(false), - } - - case *testpb.ClientArgs_Mark: - grpclog.Infof("client mark received:") - grpclog.Infof(" - %v", t) - if bc == nil { - return status.Error(codes.InvalidArgument, "client does not exist when mark received") - } - out = &testpb.ClientStatus{ - Stats: bc.getStats(t.Mark.Reset_), - } - } - - if err := stream.Send(out); err != nil { - return err - } - } -} - -func (s *workerServer) CoreCount(ctx context.Context, in *testpb.CoreRequest) (*testpb.CoreResponse, error) { - grpclog.Infof("core count: %v", runtime.NumCPU()) - return &testpb.CoreResponse{Cores: int32(runtime.NumCPU())}, nil -} - -func (s *workerServer) QuitWorker(ctx context.Context, in *testpb.Void) (*testpb.Void, error) { - grpclog.Infof("quitting worker") - s.stop <- true - return &testpb.Void{}, nil -} - -func main() { - grpc.EnableTracing = false - - flag.Parse() - lis, err := net.Listen("tcp", ":"+strconv.Itoa(*driverPort)) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - grpclog.Infof("worker listening at port %v", *driverPort) - - s := grpc.NewServer() - stop := make(chan bool) - testpb.RegisterWorkerServiceServer(s, &workerServer{ - stop: stop, - serverPort: *serverPort, - }) - - go func() { - <-stop - // Wait for 1 second before stopping the server to make sure the return value of QuitWorker is sent to client. - // TODO revise this once server graceful stop is supported in gRPC. - time.Sleep(time.Second) - s.Stop() - }() - - runtime.SetBlockProfileRate(*blockProfRate) - - if *pprofPort >= 0 { - go func() { - grpclog.Infoln("Starting pprof server on port " + strconv.Itoa(*pprofPort)) - grpclog.Infoln(http.ListenAndServe("localhost:"+strconv.Itoa(*pprofPort), nil)) - }() - } - - s.Serve(lis) -} diff --git a/examples/google.golang.org/grpc/benchmark/worker/util.go b/examples/google.golang.org/grpc/benchmark/worker/util.go deleted file mode 100755 index f26993e..0000000 --- a/examples/google.golang.org/grpc/benchmark/worker/util.go +++ /dev/null @@ -1,35 +0,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. - * - */ - -package main - -import "syscall" - -func cpuTimeDiff(first *syscall.Rusage, latest *syscall.Rusage) (float64, float64) { - var ( - utimeDiffs = latest.Utime.Sec - first.Utime.Sec - utimeDiffus = latest.Utime.Usec - first.Utime.Usec - stimeDiffs = latest.Stime.Sec - first.Stime.Sec - stimeDiffus = latest.Stime.Usec - first.Stime.Usec - ) - - uTimeElapsed := float64(utimeDiffs) + float64(utimeDiffus)*1.0e-6 - sTimeElapsed := float64(stimeDiffs) + float64(stimeDiffus)*1.0e-6 - - return uTimeElapsed, sTimeElapsed -} diff --git a/examples/google.golang.org/grpc/call.go b/examples/google.golang.org/grpc/call.go deleted file mode 100755 index f73b7d5..0000000 --- a/examples/google.golang.org/grpc/call.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "golang.org/x/net/context" -) - -// Invoke sends the RPC request on the wire and returns after response is -// received. This is typically called by generated code. -// -// All errors returned by Invoke are compatible with the status package. -func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error { - // allow interceptor to see all applicable call options, which means those - // configured as defaults from dial option as well as per-call options - opts = combine(cc.dopts.callOptions, opts) - - if cc.dopts.unaryInt != nil { - return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...) - } - return invoke(ctx, method, args, reply, cc, opts...) -} - -func combine(o1 []CallOption, o2 []CallOption) []CallOption { - // we don't use append because o1 could have extra capacity whose - // elements would be overwritten, which could cause inadvertent - // sharing (and race connditions) between concurrent calls - if len(o1) == 0 { - return o2 - } else if len(o2) == 0 { - return o1 - } - ret := make([]CallOption, len(o1)+len(o2)) - copy(ret, o1) - copy(ret[len(o1):], o2) - return ret -} - -// Invoke sends the RPC request on the wire and returns after response is -// received. This is typically called by generated code. -// -// DEPRECATED: Use ClientConn.Invoke instead. -func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { - return cc.Invoke(ctx, method, args, reply, opts...) -} - -var unaryStreamDesc = &StreamDesc{ServerStreams: false, ClientStreams: false} - -func invoke(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error { - // TODO: implement retries in clientStream and make this simply - // newClientStream, SendMsg, RecvMsg. - firstAttempt := true - for { - csInt, err := newClientStream(ctx, unaryStreamDesc, cc, method, opts...) - if err != nil { - return err - } - cs := csInt.(*clientStream) - if err := cs.SendMsg(req); err != nil { - if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { - // TODO: Add a field to header for grpc-transparent-retry-attempts - firstAttempt = false - continue - } - return err - } - if err := cs.RecvMsg(reply); err != nil { - if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { - // TODO: Add a field to header for grpc-transparent-retry-attempts - firstAttempt = false - continue - } - return err - } - return nil - } -} diff --git a/examples/google.golang.org/grpc/call_test.go b/examples/google.golang.org/grpc/call_test.go deleted file mode 100755 index d57d01e..0000000 --- a/examples/google.golang.org/grpc/call_test.go +++ /dev/null @@ -1,293 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "io" - "math" - "net" - "strconv" - "strings" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -var ( - expectedRequest = "ping" - expectedResponse = "pong" - weirdError = "format verbs: %v%s" - sizeLargeErr = 1024 * 1024 - canceled = 0 -) - -type testCodec struct { -} - -func (testCodec) Marshal(v interface{}) ([]byte, error) { - return []byte(*(v.(*string))), nil -} - -func (testCodec) Unmarshal(data []byte, v interface{}) error { - *(v.(*string)) = string(data) - return nil -} - -func (testCodec) String() string { - return "test" -} - -type testStreamHandler struct { - port string - t transport.ServerTransport -} - -func (h *testStreamHandler) handleStream(t *testing.T, s *transport.Stream) { - p := &parser{r: s} - for { - pf, req, err := p.recvMsg(math.MaxInt32) - if err == io.EOF { - break - } - if err != nil { - return - } - if pf != compressionNone { - t.Errorf("Received the mistaken message format %d, want %d", pf, compressionNone) - return - } - var v string - codec := testCodec{} - if err := codec.Unmarshal(req, &v); err != nil { - t.Errorf("Failed to unmarshal the received message: %v", err) - return - } - if v == "weird error" { - h.t.WriteStatus(s, status.New(codes.Internal, weirdError)) - return - } - if v == "canceled" { - canceled++ - h.t.WriteStatus(s, status.New(codes.Internal, "")) - return - } - if v == "port" { - h.t.WriteStatus(s, status.New(codes.Internal, h.port)) - return - } - - if v != expectedRequest { - h.t.WriteStatus(s, status.New(codes.Internal, strings.Repeat("A", sizeLargeErr))) - return - } - } - // send a response back to end the stream. - data, err := encode(testCodec{}, &expectedResponse) - if err != nil { - t.Errorf("Failed to encode the response: %v", err) - return - } - hdr, payload := msgHeader(data, nil) - h.t.Write(s, hdr, payload, &transport.Options{}) - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -type server struct { - lis net.Listener - port string - addr string - startedErr chan error // sent nil or an error after server starts - mu sync.Mutex - conns map[transport.ServerTransport]bool -} - -func newTestServer() *server { - return &server{startedErr: make(chan error, 1)} -} - -// start starts server. Other goroutines should block on s.startedErr for further operations. -func (s *server) start(t *testing.T, port int, maxStreams uint32) { - var err error - if port == 0 { - s.lis, err = net.Listen("tcp", "localhost:0") - } else { - s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port)) - } - if err != nil { - s.startedErr <- fmt.Errorf("failed to listen: %v", err) - return - } - s.addr = s.lis.Addr().String() - _, p, err := net.SplitHostPort(s.addr) - if err != nil { - s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err) - return - } - s.port = p - s.conns = make(map[transport.ServerTransport]bool) - s.startedErr <- nil - for { - conn, err := s.lis.Accept() - if err != nil { - return - } - config := &transport.ServerConfig{ - MaxStreams: maxStreams, - } - st, err := transport.NewServerTransport("http2", conn, config) - if err != nil { - continue - } - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - st.Close() - return - } - s.conns[st] = true - s.mu.Unlock() - h := &testStreamHandler{ - port: s.port, - t: st, - } - go st.HandleStreams(func(s *transport.Stream) { - go h.handleStream(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - } -} - -func (s *server) wait(t *testing.T, timeout time.Duration) { - select { - case err := <-s.startedErr: - if err != nil { - t.Fatal(err) - } - case <-time.After(timeout): - t.Fatalf("Timed out after %v waiting for server to be ready", timeout) - } -} - -func (s *server) stop() { - s.lis.Close() - s.mu.Lock() - for c := range s.conns { - c.Close() - } - s.conns = nil - s.mu.Unlock() -} - -func setUp(t *testing.T, port int, maxStreams uint32) (*server, *ClientConn) { - server := newTestServer() - go server.start(t, port, maxStreams) - server.wait(t, 2*time.Second) - addr := "localhost:" + server.port - cc, err := Dial(addr, WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - return server, cc -} - -func TestInvoke(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want ", err) - } - cc.Close() - server.stop() -} - -func TestInvokeLargeErr(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "hello" - err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - if _, ok := status.FromError(err); !ok { - t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.") - } - if status.Code(err) != codes.Internal || len(errorDesc(err)) != sizeLargeErr { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want an error of code %d and desc size %d", err, codes.Internal, sizeLargeErr) - } - cc.Close() - server.stop() -} - -// TestInvokeErrorSpecialChars checks that error messages don't get mangled. -func TestInvokeErrorSpecialChars(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "weird error" - err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - if _, ok := status.FromError(err); !ok { - t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.") - } - if got, want := errorDesc(err), weirdError; got != want { - t.Fatalf("grpc.Invoke(_, _, _, _, _) error = %q, want %q", got, want) - } - cc.Close() - server.stop() -} - -// TestInvokeCancel checks that an Invoke with a canceled context is not sent. -func TestInvokeCancel(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "canceled" - for i := 0; i < 100; i++ { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - cc.Invoke(ctx, "/foo/bar", &req, &reply) - } - if canceled != 0 { - t.Fatalf("received %d of 100 canceled requests", canceled) - } - cc.Close() - server.stop() -} - -// TestInvokeCancelClosedNonFail checks that a canceled non-failfast RPC -// on a closed client will terminate. -func TestInvokeCancelClosedNonFailFast(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - cc.Close() - req := "hello" - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply, FailFast(false)); err == nil { - t.Fatalf("canceled invoke on closed connection should fail") - } - server.stop() -} diff --git a/examples/google.golang.org/grpc/channelz/grpc_channelz_v1/channelz.pb.go b/examples/google.golang.org/grpc/channelz/grpc_channelz_v1/channelz.pb.go deleted file mode 100755 index 747b8f8..0000000 --- a/examples/google.golang.org/grpc/channelz/grpc_channelz_v1/channelz.pb.go +++ /dev/null @@ -1,3257 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/channelz/v1/channelz.proto - -package grpc_channelz_v1 // import "google.golang.org/grpc/channelz/grpc_channelz_v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import any "github.com/golang/protobuf/ptypes/any" -import duration "github.com/golang/protobuf/ptypes/duration" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" -import wrappers "github.com/golang/protobuf/ptypes/wrappers" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ChannelConnectivityState_State int32 - -const ( - ChannelConnectivityState_UNKNOWN ChannelConnectivityState_State = 0 - ChannelConnectivityState_IDLE ChannelConnectivityState_State = 1 - ChannelConnectivityState_CONNECTING ChannelConnectivityState_State = 2 - ChannelConnectivityState_READY ChannelConnectivityState_State = 3 - ChannelConnectivityState_TRANSIENT_FAILURE ChannelConnectivityState_State = 4 - ChannelConnectivityState_SHUTDOWN ChannelConnectivityState_State = 5 -) - -var ChannelConnectivityState_State_name = map[int32]string{ - 0: "UNKNOWN", - 1: "IDLE", - 2: "CONNECTING", - 3: "READY", - 4: "TRANSIENT_FAILURE", - 5: "SHUTDOWN", -} -var ChannelConnectivityState_State_value = map[string]int32{ - "UNKNOWN": 0, - "IDLE": 1, - "CONNECTING": 2, - "READY": 3, - "TRANSIENT_FAILURE": 4, - "SHUTDOWN": 5, -} - -func (x ChannelConnectivityState_State) String() string { - return proto.EnumName(ChannelConnectivityState_State_name, int32(x)) -} -func (ChannelConnectivityState_State) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{2, 0} -} - -// The supported severity levels of trace events. -type ChannelTraceEvent_Severity int32 - -const ( - ChannelTraceEvent_CT_UNKNOWN ChannelTraceEvent_Severity = 0 - ChannelTraceEvent_CT_INFO ChannelTraceEvent_Severity = 1 - ChannelTraceEvent_CT_WARNING ChannelTraceEvent_Severity = 2 - ChannelTraceEvent_CT_ERROR ChannelTraceEvent_Severity = 3 -) - -var ChannelTraceEvent_Severity_name = map[int32]string{ - 0: "CT_UNKNOWN", - 1: "CT_INFO", - 2: "CT_WARNING", - 3: "CT_ERROR", -} -var ChannelTraceEvent_Severity_value = map[string]int32{ - "CT_UNKNOWN": 0, - "CT_INFO": 1, - "CT_WARNING": 2, - "CT_ERROR": 3, -} - -func (x ChannelTraceEvent_Severity) String() string { - return proto.EnumName(ChannelTraceEvent_Severity_name, int32(x)) -} -func (ChannelTraceEvent_Severity) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{4, 0} -} - -// Channel is a logical grouping of channels, subchannels, and sockets. -type Channel struct { - // The identifier for this channel. This should bet set. - Ref *ChannelRef `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` - // Data specific to this channel. - Data *ChannelData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` - // 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. - ChannelRef []*ChannelRef `protobuf:"bytes,3,rep,name=channel_ref,json=channelRef,proto3" json:"channel_ref,omitempty"` - // 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. - SubchannelRef []*SubchannelRef `protobuf:"bytes,4,rep,name=subchannel_ref,json=subchannelRef,proto3" json:"subchannel_ref,omitempty"` - // There are no ordering guarantees on the order of sockets. - SocketRef []*SocketRef `protobuf:"bytes,5,rep,name=socket_ref,json=socketRef,proto3" json:"socket_ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Channel) Reset() { *m = Channel{} } -func (m *Channel) String() string { return proto.CompactTextString(m) } -func (*Channel) ProtoMessage() {} -func (*Channel) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{0} -} -func (m *Channel) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Channel.Unmarshal(m, b) -} -func (m *Channel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Channel.Marshal(b, m, deterministic) -} -func (dst *Channel) XXX_Merge(src proto.Message) { - xxx_messageInfo_Channel.Merge(dst, src) -} -func (m *Channel) XXX_Size() int { - return xxx_messageInfo_Channel.Size(m) -} -func (m *Channel) XXX_DiscardUnknown() { - xxx_messageInfo_Channel.DiscardUnknown(m) -} - -var xxx_messageInfo_Channel proto.InternalMessageInfo - -func (m *Channel) GetRef() *ChannelRef { - if m != nil { - return m.Ref - } - return nil -} - -func (m *Channel) GetData() *ChannelData { - if m != nil { - return m.Data - } - return nil -} - -func (m *Channel) GetChannelRef() []*ChannelRef { - if m != nil { - return m.ChannelRef - } - return nil -} - -func (m *Channel) GetSubchannelRef() []*SubchannelRef { - if m != nil { - return m.SubchannelRef - } - return nil -} - -func (m *Channel) GetSocketRef() []*SocketRef { - if m != nil { - return m.SocketRef - } - return nil -} - -// Subchannel is a logical grouping of channels, subchannels, and sockets. -// A subchannel is load balanced over by it's ancestor -type Subchannel struct { - // The identifier for this channel. - Ref *SubchannelRef `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` - // Data specific to this channel. - Data *ChannelData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` - // 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. - ChannelRef []*ChannelRef `protobuf:"bytes,3,rep,name=channel_ref,json=channelRef,proto3" json:"channel_ref,omitempty"` - // 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. - SubchannelRef []*SubchannelRef `protobuf:"bytes,4,rep,name=subchannel_ref,json=subchannelRef,proto3" json:"subchannel_ref,omitempty"` - // There are no ordering guarantees on the order of sockets. - SocketRef []*SocketRef `protobuf:"bytes,5,rep,name=socket_ref,json=socketRef,proto3" json:"socket_ref,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Subchannel) Reset() { *m = Subchannel{} } -func (m *Subchannel) String() string { return proto.CompactTextString(m) } -func (*Subchannel) ProtoMessage() {} -func (*Subchannel) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{1} -} -func (m *Subchannel) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Subchannel.Unmarshal(m, b) -} -func (m *Subchannel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Subchannel.Marshal(b, m, deterministic) -} -func (dst *Subchannel) XXX_Merge(src proto.Message) { - xxx_messageInfo_Subchannel.Merge(dst, src) -} -func (m *Subchannel) XXX_Size() int { - return xxx_messageInfo_Subchannel.Size(m) -} -func (m *Subchannel) XXX_DiscardUnknown() { - xxx_messageInfo_Subchannel.DiscardUnknown(m) -} - -var xxx_messageInfo_Subchannel proto.InternalMessageInfo - -func (m *Subchannel) GetRef() *SubchannelRef { - if m != nil { - return m.Ref - } - return nil -} - -func (m *Subchannel) GetData() *ChannelData { - if m != nil { - return m.Data - } - return nil -} - -func (m *Subchannel) GetChannelRef() []*ChannelRef { - if m != nil { - return m.ChannelRef - } - return nil -} - -func (m *Subchannel) GetSubchannelRef() []*SubchannelRef { - if m != nil { - return m.SubchannelRef - } - return nil -} - -func (m *Subchannel) GetSocketRef() []*SocketRef { - if m != nil { - return m.SocketRef - } - return nil -} - -// These come from the specified states in this document: -// https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md -type ChannelConnectivityState struct { - State ChannelConnectivityState_State `protobuf:"varint,1,opt,name=state,proto3,enum=grpc.channelz.v1.ChannelConnectivityState_State" json:"state,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChannelConnectivityState) Reset() { *m = ChannelConnectivityState{} } -func (m *ChannelConnectivityState) String() string { return proto.CompactTextString(m) } -func (*ChannelConnectivityState) ProtoMessage() {} -func (*ChannelConnectivityState) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{2} -} -func (m *ChannelConnectivityState) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChannelConnectivityState.Unmarshal(m, b) -} -func (m *ChannelConnectivityState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChannelConnectivityState.Marshal(b, m, deterministic) -} -func (dst *ChannelConnectivityState) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChannelConnectivityState.Merge(dst, src) -} -func (m *ChannelConnectivityState) XXX_Size() int { - return xxx_messageInfo_ChannelConnectivityState.Size(m) -} -func (m *ChannelConnectivityState) XXX_DiscardUnknown() { - xxx_messageInfo_ChannelConnectivityState.DiscardUnknown(m) -} - -var xxx_messageInfo_ChannelConnectivityState proto.InternalMessageInfo - -func (m *ChannelConnectivityState) GetState() ChannelConnectivityState_State { - if m != nil { - return m.State - } - return ChannelConnectivityState_UNKNOWN -} - -// Channel data is data related to a specific Channel or Subchannel. -type ChannelData struct { - // The connectivity state of the channel or subchannel. Implementations - // should always set this. - State *ChannelConnectivityState `protobuf:"bytes,1,opt,name=state,proto3" json:"state,omitempty"` - // The target this channel originally tried to connect to. May be absent - Target string `protobuf:"bytes,2,opt,name=target,proto3" json:"target,omitempty"` - // A trace of recent events on the channel. May be absent. - Trace *ChannelTrace `protobuf:"bytes,3,opt,name=trace,proto3" json:"trace,omitempty"` - // The number of calls started on the channel - CallsStarted int64 `protobuf:"varint,4,opt,name=calls_started,json=callsStarted,proto3" json:"calls_started,omitempty"` - // The number of calls that have completed with an OK status - CallsSucceeded int64 `protobuf:"varint,5,opt,name=calls_succeeded,json=callsSucceeded,proto3" json:"calls_succeeded,omitempty"` - // The number of calls that have completed with a non-OK status - CallsFailed int64 `protobuf:"varint,6,opt,name=calls_failed,json=callsFailed,proto3" json:"calls_failed,omitempty"` - // The last time a call was started on the channel. - LastCallStartedTimestamp *timestamp.Timestamp `protobuf:"bytes,7,opt,name=last_call_started_timestamp,json=lastCallStartedTimestamp,proto3" json:"last_call_started_timestamp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChannelData) Reset() { *m = ChannelData{} } -func (m *ChannelData) String() string { return proto.CompactTextString(m) } -func (*ChannelData) ProtoMessage() {} -func (*ChannelData) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{3} -} -func (m *ChannelData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChannelData.Unmarshal(m, b) -} -func (m *ChannelData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChannelData.Marshal(b, m, deterministic) -} -func (dst *ChannelData) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChannelData.Merge(dst, src) -} -func (m *ChannelData) XXX_Size() int { - return xxx_messageInfo_ChannelData.Size(m) -} -func (m *ChannelData) XXX_DiscardUnknown() { - xxx_messageInfo_ChannelData.DiscardUnknown(m) -} - -var xxx_messageInfo_ChannelData proto.InternalMessageInfo - -func (m *ChannelData) GetState() *ChannelConnectivityState { - if m != nil { - return m.State - } - return nil -} - -func (m *ChannelData) GetTarget() string { - if m != nil { - return m.Target - } - return "" -} - -func (m *ChannelData) GetTrace() *ChannelTrace { - if m != nil { - return m.Trace - } - return nil -} - -func (m *ChannelData) GetCallsStarted() int64 { - if m != nil { - return m.CallsStarted - } - return 0 -} - -func (m *ChannelData) GetCallsSucceeded() int64 { - if m != nil { - return m.CallsSucceeded - } - return 0 -} - -func (m *ChannelData) GetCallsFailed() int64 { - if m != nil { - return m.CallsFailed - } - return 0 -} - -func (m *ChannelData) GetLastCallStartedTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastCallStartedTimestamp - } - return nil -} - -// A trace event is an interesting thing that happened to a channel or -// subchannel, such as creation, address resolution, subchannel creation, etc. -type ChannelTraceEvent struct { - // High level description of the event. - Description string `protobuf:"bytes,1,opt,name=description,proto3" json:"description,omitempty"` - // the severity of the trace event - Severity ChannelTraceEvent_Severity `protobuf:"varint,2,opt,name=severity,proto3,enum=grpc.channelz.v1.ChannelTraceEvent_Severity" json:"severity,omitempty"` - // When this event occurred. - Timestamp *timestamp.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // 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. - // - // Types that are valid to be assigned to ChildRef: - // *ChannelTraceEvent_ChannelRef - // *ChannelTraceEvent_SubchannelRef - ChildRef isChannelTraceEvent_ChildRef `protobuf_oneof:"child_ref"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChannelTraceEvent) Reset() { *m = ChannelTraceEvent{} } -func (m *ChannelTraceEvent) String() string { return proto.CompactTextString(m) } -func (*ChannelTraceEvent) ProtoMessage() {} -func (*ChannelTraceEvent) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{4} -} -func (m *ChannelTraceEvent) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChannelTraceEvent.Unmarshal(m, b) -} -func (m *ChannelTraceEvent) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChannelTraceEvent.Marshal(b, m, deterministic) -} -func (dst *ChannelTraceEvent) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChannelTraceEvent.Merge(dst, src) -} -func (m *ChannelTraceEvent) XXX_Size() int { - return xxx_messageInfo_ChannelTraceEvent.Size(m) -} -func (m *ChannelTraceEvent) XXX_DiscardUnknown() { - xxx_messageInfo_ChannelTraceEvent.DiscardUnknown(m) -} - -var xxx_messageInfo_ChannelTraceEvent proto.InternalMessageInfo - -type isChannelTraceEvent_ChildRef interface { - isChannelTraceEvent_ChildRef() -} - -type ChannelTraceEvent_ChannelRef struct { - ChannelRef *ChannelRef `protobuf:"bytes,4,opt,name=channel_ref,json=channelRef,proto3,oneof"` -} -type ChannelTraceEvent_SubchannelRef struct { - SubchannelRef *SubchannelRef `protobuf:"bytes,5,opt,name=subchannel_ref,json=subchannelRef,proto3,oneof"` -} - -func (*ChannelTraceEvent_ChannelRef) isChannelTraceEvent_ChildRef() {} -func (*ChannelTraceEvent_SubchannelRef) isChannelTraceEvent_ChildRef() {} - -func (m *ChannelTraceEvent) GetChildRef() isChannelTraceEvent_ChildRef { - if m != nil { - return m.ChildRef - } - return nil -} - -func (m *ChannelTraceEvent) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *ChannelTraceEvent) GetSeverity() ChannelTraceEvent_Severity { - if m != nil { - return m.Severity - } - return ChannelTraceEvent_CT_UNKNOWN -} - -func (m *ChannelTraceEvent) GetTimestamp() *timestamp.Timestamp { - if m != nil { - return m.Timestamp - } - return nil -} - -func (m *ChannelTraceEvent) GetChannelRef() *ChannelRef { - if x, ok := m.GetChildRef().(*ChannelTraceEvent_ChannelRef); ok { - return x.ChannelRef - } - return nil -} - -func (m *ChannelTraceEvent) GetSubchannelRef() *SubchannelRef { - if x, ok := m.GetChildRef().(*ChannelTraceEvent_SubchannelRef); ok { - return x.SubchannelRef - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ChannelTraceEvent) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ChannelTraceEvent_OneofMarshaler, _ChannelTraceEvent_OneofUnmarshaler, _ChannelTraceEvent_OneofSizer, []interface{}{ - (*ChannelTraceEvent_ChannelRef)(nil), - (*ChannelTraceEvent_SubchannelRef)(nil), - } -} - -func _ChannelTraceEvent_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ChannelTraceEvent) - // child_ref - switch x := m.ChildRef.(type) { - case *ChannelTraceEvent_ChannelRef: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ChannelRef); err != nil { - return err - } - case *ChannelTraceEvent_SubchannelRef: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.SubchannelRef); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ChannelTraceEvent.ChildRef has unexpected type %T", x) - } - return nil -} - -func _ChannelTraceEvent_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ChannelTraceEvent) - switch tag { - case 4: // child_ref.channel_ref - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ChannelRef) - err := b.DecodeMessage(msg) - m.ChildRef = &ChannelTraceEvent_ChannelRef{msg} - return true, err - case 5: // child_ref.subchannel_ref - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(SubchannelRef) - err := b.DecodeMessage(msg) - m.ChildRef = &ChannelTraceEvent_SubchannelRef{msg} - return true, err - default: - return false, nil - } -} - -func _ChannelTraceEvent_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ChannelTraceEvent) - // child_ref - switch x := m.ChildRef.(type) { - case *ChannelTraceEvent_ChannelRef: - s := proto.Size(x.ChannelRef) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ChannelTraceEvent_SubchannelRef: - s := proto.Size(x.SubchannelRef) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// ChannelTrace represents the recent events that have occurred on the channel. -type ChannelTrace struct { - // 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. - NumEventsLogged int64 `protobuf:"varint,1,opt,name=num_events_logged,json=numEventsLogged,proto3" json:"num_events_logged,omitempty"` - // Time that this channel was created. - CreationTimestamp *timestamp.Timestamp `protobuf:"bytes,2,opt,name=creation_timestamp,json=creationTimestamp,proto3" json:"creation_timestamp,omitempty"` - // List of events that have occurred on this channel. - Events []*ChannelTraceEvent `protobuf:"bytes,3,rep,name=events,proto3" json:"events,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChannelTrace) Reset() { *m = ChannelTrace{} } -func (m *ChannelTrace) String() string { return proto.CompactTextString(m) } -func (*ChannelTrace) ProtoMessage() {} -func (*ChannelTrace) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{5} -} -func (m *ChannelTrace) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChannelTrace.Unmarshal(m, b) -} -func (m *ChannelTrace) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChannelTrace.Marshal(b, m, deterministic) -} -func (dst *ChannelTrace) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChannelTrace.Merge(dst, src) -} -func (m *ChannelTrace) XXX_Size() int { - return xxx_messageInfo_ChannelTrace.Size(m) -} -func (m *ChannelTrace) XXX_DiscardUnknown() { - xxx_messageInfo_ChannelTrace.DiscardUnknown(m) -} - -var xxx_messageInfo_ChannelTrace proto.InternalMessageInfo - -func (m *ChannelTrace) GetNumEventsLogged() int64 { - if m != nil { - return m.NumEventsLogged - } - return 0 -} - -func (m *ChannelTrace) GetCreationTimestamp() *timestamp.Timestamp { - if m != nil { - return m.CreationTimestamp - } - return nil -} - -func (m *ChannelTrace) GetEvents() []*ChannelTraceEvent { - if m != nil { - return m.Events - } - return nil -} - -// ChannelRef is a reference to a Channel. -type ChannelRef struct { - // The globally unique id for this channel. Must be a positive number. - ChannelId int64 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` - // An optional name associated with the channel. - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ChannelRef) Reset() { *m = ChannelRef{} } -func (m *ChannelRef) String() string { return proto.CompactTextString(m) } -func (*ChannelRef) ProtoMessage() {} -func (*ChannelRef) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{6} -} -func (m *ChannelRef) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ChannelRef.Unmarshal(m, b) -} -func (m *ChannelRef) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ChannelRef.Marshal(b, m, deterministic) -} -func (dst *ChannelRef) XXX_Merge(src proto.Message) { - xxx_messageInfo_ChannelRef.Merge(dst, src) -} -func (m *ChannelRef) XXX_Size() int { - return xxx_messageInfo_ChannelRef.Size(m) -} -func (m *ChannelRef) XXX_DiscardUnknown() { - xxx_messageInfo_ChannelRef.DiscardUnknown(m) -} - -var xxx_messageInfo_ChannelRef proto.InternalMessageInfo - -func (m *ChannelRef) GetChannelId() int64 { - if m != nil { - return m.ChannelId - } - return 0 -} - -func (m *ChannelRef) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// ChannelRef is a reference to a Subchannel. -type SubchannelRef struct { - // The globally unique id for this subchannel. Must be a positive number. - SubchannelId int64 `protobuf:"varint,7,opt,name=subchannel_id,json=subchannelId,proto3" json:"subchannel_id,omitempty"` - // An optional name associated with the subchannel. - Name string `protobuf:"bytes,8,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SubchannelRef) Reset() { *m = SubchannelRef{} } -func (m *SubchannelRef) String() string { return proto.CompactTextString(m) } -func (*SubchannelRef) ProtoMessage() {} -func (*SubchannelRef) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{7} -} -func (m *SubchannelRef) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SubchannelRef.Unmarshal(m, b) -} -func (m *SubchannelRef) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SubchannelRef.Marshal(b, m, deterministic) -} -func (dst *SubchannelRef) XXX_Merge(src proto.Message) { - xxx_messageInfo_SubchannelRef.Merge(dst, src) -} -func (m *SubchannelRef) XXX_Size() int { - return xxx_messageInfo_SubchannelRef.Size(m) -} -func (m *SubchannelRef) XXX_DiscardUnknown() { - xxx_messageInfo_SubchannelRef.DiscardUnknown(m) -} - -var xxx_messageInfo_SubchannelRef proto.InternalMessageInfo - -func (m *SubchannelRef) GetSubchannelId() int64 { - if m != nil { - return m.SubchannelId - } - return 0 -} - -func (m *SubchannelRef) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// SocketRef is a reference to a Socket. -type SocketRef struct { - SocketId int64 `protobuf:"varint,3,opt,name=socket_id,json=socketId,proto3" json:"socket_id,omitempty"` - // An optional name associated with the socket. - Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketRef) Reset() { *m = SocketRef{} } -func (m *SocketRef) String() string { return proto.CompactTextString(m) } -func (*SocketRef) ProtoMessage() {} -func (*SocketRef) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{8} -} -func (m *SocketRef) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketRef.Unmarshal(m, b) -} -func (m *SocketRef) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketRef.Marshal(b, m, deterministic) -} -func (dst *SocketRef) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketRef.Merge(dst, src) -} -func (m *SocketRef) XXX_Size() int { - return xxx_messageInfo_SocketRef.Size(m) -} -func (m *SocketRef) XXX_DiscardUnknown() { - xxx_messageInfo_SocketRef.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketRef proto.InternalMessageInfo - -func (m *SocketRef) GetSocketId() int64 { - if m != nil { - return m.SocketId - } - return 0 -} - -func (m *SocketRef) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// ServerRef is a reference to a Server. -type ServerRef struct { - // A globally unique identifier for this server. Must be a positive number. - ServerId int64 `protobuf:"varint,5,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` - // An optional name associated with the server. - Name string `protobuf:"bytes,6,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerRef) Reset() { *m = ServerRef{} } -func (m *ServerRef) String() string { return proto.CompactTextString(m) } -func (*ServerRef) ProtoMessage() {} -func (*ServerRef) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{9} -} -func (m *ServerRef) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerRef.Unmarshal(m, b) -} -func (m *ServerRef) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerRef.Marshal(b, m, deterministic) -} -func (dst *ServerRef) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerRef.Merge(dst, src) -} -func (m *ServerRef) XXX_Size() int { - return xxx_messageInfo_ServerRef.Size(m) -} -func (m *ServerRef) XXX_DiscardUnknown() { - xxx_messageInfo_ServerRef.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerRef proto.InternalMessageInfo - -func (m *ServerRef) GetServerId() int64 { - if m != nil { - return m.ServerId - } - return 0 -} - -func (m *ServerRef) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// Server represents a single server. There may be multiple servers in a single -// program. -type Server struct { - // The identifier for a Server. This should be set. - Ref *ServerRef `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` - // The associated data of the Server. - Data *ServerData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` - // The sockets that the server is listening on. There are no ordering - // guarantees. This may be absent. - ListenSocket []*SocketRef `protobuf:"bytes,3,rep,name=listen_socket,json=listenSocket,proto3" json:"listen_socket,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{10} -} -func (m *Server) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Server.Unmarshal(m, b) -} -func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Server.Marshal(b, m, deterministic) -} -func (dst *Server) XXX_Merge(src proto.Message) { - xxx_messageInfo_Server.Merge(dst, src) -} -func (m *Server) XXX_Size() int { - return xxx_messageInfo_Server.Size(m) -} -func (m *Server) XXX_DiscardUnknown() { - xxx_messageInfo_Server.DiscardUnknown(m) -} - -var xxx_messageInfo_Server proto.InternalMessageInfo - -func (m *Server) GetRef() *ServerRef { - if m != nil { - return m.Ref - } - return nil -} - -func (m *Server) GetData() *ServerData { - if m != nil { - return m.Data - } - return nil -} - -func (m *Server) GetListenSocket() []*SocketRef { - if m != nil { - return m.ListenSocket - } - return nil -} - -// ServerData is data for a specific Server. -type ServerData struct { - // A trace of recent events on the server. May be absent. - Trace *ChannelTrace `protobuf:"bytes,1,opt,name=trace,proto3" json:"trace,omitempty"` - // The number of incoming calls started on the server - CallsStarted int64 `protobuf:"varint,2,opt,name=calls_started,json=callsStarted,proto3" json:"calls_started,omitempty"` - // The number of incoming calls that have completed with an OK status - CallsSucceeded int64 `protobuf:"varint,3,opt,name=calls_succeeded,json=callsSucceeded,proto3" json:"calls_succeeded,omitempty"` - // The number of incoming calls that have a completed with a non-OK status - CallsFailed int64 `protobuf:"varint,4,opt,name=calls_failed,json=callsFailed,proto3" json:"calls_failed,omitempty"` - // The last time a call was started on the server. - LastCallStartedTimestamp *timestamp.Timestamp `protobuf:"bytes,5,opt,name=last_call_started_timestamp,json=lastCallStartedTimestamp,proto3" json:"last_call_started_timestamp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerData) Reset() { *m = ServerData{} } -func (m *ServerData) String() string { return proto.CompactTextString(m) } -func (*ServerData) ProtoMessage() {} -func (*ServerData) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{11} -} -func (m *ServerData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerData.Unmarshal(m, b) -} -func (m *ServerData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerData.Marshal(b, m, deterministic) -} -func (dst *ServerData) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerData.Merge(dst, src) -} -func (m *ServerData) XXX_Size() int { - return xxx_messageInfo_ServerData.Size(m) -} -func (m *ServerData) XXX_DiscardUnknown() { - xxx_messageInfo_ServerData.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerData proto.InternalMessageInfo - -func (m *ServerData) GetTrace() *ChannelTrace { - if m != nil { - return m.Trace - } - return nil -} - -func (m *ServerData) GetCallsStarted() int64 { - if m != nil { - return m.CallsStarted - } - return 0 -} - -func (m *ServerData) GetCallsSucceeded() int64 { - if m != nil { - return m.CallsSucceeded - } - return 0 -} - -func (m *ServerData) GetCallsFailed() int64 { - if m != nil { - return m.CallsFailed - } - return 0 -} - -func (m *ServerData) GetLastCallStartedTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastCallStartedTimestamp - } - return nil -} - -// Information about an actual connection. Pronounced "sock-ay". -type Socket struct { - // The identifier for the Socket. - Ref *SocketRef `protobuf:"bytes,1,opt,name=ref,proto3" json:"ref,omitempty"` - // Data specific to this Socket. - Data *SocketData `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` - // The locally bound address. - Local *Address `protobuf:"bytes,3,opt,name=local,proto3" json:"local,omitempty"` - // The remote bound address. May be absent. - Remote *Address `protobuf:"bytes,4,opt,name=remote,proto3" json:"remote,omitempty"` - // Security details for this socket. May be absent if not available, or - // there is no security on the socket. - Security *Security `protobuf:"bytes,5,opt,name=security,proto3" json:"security,omitempty"` - // Optional, represents the name of the remote endpoint, if different than - // the original target name. - RemoteName string `protobuf:"bytes,6,opt,name=remote_name,json=remoteName,proto3" json:"remote_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Socket) Reset() { *m = Socket{} } -func (m *Socket) String() string { return proto.CompactTextString(m) } -func (*Socket) ProtoMessage() {} -func (*Socket) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{12} -} -func (m *Socket) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Socket.Unmarshal(m, b) -} -func (m *Socket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Socket.Marshal(b, m, deterministic) -} -func (dst *Socket) XXX_Merge(src proto.Message) { - xxx_messageInfo_Socket.Merge(dst, src) -} -func (m *Socket) XXX_Size() int { - return xxx_messageInfo_Socket.Size(m) -} -func (m *Socket) XXX_DiscardUnknown() { - xxx_messageInfo_Socket.DiscardUnknown(m) -} - -var xxx_messageInfo_Socket proto.InternalMessageInfo - -func (m *Socket) GetRef() *SocketRef { - if m != nil { - return m.Ref - } - return nil -} - -func (m *Socket) GetData() *SocketData { - if m != nil { - return m.Data - } - return nil -} - -func (m *Socket) GetLocal() *Address { - if m != nil { - return m.Local - } - return nil -} - -func (m *Socket) GetRemote() *Address { - if m != nil { - return m.Remote - } - return nil -} - -func (m *Socket) GetSecurity() *Security { - if m != nil { - return m.Security - } - return nil -} - -func (m *Socket) GetRemoteName() string { - if m != nil { - return m.RemoteName - } - return "" -} - -// 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) -type SocketData struct { - // The number of streams that have been started. - StreamsStarted int64 `protobuf:"varint,1,opt,name=streams_started,json=streamsStarted,proto3" json:"streams_started,omitempty"` - // 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. - StreamsSucceeded int64 `protobuf:"varint,2,opt,name=streams_succeeded,json=streamsSucceeded,proto3" json:"streams_succeeded,omitempty"` - // 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. - StreamsFailed int64 `protobuf:"varint,3,opt,name=streams_failed,json=streamsFailed,proto3" json:"streams_failed,omitempty"` - // The number of grpc messages successfully sent on this socket. - MessagesSent int64 `protobuf:"varint,4,opt,name=messages_sent,json=messagesSent,proto3" json:"messages_sent,omitempty"` - // The number of grpc messages received on this socket. - MessagesReceived int64 `protobuf:"varint,5,opt,name=messages_received,json=messagesReceived,proto3" json:"messages_received,omitempty"` - // The number of keep alives sent. This is typically implemented with HTTP/2 - // ping messages. - KeepAlivesSent int64 `protobuf:"varint,6,opt,name=keep_alives_sent,json=keepAlivesSent,proto3" json:"keep_alives_sent,omitempty"` - // The last time a stream was created by this endpoint. Usually unset for - // servers. - LastLocalStreamCreatedTimestamp *timestamp.Timestamp `protobuf:"bytes,7,opt,name=last_local_stream_created_timestamp,json=lastLocalStreamCreatedTimestamp,proto3" json:"last_local_stream_created_timestamp,omitempty"` - // The last time a stream was created by the remote endpoint. Usually unset - // for clients. - LastRemoteStreamCreatedTimestamp *timestamp.Timestamp `protobuf:"bytes,8,opt,name=last_remote_stream_created_timestamp,json=lastRemoteStreamCreatedTimestamp,proto3" json:"last_remote_stream_created_timestamp,omitempty"` - // The last time a message was sent by this endpoint. - LastMessageSentTimestamp *timestamp.Timestamp `protobuf:"bytes,9,opt,name=last_message_sent_timestamp,json=lastMessageSentTimestamp,proto3" json:"last_message_sent_timestamp,omitempty"` - // The last time a message was received by this endpoint. - LastMessageReceivedTimestamp *timestamp.Timestamp `protobuf:"bytes,10,opt,name=last_message_received_timestamp,json=lastMessageReceivedTimestamp,proto3" json:"last_message_received_timestamp,omitempty"` - // 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. - LocalFlowControlWindow *wrappers.Int64Value `protobuf:"bytes,11,opt,name=local_flow_control_window,json=localFlowControlWindow,proto3" json:"local_flow_control_window,omitempty"` - // 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. - RemoteFlowControlWindow *wrappers.Int64Value `protobuf:"bytes,12,opt,name=remote_flow_control_window,json=remoteFlowControlWindow,proto3" json:"remote_flow_control_window,omitempty"` - // Socket options set on this socket. May be absent. - Option []*SocketOption `protobuf:"bytes,13,rep,name=option,proto3" json:"option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketData) Reset() { *m = SocketData{} } -func (m *SocketData) String() string { return proto.CompactTextString(m) } -func (*SocketData) ProtoMessage() {} -func (*SocketData) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{13} -} -func (m *SocketData) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketData.Unmarshal(m, b) -} -func (m *SocketData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketData.Marshal(b, m, deterministic) -} -func (dst *SocketData) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketData.Merge(dst, src) -} -func (m *SocketData) XXX_Size() int { - return xxx_messageInfo_SocketData.Size(m) -} -func (m *SocketData) XXX_DiscardUnknown() { - xxx_messageInfo_SocketData.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketData proto.InternalMessageInfo - -func (m *SocketData) GetStreamsStarted() int64 { - if m != nil { - return m.StreamsStarted - } - return 0 -} - -func (m *SocketData) GetStreamsSucceeded() int64 { - if m != nil { - return m.StreamsSucceeded - } - return 0 -} - -func (m *SocketData) GetStreamsFailed() int64 { - if m != nil { - return m.StreamsFailed - } - return 0 -} - -func (m *SocketData) GetMessagesSent() int64 { - if m != nil { - return m.MessagesSent - } - return 0 -} - -func (m *SocketData) GetMessagesReceived() int64 { - if m != nil { - return m.MessagesReceived - } - return 0 -} - -func (m *SocketData) GetKeepAlivesSent() int64 { - if m != nil { - return m.KeepAlivesSent - } - return 0 -} - -func (m *SocketData) GetLastLocalStreamCreatedTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastLocalStreamCreatedTimestamp - } - return nil -} - -func (m *SocketData) GetLastRemoteStreamCreatedTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastRemoteStreamCreatedTimestamp - } - return nil -} - -func (m *SocketData) GetLastMessageSentTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastMessageSentTimestamp - } - return nil -} - -func (m *SocketData) GetLastMessageReceivedTimestamp() *timestamp.Timestamp { - if m != nil { - return m.LastMessageReceivedTimestamp - } - return nil -} - -func (m *SocketData) GetLocalFlowControlWindow() *wrappers.Int64Value { - if m != nil { - return m.LocalFlowControlWindow - } - return nil -} - -func (m *SocketData) GetRemoteFlowControlWindow() *wrappers.Int64Value { - if m != nil { - return m.RemoteFlowControlWindow - } - return nil -} - -func (m *SocketData) GetOption() []*SocketOption { - if m != nil { - return m.Option - } - return nil -} - -// Address represents the address used to create the socket. -type Address struct { - // Types that are valid to be assigned to Address: - // *Address_TcpipAddress - // *Address_UdsAddress_ - // *Address_OtherAddress_ - Address isAddress_Address `protobuf_oneof:"address"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Address) Reset() { *m = Address{} } -func (m *Address) String() string { return proto.CompactTextString(m) } -func (*Address) ProtoMessage() {} -func (*Address) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{14} -} -func (m *Address) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Address.Unmarshal(m, b) -} -func (m *Address) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Address.Marshal(b, m, deterministic) -} -func (dst *Address) XXX_Merge(src proto.Message) { - xxx_messageInfo_Address.Merge(dst, src) -} -func (m *Address) XXX_Size() int { - return xxx_messageInfo_Address.Size(m) -} -func (m *Address) XXX_DiscardUnknown() { - xxx_messageInfo_Address.DiscardUnknown(m) -} - -var xxx_messageInfo_Address proto.InternalMessageInfo - -type isAddress_Address interface { - isAddress_Address() -} - -type Address_TcpipAddress struct { - TcpipAddress *Address_TcpIpAddress `protobuf:"bytes,1,opt,name=tcpip_address,json=tcpipAddress,proto3,oneof"` -} -type Address_UdsAddress_ struct { - UdsAddress *Address_UdsAddress `protobuf:"bytes,2,opt,name=uds_address,json=udsAddress,proto3,oneof"` -} -type Address_OtherAddress_ struct { - OtherAddress *Address_OtherAddress `protobuf:"bytes,3,opt,name=other_address,json=otherAddress,proto3,oneof"` -} - -func (*Address_TcpipAddress) isAddress_Address() {} -func (*Address_UdsAddress_) isAddress_Address() {} -func (*Address_OtherAddress_) isAddress_Address() {} - -func (m *Address) GetAddress() isAddress_Address { - if m != nil { - return m.Address - } - return nil -} - -func (m *Address) GetTcpipAddress() *Address_TcpIpAddress { - if x, ok := m.GetAddress().(*Address_TcpipAddress); ok { - return x.TcpipAddress - } - return nil -} - -func (m *Address) GetUdsAddress() *Address_UdsAddress { - if x, ok := m.GetAddress().(*Address_UdsAddress_); ok { - return x.UdsAddress - } - return nil -} - -func (m *Address) GetOtherAddress() *Address_OtherAddress { - if x, ok := m.GetAddress().(*Address_OtherAddress_); ok { - return x.OtherAddress - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Address) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Address_OneofMarshaler, _Address_OneofUnmarshaler, _Address_OneofSizer, []interface{}{ - (*Address_TcpipAddress)(nil), - (*Address_UdsAddress_)(nil), - (*Address_OtherAddress_)(nil), - } -} - -func _Address_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Address) - // address - switch x := m.Address.(type) { - case *Address_TcpipAddress: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.TcpipAddress); err != nil { - return err - } - case *Address_UdsAddress_: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.UdsAddress); err != nil { - return err - } - case *Address_OtherAddress_: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.OtherAddress); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("Address.Address has unexpected type %T", x) - } - return nil -} - -func _Address_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Address) - switch tag { - case 1: // address.tcpip_address - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Address_TcpIpAddress) - err := b.DecodeMessage(msg) - m.Address = &Address_TcpipAddress{msg} - return true, err - case 2: // address.uds_address - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Address_UdsAddress) - err := b.DecodeMessage(msg) - m.Address = &Address_UdsAddress_{msg} - return true, err - case 3: // address.other_address - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Address_OtherAddress) - err := b.DecodeMessage(msg) - m.Address = &Address_OtherAddress_{msg} - return true, err - default: - return false, nil - } -} - -func _Address_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Address) - // address - switch x := m.Address.(type) { - case *Address_TcpipAddress: - s := proto.Size(x.TcpipAddress) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Address_UdsAddress_: - s := proto.Size(x.UdsAddress) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Address_OtherAddress_: - s := proto.Size(x.OtherAddress) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Address_TcpIpAddress struct { - // Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 - // bytes in length. - IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // 0-64k, or -1 if not appropriate. - Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Address_TcpIpAddress) Reset() { *m = Address_TcpIpAddress{} } -func (m *Address_TcpIpAddress) String() string { return proto.CompactTextString(m) } -func (*Address_TcpIpAddress) ProtoMessage() {} -func (*Address_TcpIpAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{14, 0} -} -func (m *Address_TcpIpAddress) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Address_TcpIpAddress.Unmarshal(m, b) -} -func (m *Address_TcpIpAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Address_TcpIpAddress.Marshal(b, m, deterministic) -} -func (dst *Address_TcpIpAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_Address_TcpIpAddress.Merge(dst, src) -} -func (m *Address_TcpIpAddress) XXX_Size() int { - return xxx_messageInfo_Address_TcpIpAddress.Size(m) -} -func (m *Address_TcpIpAddress) XXX_DiscardUnknown() { - xxx_messageInfo_Address_TcpIpAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_Address_TcpIpAddress proto.InternalMessageInfo - -func (m *Address_TcpIpAddress) GetIpAddress() []byte { - if m != nil { - return m.IpAddress - } - return nil -} - -func (m *Address_TcpIpAddress) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -// A Unix Domain Socket address. -type Address_UdsAddress struct { - Filename string `protobuf:"bytes,1,opt,name=filename,proto3" json:"filename,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Address_UdsAddress) Reset() { *m = Address_UdsAddress{} } -func (m *Address_UdsAddress) String() string { return proto.CompactTextString(m) } -func (*Address_UdsAddress) ProtoMessage() {} -func (*Address_UdsAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{14, 1} -} -func (m *Address_UdsAddress) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Address_UdsAddress.Unmarshal(m, b) -} -func (m *Address_UdsAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Address_UdsAddress.Marshal(b, m, deterministic) -} -func (dst *Address_UdsAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_Address_UdsAddress.Merge(dst, src) -} -func (m *Address_UdsAddress) XXX_Size() int { - return xxx_messageInfo_Address_UdsAddress.Size(m) -} -func (m *Address_UdsAddress) XXX_DiscardUnknown() { - xxx_messageInfo_Address_UdsAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_Address_UdsAddress proto.InternalMessageInfo - -func (m *Address_UdsAddress) GetFilename() string { - if m != nil { - return m.Filename - } - return "" -} - -// An address type not included above. -type Address_OtherAddress struct { - // The human readable version of the value. This value should be set. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // The actual address message. - Value *any.Any `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Address_OtherAddress) Reset() { *m = Address_OtherAddress{} } -func (m *Address_OtherAddress) String() string { return proto.CompactTextString(m) } -func (*Address_OtherAddress) ProtoMessage() {} -func (*Address_OtherAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{14, 2} -} -func (m *Address_OtherAddress) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Address_OtherAddress.Unmarshal(m, b) -} -func (m *Address_OtherAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Address_OtherAddress.Marshal(b, m, deterministic) -} -func (dst *Address_OtherAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_Address_OtherAddress.Merge(dst, src) -} -func (m *Address_OtherAddress) XXX_Size() int { - return xxx_messageInfo_Address_OtherAddress.Size(m) -} -func (m *Address_OtherAddress) XXX_DiscardUnknown() { - xxx_messageInfo_Address_OtherAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_Address_OtherAddress proto.InternalMessageInfo - -func (m *Address_OtherAddress) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Address_OtherAddress) GetValue() *any.Any { - if m != nil { - return m.Value - } - return nil -} - -// Security represents details about how secure the socket is. -type Security struct { - // Types that are valid to be assigned to Model: - // *Security_Tls_ - // *Security_Other - Model isSecurity_Model `protobuf_oneof:"model"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Security) Reset() { *m = Security{} } -func (m *Security) String() string { return proto.CompactTextString(m) } -func (*Security) ProtoMessage() {} -func (*Security) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{15} -} -func (m *Security) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Security.Unmarshal(m, b) -} -func (m *Security) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Security.Marshal(b, m, deterministic) -} -func (dst *Security) XXX_Merge(src proto.Message) { - xxx_messageInfo_Security.Merge(dst, src) -} -func (m *Security) XXX_Size() int { - return xxx_messageInfo_Security.Size(m) -} -func (m *Security) XXX_DiscardUnknown() { - xxx_messageInfo_Security.DiscardUnknown(m) -} - -var xxx_messageInfo_Security proto.InternalMessageInfo - -type isSecurity_Model interface { - isSecurity_Model() -} - -type Security_Tls_ struct { - Tls *Security_Tls `protobuf:"bytes,1,opt,name=tls,proto3,oneof"` -} -type Security_Other struct { - Other *Security_OtherSecurity `protobuf:"bytes,2,opt,name=other,proto3,oneof"` -} - -func (*Security_Tls_) isSecurity_Model() {} -func (*Security_Other) isSecurity_Model() {} - -func (m *Security) GetModel() isSecurity_Model { - if m != nil { - return m.Model - } - return nil -} - -func (m *Security) GetTls() *Security_Tls { - if x, ok := m.GetModel().(*Security_Tls_); ok { - return x.Tls - } - return nil -} - -func (m *Security) GetOther() *Security_OtherSecurity { - if x, ok := m.GetModel().(*Security_Other); ok { - return x.Other - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Security) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Security_OneofMarshaler, _Security_OneofUnmarshaler, _Security_OneofSizer, []interface{}{ - (*Security_Tls_)(nil), - (*Security_Other)(nil), - } -} - -func _Security_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Security) - // model - switch x := m.Model.(type) { - case *Security_Tls_: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Tls); err != nil { - return err - } - case *Security_Other: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Other); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("Security.Model has unexpected type %T", x) - } - return nil -} - -func _Security_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Security) - switch tag { - case 1: // model.tls - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Security_Tls) - err := b.DecodeMessage(msg) - m.Model = &Security_Tls_{msg} - return true, err - case 2: // model.other - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Security_OtherSecurity) - err := b.DecodeMessage(msg) - m.Model = &Security_Other{msg} - return true, err - default: - return false, nil - } -} - -func _Security_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Security) - // model - switch x := m.Model.(type) { - case *Security_Tls_: - s := proto.Size(x.Tls) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *Security_Other: - s := proto.Size(x.Other) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Security_Tls struct { - // Types that are valid to be assigned to CipherSuite: - // *Security_Tls_StandardName - // *Security_Tls_OtherName - CipherSuite isSecurity_Tls_CipherSuite `protobuf_oneof:"cipher_suite"` - // the certificate used by this endpoint. - LocalCertificate []byte `protobuf:"bytes,3,opt,name=local_certificate,json=localCertificate,proto3" json:"local_certificate,omitempty"` - // the certificate used by the remote endpoint. - RemoteCertificate []byte `protobuf:"bytes,4,opt,name=remote_certificate,json=remoteCertificate,proto3" json:"remote_certificate,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Security_Tls) Reset() { *m = Security_Tls{} } -func (m *Security_Tls) String() string { return proto.CompactTextString(m) } -func (*Security_Tls) ProtoMessage() {} -func (*Security_Tls) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{15, 0} -} -func (m *Security_Tls) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Security_Tls.Unmarshal(m, b) -} -func (m *Security_Tls) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Security_Tls.Marshal(b, m, deterministic) -} -func (dst *Security_Tls) XXX_Merge(src proto.Message) { - xxx_messageInfo_Security_Tls.Merge(dst, src) -} -func (m *Security_Tls) XXX_Size() int { - return xxx_messageInfo_Security_Tls.Size(m) -} -func (m *Security_Tls) XXX_DiscardUnknown() { - xxx_messageInfo_Security_Tls.DiscardUnknown(m) -} - -var xxx_messageInfo_Security_Tls proto.InternalMessageInfo - -type isSecurity_Tls_CipherSuite interface { - isSecurity_Tls_CipherSuite() -} - -type Security_Tls_StandardName struct { - StandardName string `protobuf:"bytes,1,opt,name=standard_name,json=standardName,proto3,oneof"` -} -type Security_Tls_OtherName struct { - OtherName string `protobuf:"bytes,2,opt,name=other_name,json=otherName,proto3,oneof"` -} - -func (*Security_Tls_StandardName) isSecurity_Tls_CipherSuite() {} -func (*Security_Tls_OtherName) isSecurity_Tls_CipherSuite() {} - -func (m *Security_Tls) GetCipherSuite() isSecurity_Tls_CipherSuite { - if m != nil { - return m.CipherSuite - } - return nil -} - -func (m *Security_Tls) GetStandardName() string { - if x, ok := m.GetCipherSuite().(*Security_Tls_StandardName); ok { - return x.StandardName - } - return "" -} - -func (m *Security_Tls) GetOtherName() string { - if x, ok := m.GetCipherSuite().(*Security_Tls_OtherName); ok { - return x.OtherName - } - return "" -} - -func (m *Security_Tls) GetLocalCertificate() []byte { - if m != nil { - return m.LocalCertificate - } - return nil -} - -func (m *Security_Tls) GetRemoteCertificate() []byte { - if m != nil { - return m.RemoteCertificate - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Security_Tls) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Security_Tls_OneofMarshaler, _Security_Tls_OneofUnmarshaler, _Security_Tls_OneofSizer, []interface{}{ - (*Security_Tls_StandardName)(nil), - (*Security_Tls_OtherName)(nil), - } -} - -func _Security_Tls_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Security_Tls) - // cipher_suite - switch x := m.CipherSuite.(type) { - case *Security_Tls_StandardName: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.StandardName) - case *Security_Tls_OtherName: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.OtherName) - case nil: - default: - return fmt.Errorf("Security_Tls.CipherSuite has unexpected type %T", x) - } - return nil -} - -func _Security_Tls_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Security_Tls) - switch tag { - case 1: // cipher_suite.standard_name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.CipherSuite = &Security_Tls_StandardName{x} - return true, err - case 2: // cipher_suite.other_name - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.CipherSuite = &Security_Tls_OtherName{x} - return true, err - default: - return false, nil - } -} - -func _Security_Tls_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Security_Tls) - // cipher_suite - switch x := m.CipherSuite.(type) { - case *Security_Tls_StandardName: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.StandardName))) - n += len(x.StandardName) - case *Security_Tls_OtherName: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.OtherName))) - n += len(x.OtherName) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type Security_OtherSecurity struct { - // The human readable version of the value. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // The actual security details message. - Value *any.Any `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Security_OtherSecurity) Reset() { *m = Security_OtherSecurity{} } -func (m *Security_OtherSecurity) String() string { return proto.CompactTextString(m) } -func (*Security_OtherSecurity) ProtoMessage() {} -func (*Security_OtherSecurity) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{15, 1} -} -func (m *Security_OtherSecurity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Security_OtherSecurity.Unmarshal(m, b) -} -func (m *Security_OtherSecurity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Security_OtherSecurity.Marshal(b, m, deterministic) -} -func (dst *Security_OtherSecurity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Security_OtherSecurity.Merge(dst, src) -} -func (m *Security_OtherSecurity) XXX_Size() int { - return xxx_messageInfo_Security_OtherSecurity.Size(m) -} -func (m *Security_OtherSecurity) XXX_DiscardUnknown() { - xxx_messageInfo_Security_OtherSecurity.DiscardUnknown(m) -} - -var xxx_messageInfo_Security_OtherSecurity proto.InternalMessageInfo - -func (m *Security_OtherSecurity) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Security_OtherSecurity) GetValue() *any.Any { - if m != nil { - return m.Value - } - return nil -} - -// SocketOption represents socket options for a socket. Specifically, these -// are the options returned by getsockopt(). -type SocketOption struct { - // The full name of the socket option. Typically this will be the upper case - // name, such as "SO_REUSEPORT". - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // The human readable value of this socket option. At least one of value or - // additional will be set. - Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - // Additional data associated with the socket option. At least one of value - // or additional will be set. - Additional *any.Any `protobuf:"bytes,3,opt,name=additional,proto3" json:"additional,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketOption) Reset() { *m = SocketOption{} } -func (m *SocketOption) String() string { return proto.CompactTextString(m) } -func (*SocketOption) ProtoMessage() {} -func (*SocketOption) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{16} -} -func (m *SocketOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketOption.Unmarshal(m, b) -} -func (m *SocketOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketOption.Marshal(b, m, deterministic) -} -func (dst *SocketOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketOption.Merge(dst, src) -} -func (m *SocketOption) XXX_Size() int { - return xxx_messageInfo_SocketOption.Size(m) -} -func (m *SocketOption) XXX_DiscardUnknown() { - xxx_messageInfo_SocketOption.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketOption proto.InternalMessageInfo - -func (m *SocketOption) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *SocketOption) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -func (m *SocketOption) GetAdditional() *any.Any { - if m != nil { - return m.Additional - } - return nil -} - -// For use with SocketOption's additional field. This is primarily used for -// SO_RCVTIMEO and SO_SNDTIMEO -type SocketOptionTimeout struct { - Duration *duration.Duration `protobuf:"bytes,1,opt,name=duration,proto3" json:"duration,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketOptionTimeout) Reset() { *m = SocketOptionTimeout{} } -func (m *SocketOptionTimeout) String() string { return proto.CompactTextString(m) } -func (*SocketOptionTimeout) ProtoMessage() {} -func (*SocketOptionTimeout) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{17} -} -func (m *SocketOptionTimeout) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketOptionTimeout.Unmarshal(m, b) -} -func (m *SocketOptionTimeout) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketOptionTimeout.Marshal(b, m, deterministic) -} -func (dst *SocketOptionTimeout) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketOptionTimeout.Merge(dst, src) -} -func (m *SocketOptionTimeout) XXX_Size() int { - return xxx_messageInfo_SocketOptionTimeout.Size(m) -} -func (m *SocketOptionTimeout) XXX_DiscardUnknown() { - xxx_messageInfo_SocketOptionTimeout.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketOptionTimeout proto.InternalMessageInfo - -func (m *SocketOptionTimeout) GetDuration() *duration.Duration { - if m != nil { - return m.Duration - } - return nil -} - -// For use with SocketOption's additional field. This is primarily used for -// SO_LINGER. -type SocketOptionLinger struct { - // active maps to `struct linger.l_onoff` - Active bool `protobuf:"varint,1,opt,name=active,proto3" json:"active,omitempty"` - // duration maps to `struct linger.l_linger` - Duration *duration.Duration `protobuf:"bytes,2,opt,name=duration,proto3" json:"duration,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketOptionLinger) Reset() { *m = SocketOptionLinger{} } -func (m *SocketOptionLinger) String() string { return proto.CompactTextString(m) } -func (*SocketOptionLinger) ProtoMessage() {} -func (*SocketOptionLinger) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{18} -} -func (m *SocketOptionLinger) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketOptionLinger.Unmarshal(m, b) -} -func (m *SocketOptionLinger) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketOptionLinger.Marshal(b, m, deterministic) -} -func (dst *SocketOptionLinger) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketOptionLinger.Merge(dst, src) -} -func (m *SocketOptionLinger) XXX_Size() int { - return xxx_messageInfo_SocketOptionLinger.Size(m) -} -func (m *SocketOptionLinger) XXX_DiscardUnknown() { - xxx_messageInfo_SocketOptionLinger.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketOptionLinger proto.InternalMessageInfo - -func (m *SocketOptionLinger) GetActive() bool { - if m != nil { - return m.Active - } - return false -} - -func (m *SocketOptionLinger) GetDuration() *duration.Duration { - if m != nil { - return m.Duration - } - return nil -} - -// For use with SocketOption's additional field. Tcp info for -// SOL_TCP and TCP_INFO. -type SocketOptionTcpInfo struct { - TcpiState uint32 `protobuf:"varint,1,opt,name=tcpi_state,json=tcpiState,proto3" json:"tcpi_state,omitempty"` - TcpiCaState uint32 `protobuf:"varint,2,opt,name=tcpi_ca_state,json=tcpiCaState,proto3" json:"tcpi_ca_state,omitempty"` - TcpiRetransmits uint32 `protobuf:"varint,3,opt,name=tcpi_retransmits,json=tcpiRetransmits,proto3" json:"tcpi_retransmits,omitempty"` - TcpiProbes uint32 `protobuf:"varint,4,opt,name=tcpi_probes,json=tcpiProbes,proto3" json:"tcpi_probes,omitempty"` - TcpiBackoff uint32 `protobuf:"varint,5,opt,name=tcpi_backoff,json=tcpiBackoff,proto3" json:"tcpi_backoff,omitempty"` - TcpiOptions uint32 `protobuf:"varint,6,opt,name=tcpi_options,json=tcpiOptions,proto3" json:"tcpi_options,omitempty"` - TcpiSndWscale uint32 `protobuf:"varint,7,opt,name=tcpi_snd_wscale,json=tcpiSndWscale,proto3" json:"tcpi_snd_wscale,omitempty"` - TcpiRcvWscale uint32 `protobuf:"varint,8,opt,name=tcpi_rcv_wscale,json=tcpiRcvWscale,proto3" json:"tcpi_rcv_wscale,omitempty"` - TcpiRto uint32 `protobuf:"varint,9,opt,name=tcpi_rto,json=tcpiRto,proto3" json:"tcpi_rto,omitempty"` - TcpiAto uint32 `protobuf:"varint,10,opt,name=tcpi_ato,json=tcpiAto,proto3" json:"tcpi_ato,omitempty"` - TcpiSndMss uint32 `protobuf:"varint,11,opt,name=tcpi_snd_mss,json=tcpiSndMss,proto3" json:"tcpi_snd_mss,omitempty"` - TcpiRcvMss uint32 `protobuf:"varint,12,opt,name=tcpi_rcv_mss,json=tcpiRcvMss,proto3" json:"tcpi_rcv_mss,omitempty"` - TcpiUnacked uint32 `protobuf:"varint,13,opt,name=tcpi_unacked,json=tcpiUnacked,proto3" json:"tcpi_unacked,omitempty"` - TcpiSacked uint32 `protobuf:"varint,14,opt,name=tcpi_sacked,json=tcpiSacked,proto3" json:"tcpi_sacked,omitempty"` - TcpiLost uint32 `protobuf:"varint,15,opt,name=tcpi_lost,json=tcpiLost,proto3" json:"tcpi_lost,omitempty"` - TcpiRetrans uint32 `protobuf:"varint,16,opt,name=tcpi_retrans,json=tcpiRetrans,proto3" json:"tcpi_retrans,omitempty"` - TcpiFackets uint32 `protobuf:"varint,17,opt,name=tcpi_fackets,json=tcpiFackets,proto3" json:"tcpi_fackets,omitempty"` - TcpiLastDataSent uint32 `protobuf:"varint,18,opt,name=tcpi_last_data_sent,json=tcpiLastDataSent,proto3" json:"tcpi_last_data_sent,omitempty"` - TcpiLastAckSent uint32 `protobuf:"varint,19,opt,name=tcpi_last_ack_sent,json=tcpiLastAckSent,proto3" json:"tcpi_last_ack_sent,omitempty"` - TcpiLastDataRecv uint32 `protobuf:"varint,20,opt,name=tcpi_last_data_recv,json=tcpiLastDataRecv,proto3" json:"tcpi_last_data_recv,omitempty"` - TcpiLastAckRecv uint32 `protobuf:"varint,21,opt,name=tcpi_last_ack_recv,json=tcpiLastAckRecv,proto3" json:"tcpi_last_ack_recv,omitempty"` - TcpiPmtu uint32 `protobuf:"varint,22,opt,name=tcpi_pmtu,json=tcpiPmtu,proto3" json:"tcpi_pmtu,omitempty"` - TcpiRcvSsthresh uint32 `protobuf:"varint,23,opt,name=tcpi_rcv_ssthresh,json=tcpiRcvSsthresh,proto3" json:"tcpi_rcv_ssthresh,omitempty"` - TcpiRtt uint32 `protobuf:"varint,24,opt,name=tcpi_rtt,json=tcpiRtt,proto3" json:"tcpi_rtt,omitempty"` - TcpiRttvar uint32 `protobuf:"varint,25,opt,name=tcpi_rttvar,json=tcpiRttvar,proto3" json:"tcpi_rttvar,omitempty"` - TcpiSndSsthresh uint32 `protobuf:"varint,26,opt,name=tcpi_snd_ssthresh,json=tcpiSndSsthresh,proto3" json:"tcpi_snd_ssthresh,omitempty"` - TcpiSndCwnd uint32 `protobuf:"varint,27,opt,name=tcpi_snd_cwnd,json=tcpiSndCwnd,proto3" json:"tcpi_snd_cwnd,omitempty"` - TcpiAdvmss uint32 `protobuf:"varint,28,opt,name=tcpi_advmss,json=tcpiAdvmss,proto3" json:"tcpi_advmss,omitempty"` - TcpiReordering uint32 `protobuf:"varint,29,opt,name=tcpi_reordering,json=tcpiReordering,proto3" json:"tcpi_reordering,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SocketOptionTcpInfo) Reset() { *m = SocketOptionTcpInfo{} } -func (m *SocketOptionTcpInfo) String() string { return proto.CompactTextString(m) } -func (*SocketOptionTcpInfo) ProtoMessage() {} -func (*SocketOptionTcpInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{19} -} -func (m *SocketOptionTcpInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SocketOptionTcpInfo.Unmarshal(m, b) -} -func (m *SocketOptionTcpInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SocketOptionTcpInfo.Marshal(b, m, deterministic) -} -func (dst *SocketOptionTcpInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SocketOptionTcpInfo.Merge(dst, src) -} -func (m *SocketOptionTcpInfo) XXX_Size() int { - return xxx_messageInfo_SocketOptionTcpInfo.Size(m) -} -func (m *SocketOptionTcpInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SocketOptionTcpInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SocketOptionTcpInfo proto.InternalMessageInfo - -func (m *SocketOptionTcpInfo) GetTcpiState() uint32 { - if m != nil { - return m.TcpiState - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiCaState() uint32 { - if m != nil { - return m.TcpiCaState - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRetransmits() uint32 { - if m != nil { - return m.TcpiRetransmits - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiProbes() uint32 { - if m != nil { - return m.TcpiProbes - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiBackoff() uint32 { - if m != nil { - return m.TcpiBackoff - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiOptions() uint32 { - if m != nil { - return m.TcpiOptions - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiSndWscale() uint32 { - if m != nil { - return m.TcpiSndWscale - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRcvWscale() uint32 { - if m != nil { - return m.TcpiRcvWscale - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRto() uint32 { - if m != nil { - return m.TcpiRto - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiAto() uint32 { - if m != nil { - return m.TcpiAto - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiSndMss() uint32 { - if m != nil { - return m.TcpiSndMss - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRcvMss() uint32 { - if m != nil { - return m.TcpiRcvMss - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiUnacked() uint32 { - if m != nil { - return m.TcpiUnacked - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiSacked() uint32 { - if m != nil { - return m.TcpiSacked - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiLost() uint32 { - if m != nil { - return m.TcpiLost - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRetrans() uint32 { - if m != nil { - return m.TcpiRetrans - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiFackets() uint32 { - if m != nil { - return m.TcpiFackets - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiLastDataSent() uint32 { - if m != nil { - return m.TcpiLastDataSent - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiLastAckSent() uint32 { - if m != nil { - return m.TcpiLastAckSent - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiLastDataRecv() uint32 { - if m != nil { - return m.TcpiLastDataRecv - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiLastAckRecv() uint32 { - if m != nil { - return m.TcpiLastAckRecv - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiPmtu() uint32 { - if m != nil { - return m.TcpiPmtu - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRcvSsthresh() uint32 { - if m != nil { - return m.TcpiRcvSsthresh - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRtt() uint32 { - if m != nil { - return m.TcpiRtt - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiRttvar() uint32 { - if m != nil { - return m.TcpiRttvar - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiSndSsthresh() uint32 { - if m != nil { - return m.TcpiSndSsthresh - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiSndCwnd() uint32 { - if m != nil { - return m.TcpiSndCwnd - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiAdvmss() uint32 { - if m != nil { - return m.TcpiAdvmss - } - return 0 -} - -func (m *SocketOptionTcpInfo) GetTcpiReordering() uint32 { - if m != nil { - return m.TcpiReordering - } - return 0 -} - -type GetTopChannelsRequest struct { - // start_channel_id indicates that only channels at or above this id should be - // included in the results. - StartChannelId int64 `protobuf:"varint,1,opt,name=start_channel_id,json=startChannelId,proto3" json:"start_channel_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetTopChannelsRequest) Reset() { *m = GetTopChannelsRequest{} } -func (m *GetTopChannelsRequest) String() string { return proto.CompactTextString(m) } -func (*GetTopChannelsRequest) ProtoMessage() {} -func (*GetTopChannelsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{20} -} -func (m *GetTopChannelsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetTopChannelsRequest.Unmarshal(m, b) -} -func (m *GetTopChannelsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetTopChannelsRequest.Marshal(b, m, deterministic) -} -func (dst *GetTopChannelsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetTopChannelsRequest.Merge(dst, src) -} -func (m *GetTopChannelsRequest) XXX_Size() int { - return xxx_messageInfo_GetTopChannelsRequest.Size(m) -} -func (m *GetTopChannelsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetTopChannelsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetTopChannelsRequest proto.InternalMessageInfo - -func (m *GetTopChannelsRequest) GetStartChannelId() int64 { - if m != nil { - return m.StartChannelId - } - return 0 -} - -type GetTopChannelsResponse struct { - // list of channels that the connection detail service knows about. Sorted in - // ascending channel_id order. - Channel []*Channel `protobuf:"bytes,1,rep,name=channel,proto3" json:"channel,omitempty"` - // If set, indicates that the list of channels is the final list. Requesting - // more channels can only return more if they are created after this RPC - // completes. - End bool `protobuf:"varint,2,opt,name=end,proto3" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetTopChannelsResponse) Reset() { *m = GetTopChannelsResponse{} } -func (m *GetTopChannelsResponse) String() string { return proto.CompactTextString(m) } -func (*GetTopChannelsResponse) ProtoMessage() {} -func (*GetTopChannelsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{21} -} -func (m *GetTopChannelsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetTopChannelsResponse.Unmarshal(m, b) -} -func (m *GetTopChannelsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetTopChannelsResponse.Marshal(b, m, deterministic) -} -func (dst *GetTopChannelsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetTopChannelsResponse.Merge(dst, src) -} -func (m *GetTopChannelsResponse) XXX_Size() int { - return xxx_messageInfo_GetTopChannelsResponse.Size(m) -} -func (m *GetTopChannelsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetTopChannelsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetTopChannelsResponse proto.InternalMessageInfo - -func (m *GetTopChannelsResponse) GetChannel() []*Channel { - if m != nil { - return m.Channel - } - return nil -} - -func (m *GetTopChannelsResponse) GetEnd() bool { - if m != nil { - return m.End - } - return false -} - -type GetServersRequest struct { - // start_server_id indicates that only servers at or above this id should be - // included in the results. - StartServerId int64 `protobuf:"varint,1,opt,name=start_server_id,json=startServerId,proto3" json:"start_server_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetServersRequest) Reset() { *m = GetServersRequest{} } -func (m *GetServersRequest) String() string { return proto.CompactTextString(m) } -func (*GetServersRequest) ProtoMessage() {} -func (*GetServersRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{22} -} -func (m *GetServersRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetServersRequest.Unmarshal(m, b) -} -func (m *GetServersRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetServersRequest.Marshal(b, m, deterministic) -} -func (dst *GetServersRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetServersRequest.Merge(dst, src) -} -func (m *GetServersRequest) XXX_Size() int { - return xxx_messageInfo_GetServersRequest.Size(m) -} -func (m *GetServersRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetServersRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetServersRequest proto.InternalMessageInfo - -func (m *GetServersRequest) GetStartServerId() int64 { - if m != nil { - return m.StartServerId - } - return 0 -} - -type GetServersResponse struct { - // list of servers that the connection detail service knows about. Sorted in - // ascending server_id order. - Server []*Server `protobuf:"bytes,1,rep,name=server,proto3" json:"server,omitempty"` - // 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. - End bool `protobuf:"varint,2,opt,name=end,proto3" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetServersResponse) Reset() { *m = GetServersResponse{} } -func (m *GetServersResponse) String() string { return proto.CompactTextString(m) } -func (*GetServersResponse) ProtoMessage() {} -func (*GetServersResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{23} -} -func (m *GetServersResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetServersResponse.Unmarshal(m, b) -} -func (m *GetServersResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetServersResponse.Marshal(b, m, deterministic) -} -func (dst *GetServersResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetServersResponse.Merge(dst, src) -} -func (m *GetServersResponse) XXX_Size() int { - return xxx_messageInfo_GetServersResponse.Size(m) -} -func (m *GetServersResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetServersResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetServersResponse proto.InternalMessageInfo - -func (m *GetServersResponse) GetServer() []*Server { - if m != nil { - return m.Server - } - return nil -} - -func (m *GetServersResponse) GetEnd() bool { - if m != nil { - return m.End - } - return false -} - -type GetServerSocketsRequest struct { - ServerId int64 `protobuf:"varint,1,opt,name=server_id,json=serverId,proto3" json:"server_id,omitempty"` - // start_socket_id indicates that only sockets at or above this id should be - // included in the results. - StartSocketId int64 `protobuf:"varint,2,opt,name=start_socket_id,json=startSocketId,proto3" json:"start_socket_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetServerSocketsRequest) Reset() { *m = GetServerSocketsRequest{} } -func (m *GetServerSocketsRequest) String() string { return proto.CompactTextString(m) } -func (*GetServerSocketsRequest) ProtoMessage() {} -func (*GetServerSocketsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{24} -} -func (m *GetServerSocketsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetServerSocketsRequest.Unmarshal(m, b) -} -func (m *GetServerSocketsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetServerSocketsRequest.Marshal(b, m, deterministic) -} -func (dst *GetServerSocketsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetServerSocketsRequest.Merge(dst, src) -} -func (m *GetServerSocketsRequest) XXX_Size() int { - return xxx_messageInfo_GetServerSocketsRequest.Size(m) -} -func (m *GetServerSocketsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetServerSocketsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetServerSocketsRequest proto.InternalMessageInfo - -func (m *GetServerSocketsRequest) GetServerId() int64 { - if m != nil { - return m.ServerId - } - return 0 -} - -func (m *GetServerSocketsRequest) GetStartSocketId() int64 { - if m != nil { - return m.StartSocketId - } - return 0 -} - -type GetServerSocketsResponse struct { - // list of socket refs that the connection detail service knows about. Sorted in - // ascending socket_id order. - SocketRef []*SocketRef `protobuf:"bytes,1,rep,name=socket_ref,json=socketRef,proto3" json:"socket_ref,omitempty"` - // 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. - End bool `protobuf:"varint,2,opt,name=end,proto3" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetServerSocketsResponse) Reset() { *m = GetServerSocketsResponse{} } -func (m *GetServerSocketsResponse) String() string { return proto.CompactTextString(m) } -func (*GetServerSocketsResponse) ProtoMessage() {} -func (*GetServerSocketsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{25} -} -func (m *GetServerSocketsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetServerSocketsResponse.Unmarshal(m, b) -} -func (m *GetServerSocketsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetServerSocketsResponse.Marshal(b, m, deterministic) -} -func (dst *GetServerSocketsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetServerSocketsResponse.Merge(dst, src) -} -func (m *GetServerSocketsResponse) XXX_Size() int { - return xxx_messageInfo_GetServerSocketsResponse.Size(m) -} -func (m *GetServerSocketsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetServerSocketsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetServerSocketsResponse proto.InternalMessageInfo - -func (m *GetServerSocketsResponse) GetSocketRef() []*SocketRef { - if m != nil { - return m.SocketRef - } - return nil -} - -func (m *GetServerSocketsResponse) GetEnd() bool { - if m != nil { - return m.End - } - return false -} - -type GetChannelRequest struct { - // channel_id is the identifier of the specific channel to get. - ChannelId int64 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetChannelRequest) Reset() { *m = GetChannelRequest{} } -func (m *GetChannelRequest) String() string { return proto.CompactTextString(m) } -func (*GetChannelRequest) ProtoMessage() {} -func (*GetChannelRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{26} -} -func (m *GetChannelRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetChannelRequest.Unmarshal(m, b) -} -func (m *GetChannelRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetChannelRequest.Marshal(b, m, deterministic) -} -func (dst *GetChannelRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetChannelRequest.Merge(dst, src) -} -func (m *GetChannelRequest) XXX_Size() int { - return xxx_messageInfo_GetChannelRequest.Size(m) -} -func (m *GetChannelRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetChannelRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetChannelRequest proto.InternalMessageInfo - -func (m *GetChannelRequest) GetChannelId() int64 { - if m != nil { - return m.ChannelId - } - return 0 -} - -type GetChannelResponse struct { - // The Channel that corresponds to the requested channel_id. This field - // should be set. - Channel *Channel `protobuf:"bytes,1,opt,name=channel,proto3" json:"channel,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetChannelResponse) Reset() { *m = GetChannelResponse{} } -func (m *GetChannelResponse) String() string { return proto.CompactTextString(m) } -func (*GetChannelResponse) ProtoMessage() {} -func (*GetChannelResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{27} -} -func (m *GetChannelResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetChannelResponse.Unmarshal(m, b) -} -func (m *GetChannelResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetChannelResponse.Marshal(b, m, deterministic) -} -func (dst *GetChannelResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetChannelResponse.Merge(dst, src) -} -func (m *GetChannelResponse) XXX_Size() int { - return xxx_messageInfo_GetChannelResponse.Size(m) -} -func (m *GetChannelResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetChannelResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetChannelResponse proto.InternalMessageInfo - -func (m *GetChannelResponse) GetChannel() *Channel { - if m != nil { - return m.Channel - } - return nil -} - -type GetSubchannelRequest struct { - // subchannel_id is the identifier of the specific subchannel to get. - SubchannelId int64 `protobuf:"varint,1,opt,name=subchannel_id,json=subchannelId,proto3" json:"subchannel_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetSubchannelRequest) Reset() { *m = GetSubchannelRequest{} } -func (m *GetSubchannelRequest) String() string { return proto.CompactTextString(m) } -func (*GetSubchannelRequest) ProtoMessage() {} -func (*GetSubchannelRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{28} -} -func (m *GetSubchannelRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetSubchannelRequest.Unmarshal(m, b) -} -func (m *GetSubchannelRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetSubchannelRequest.Marshal(b, m, deterministic) -} -func (dst *GetSubchannelRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetSubchannelRequest.Merge(dst, src) -} -func (m *GetSubchannelRequest) XXX_Size() int { - return xxx_messageInfo_GetSubchannelRequest.Size(m) -} -func (m *GetSubchannelRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetSubchannelRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetSubchannelRequest proto.InternalMessageInfo - -func (m *GetSubchannelRequest) GetSubchannelId() int64 { - if m != nil { - return m.SubchannelId - } - return 0 -} - -type GetSubchannelResponse struct { - // The Subchannel that corresponds to the requested subchannel_id. This - // field should be set. - Subchannel *Subchannel `protobuf:"bytes,1,opt,name=subchannel,proto3" json:"subchannel,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetSubchannelResponse) Reset() { *m = GetSubchannelResponse{} } -func (m *GetSubchannelResponse) String() string { return proto.CompactTextString(m) } -func (*GetSubchannelResponse) ProtoMessage() {} -func (*GetSubchannelResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{29} -} -func (m *GetSubchannelResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetSubchannelResponse.Unmarshal(m, b) -} -func (m *GetSubchannelResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetSubchannelResponse.Marshal(b, m, deterministic) -} -func (dst *GetSubchannelResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetSubchannelResponse.Merge(dst, src) -} -func (m *GetSubchannelResponse) XXX_Size() int { - return xxx_messageInfo_GetSubchannelResponse.Size(m) -} -func (m *GetSubchannelResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetSubchannelResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetSubchannelResponse proto.InternalMessageInfo - -func (m *GetSubchannelResponse) GetSubchannel() *Subchannel { - if m != nil { - return m.Subchannel - } - return nil -} - -type GetSocketRequest struct { - // socket_id is the identifier of the specific socket to get. - SocketId int64 `protobuf:"varint,1,opt,name=socket_id,json=socketId,proto3" json:"socket_id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetSocketRequest) Reset() { *m = GetSocketRequest{} } -func (m *GetSocketRequest) String() string { return proto.CompactTextString(m) } -func (*GetSocketRequest) ProtoMessage() {} -func (*GetSocketRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{30} -} -func (m *GetSocketRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetSocketRequest.Unmarshal(m, b) -} -func (m *GetSocketRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetSocketRequest.Marshal(b, m, deterministic) -} -func (dst *GetSocketRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetSocketRequest.Merge(dst, src) -} -func (m *GetSocketRequest) XXX_Size() int { - return xxx_messageInfo_GetSocketRequest.Size(m) -} -func (m *GetSocketRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetSocketRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GetSocketRequest proto.InternalMessageInfo - -func (m *GetSocketRequest) GetSocketId() int64 { - if m != nil { - return m.SocketId - } - return 0 -} - -type GetSocketResponse struct { - // The Socket that corresponds to the requested socket_id. This field - // should be set. - Socket *Socket `protobuf:"bytes,1,opt,name=socket,proto3" json:"socket,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GetSocketResponse) Reset() { *m = GetSocketResponse{} } -func (m *GetSocketResponse) String() string { return proto.CompactTextString(m) } -func (*GetSocketResponse) ProtoMessage() {} -func (*GetSocketResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_channelz_ce3ed45d08251f2f, []int{31} -} -func (m *GetSocketResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetSocketResponse.Unmarshal(m, b) -} -func (m *GetSocketResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetSocketResponse.Marshal(b, m, deterministic) -} -func (dst *GetSocketResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetSocketResponse.Merge(dst, src) -} -func (m *GetSocketResponse) XXX_Size() int { - return xxx_messageInfo_GetSocketResponse.Size(m) -} -func (m *GetSocketResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GetSocketResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GetSocketResponse proto.InternalMessageInfo - -func (m *GetSocketResponse) GetSocket() *Socket { - if m != nil { - return m.Socket - } - return nil -} - -func init() { - proto.RegisterType((*Channel)(nil), "grpc.channelz.v1.Channel") - proto.RegisterType((*Subchannel)(nil), "grpc.channelz.v1.Subchannel") - proto.RegisterType((*ChannelConnectivityState)(nil), "grpc.channelz.v1.ChannelConnectivityState") - proto.RegisterType((*ChannelData)(nil), "grpc.channelz.v1.ChannelData") - proto.RegisterType((*ChannelTraceEvent)(nil), "grpc.channelz.v1.ChannelTraceEvent") - proto.RegisterType((*ChannelTrace)(nil), "grpc.channelz.v1.ChannelTrace") - proto.RegisterType((*ChannelRef)(nil), "grpc.channelz.v1.ChannelRef") - proto.RegisterType((*SubchannelRef)(nil), "grpc.channelz.v1.SubchannelRef") - proto.RegisterType((*SocketRef)(nil), "grpc.channelz.v1.SocketRef") - proto.RegisterType((*ServerRef)(nil), "grpc.channelz.v1.ServerRef") - proto.RegisterType((*Server)(nil), "grpc.channelz.v1.Server") - proto.RegisterType((*ServerData)(nil), "grpc.channelz.v1.ServerData") - proto.RegisterType((*Socket)(nil), "grpc.channelz.v1.Socket") - proto.RegisterType((*SocketData)(nil), "grpc.channelz.v1.SocketData") - proto.RegisterType((*Address)(nil), "grpc.channelz.v1.Address") - proto.RegisterType((*Address_TcpIpAddress)(nil), "grpc.channelz.v1.Address.TcpIpAddress") - proto.RegisterType((*Address_UdsAddress)(nil), "grpc.channelz.v1.Address.UdsAddress") - proto.RegisterType((*Address_OtherAddress)(nil), "grpc.channelz.v1.Address.OtherAddress") - proto.RegisterType((*Security)(nil), "grpc.channelz.v1.Security") - proto.RegisterType((*Security_Tls)(nil), "grpc.channelz.v1.Security.Tls") - proto.RegisterType((*Security_OtherSecurity)(nil), "grpc.channelz.v1.Security.OtherSecurity") - proto.RegisterType((*SocketOption)(nil), "grpc.channelz.v1.SocketOption") - proto.RegisterType((*SocketOptionTimeout)(nil), "grpc.channelz.v1.SocketOptionTimeout") - proto.RegisterType((*SocketOptionLinger)(nil), "grpc.channelz.v1.SocketOptionLinger") - proto.RegisterType((*SocketOptionTcpInfo)(nil), "grpc.channelz.v1.SocketOptionTcpInfo") - proto.RegisterType((*GetTopChannelsRequest)(nil), "grpc.channelz.v1.GetTopChannelsRequest") - proto.RegisterType((*GetTopChannelsResponse)(nil), "grpc.channelz.v1.GetTopChannelsResponse") - proto.RegisterType((*GetServersRequest)(nil), "grpc.channelz.v1.GetServersRequest") - proto.RegisterType((*GetServersResponse)(nil), "grpc.channelz.v1.GetServersResponse") - proto.RegisterType((*GetServerSocketsRequest)(nil), "grpc.channelz.v1.GetServerSocketsRequest") - proto.RegisterType((*GetServerSocketsResponse)(nil), "grpc.channelz.v1.GetServerSocketsResponse") - proto.RegisterType((*GetChannelRequest)(nil), "grpc.channelz.v1.GetChannelRequest") - proto.RegisterType((*GetChannelResponse)(nil), "grpc.channelz.v1.GetChannelResponse") - proto.RegisterType((*GetSubchannelRequest)(nil), "grpc.channelz.v1.GetSubchannelRequest") - proto.RegisterType((*GetSubchannelResponse)(nil), "grpc.channelz.v1.GetSubchannelResponse") - proto.RegisterType((*GetSocketRequest)(nil), "grpc.channelz.v1.GetSocketRequest") - proto.RegisterType((*GetSocketResponse)(nil), "grpc.channelz.v1.GetSocketResponse") - proto.RegisterEnum("grpc.channelz.v1.ChannelConnectivityState_State", ChannelConnectivityState_State_name, ChannelConnectivityState_State_value) - proto.RegisterEnum("grpc.channelz.v1.ChannelTraceEvent_Severity", ChannelTraceEvent_Severity_name, ChannelTraceEvent_Severity_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// ChannelzClient is the client API for Channelz service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ChannelzClient interface { - // Gets all root channels (i.e. channels the application has directly - // created). This does not include subchannels nor non-top level channels. - GetTopChannels(ctx context.Context, in *GetTopChannelsRequest, opts ...grpc.CallOption) (*GetTopChannelsResponse, error) - // Gets all servers that exist in the process. - GetServers(ctx context.Context, in *GetServersRequest, opts ...grpc.CallOption) (*GetServersResponse, error) - // Gets all server sockets that exist in the process. - GetServerSockets(ctx context.Context, in *GetServerSocketsRequest, opts ...grpc.CallOption) (*GetServerSocketsResponse, error) - // Returns a single Channel, or else a NOT_FOUND code. - GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) - // Returns a single Subchannel, or else a NOT_FOUND code. - GetSubchannel(ctx context.Context, in *GetSubchannelRequest, opts ...grpc.CallOption) (*GetSubchannelResponse, error) - // Returns a single Socket or else a NOT_FOUND code. - GetSocket(ctx context.Context, in *GetSocketRequest, opts ...grpc.CallOption) (*GetSocketResponse, error) -} - -type channelzClient struct { - cc *grpc.ClientConn -} - -func NewChannelzClient(cc *grpc.ClientConn) ChannelzClient { - return &channelzClient{cc} -} - -func (c *channelzClient) GetTopChannels(ctx context.Context, in *GetTopChannelsRequest, opts ...grpc.CallOption) (*GetTopChannelsResponse, error) { - out := new(GetTopChannelsResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetTopChannels", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *channelzClient) GetServers(ctx context.Context, in *GetServersRequest, opts ...grpc.CallOption) (*GetServersResponse, error) { - out := new(GetServersResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServers", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *channelzClient) GetServerSockets(ctx context.Context, in *GetServerSocketsRequest, opts ...grpc.CallOption) (*GetServerSocketsResponse, error) { - out := new(GetServerSocketsResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetServerSockets", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *channelzClient) GetChannel(ctx context.Context, in *GetChannelRequest, opts ...grpc.CallOption) (*GetChannelResponse, error) { - out := new(GetChannelResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetChannel", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *channelzClient) GetSubchannel(ctx context.Context, in *GetSubchannelRequest, opts ...grpc.CallOption) (*GetSubchannelResponse, error) { - out := new(GetSubchannelResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSubchannel", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *channelzClient) GetSocket(ctx context.Context, in *GetSocketRequest, opts ...grpc.CallOption) (*GetSocketResponse, error) { - out := new(GetSocketResponse) - err := c.cc.Invoke(ctx, "/grpc.channelz.v1.Channelz/GetSocket", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// ChannelzServer is the server API for Channelz service. -type ChannelzServer interface { - // Gets all root channels (i.e. channels the application has directly - // created). This does not include subchannels nor non-top level channels. - GetTopChannels(context.Context, *GetTopChannelsRequest) (*GetTopChannelsResponse, error) - // Gets all servers that exist in the process. - GetServers(context.Context, *GetServersRequest) (*GetServersResponse, error) - // Gets all server sockets that exist in the process. - GetServerSockets(context.Context, *GetServerSocketsRequest) (*GetServerSocketsResponse, error) - // Returns a single Channel, or else a NOT_FOUND code. - GetChannel(context.Context, *GetChannelRequest) (*GetChannelResponse, error) - // Returns a single Subchannel, or else a NOT_FOUND code. - GetSubchannel(context.Context, *GetSubchannelRequest) (*GetSubchannelResponse, error) - // Returns a single Socket or else a NOT_FOUND code. - GetSocket(context.Context, *GetSocketRequest) (*GetSocketResponse, error) -} - -func RegisterChannelzServer(s *grpc.Server, srv ChannelzServer) { - s.RegisterService(&_Channelz_serviceDesc, srv) -} - -func _Channelz_GetTopChannels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetTopChannelsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetTopChannels(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetTopChannels", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetTopChannels(ctx, req.(*GetTopChannelsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Channelz_GetServers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetServersRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetServers(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetServers", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetServers(ctx, req.(*GetServersRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Channelz_GetServerSockets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetServerSocketsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetServerSockets(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetServerSockets", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetServerSockets(ctx, req.(*GetServerSocketsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Channelz_GetChannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetChannelRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetChannel(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetChannel", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetChannel(ctx, req.(*GetChannelRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Channelz_GetSubchannel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetSubchannelRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetSubchannel(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetSubchannel", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetSubchannel(ctx, req.(*GetSubchannelRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Channelz_GetSocket_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetSocketRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(ChannelzServer).GetSocket(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.channelz.v1.Channelz/GetSocket", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(ChannelzServer).GetSocket(ctx, req.(*GetSocketRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Channelz_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.channelz.v1.Channelz", - HandlerType: (*ChannelzServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetTopChannels", - Handler: _Channelz_GetTopChannels_Handler, - }, - { - MethodName: "GetServers", - Handler: _Channelz_GetServers_Handler, - }, - { - MethodName: "GetServerSockets", - Handler: _Channelz_GetServerSockets_Handler, - }, - { - MethodName: "GetChannel", - Handler: _Channelz_GetChannel_Handler, - }, - { - MethodName: "GetSubchannel", - Handler: _Channelz_GetSubchannel_Handler, - }, - { - MethodName: "GetSocket", - Handler: _Channelz_GetSocket_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc/channelz/v1/channelz.proto", -} - -func init() { - proto.RegisterFile("grpc/channelz/v1/channelz.proto", fileDescriptor_channelz_ce3ed45d08251f2f) -} - -var fileDescriptor_channelz_ce3ed45d08251f2f = []byte{ - // 2515 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x59, 0x4b, 0x6f, 0xdb, 0xca, - 0x15, 0xb6, 0xde, 0xd4, 0xd1, 0x23, 0xf2, 0xe4, 0x45, 0x2b, 0x0f, 0xbb, 0x74, 0x6e, 0xe2, 0x9b, - 0x34, 0x72, 0xec, 0x9b, 0x06, 0x45, 0xd3, 0xa2, 0x57, 0x56, 0xec, 0x58, 0xae, 0x23, 0x07, 0x94, - 0x7c, 0x93, 0xdb, 0xc5, 0xe5, 0x65, 0xc8, 0xb1, 0xcc, 0x9a, 0x22, 0x55, 0xce, 0x48, 0x46, 0xb2, - 0xed, 0xbe, 0xcb, 0xa2, 0xbf, 0xa0, 0x9b, 0x2e, 0x0a, 0x14, 0x28, 0xd0, 0x6e, 0x8b, 0xfe, 0x99, - 0xfe, 0x8b, 0x62, 0x1e, 0x7c, 0xc8, 0x92, 0x2c, 0x07, 0x59, 0x76, 0x63, 0x88, 0x87, 0xdf, 0xf9, - 0xce, 0x99, 0xf3, 0x9a, 0xe1, 0x18, 0x56, 0xfb, 0xc1, 0xd0, 0xda, 0xb4, 0x4e, 0x4d, 0xcf, 0xc3, - 0xee, 0xa7, 0xcd, 0xf1, 0x56, 0xf4, 0xbb, 0x31, 0x0c, 0x7c, 0xea, 0xa3, 0x1a, 0x03, 0x34, 0x22, - 0xe1, 0x78, 0xab, 0xbe, 0xd2, 0xf7, 0xfd, 0xbe, 0x8b, 0x37, 0xf9, 0xfb, 0x0f, 0xa3, 0x93, 0x4d, - 0xd3, 0xfb, 0x28, 0xc0, 0xf5, 0xfb, 0x17, 0x5f, 0xd9, 0xa3, 0xc0, 0xa4, 0x8e, 0xef, 0xc9, 0xf7, - 0xab, 0x17, 0xdf, 0x53, 0x67, 0x80, 0x09, 0x35, 0x07, 0xc3, 0x79, 0x04, 0xe7, 0x81, 0x39, 0x1c, - 0xe2, 0x80, 0x88, 0xf7, 0xda, 0xdf, 0xd2, 0x50, 0x68, 0x09, 0x5f, 0x50, 0x03, 0x32, 0x01, 0x3e, - 0x51, 0x53, 0x6b, 0xa9, 0x8d, 0xd2, 0xf6, 0xdd, 0xc6, 0x45, 0x3f, 0x1b, 0x12, 0xa7, 0xe3, 0x13, - 0x9d, 0x01, 0xd1, 0x16, 0x64, 0x6d, 0x93, 0x9a, 0x6a, 0x9a, 0x2b, 0xdc, 0x9b, 0xab, 0xf0, 0xca, - 0xa4, 0xa6, 0xce, 0xa1, 0xe8, 0x57, 0x50, 0x92, 0x00, 0x83, 0x99, 0xca, 0xac, 0x65, 0x16, 0x9a, - 0x02, 0x2b, 0xfa, 0x8d, 0xf6, 0xa0, 0x4a, 0x46, 0x1f, 0x92, 0x0c, 0x59, 0xce, 0xb0, 0x3a, 0xcd, - 0xd0, 0x8d, 0x70, 0x8c, 0xa4, 0x42, 0x92, 0x8f, 0xe8, 0x17, 0x00, 0xc4, 0xb7, 0xce, 0x30, 0xe5, - 0x1c, 0x39, 0xce, 0x71, 0x67, 0x06, 0x07, 0xc7, 0x30, 0xfd, 0x22, 0x09, 0x7f, 0x6a, 0xff, 0x48, - 0x03, 0xc4, 0xe4, 0x68, 0x2b, 0x19, 0xb4, 0x85, 0x7e, 0xfc, 0x1f, 0xc7, 0xed, 0xdf, 0x29, 0x50, - 0xa5, 0x7b, 0x2d, 0xdf, 0xf3, 0xb0, 0x45, 0x9d, 0xb1, 0x43, 0x3f, 0x76, 0xa9, 0x49, 0x31, 0xda, - 0x83, 0x1c, 0x61, 0x3f, 0x78, 0x1c, 0xab, 0xdb, 0xcf, 0xe6, 0xae, 0x6c, 0x4a, 0xb5, 0xc1, 0xff, - 0xea, 0x42, 0x5d, 0xfb, 0x01, 0x72, 0x82, 0xb0, 0x04, 0x85, 0xe3, 0xce, 0x6f, 0x3a, 0x47, 0xef, - 0x3a, 0xb5, 0x25, 0xa4, 0x40, 0xb6, 0xfd, 0xea, 0x70, 0xb7, 0x96, 0x42, 0x55, 0x80, 0xd6, 0x51, - 0xa7, 0xb3, 0xdb, 0xea, 0xb5, 0x3b, 0xaf, 0x6b, 0x69, 0x54, 0x84, 0x9c, 0xbe, 0xdb, 0x7c, 0xf5, - 0x7d, 0x2d, 0x83, 0x6e, 0xc2, 0x72, 0x4f, 0x6f, 0x76, 0xba, 0xed, 0xdd, 0x4e, 0xcf, 0xd8, 0x6b, - 0xb6, 0x0f, 0x8f, 0xf5, 0xdd, 0x5a, 0x16, 0x95, 0x41, 0xe9, 0xee, 0x1f, 0xf7, 0x5e, 0x31, 0xa6, - 0x9c, 0xf6, 0xdf, 0x34, 0x94, 0x12, 0xd9, 0x41, 0xdf, 0x26, 0xfd, 0x2e, 0x6d, 0x3f, 0xbe, 0xba, - 0xdf, 0xd2, 0x63, 0x74, 0x0b, 0xf2, 0xd4, 0x0c, 0xfa, 0x98, 0xf2, 0x72, 0x28, 0xea, 0xf2, 0x09, - 0x3d, 0x87, 0x1c, 0x0d, 0x4c, 0x0b, 0xab, 0x19, 0xce, 0x7c, 0x7f, 0x2e, 0x73, 0x8f, 0xa1, 0x74, - 0x01, 0x46, 0xeb, 0x50, 0xb1, 0x4c, 0xd7, 0x25, 0x06, 0xa1, 0x66, 0x40, 0xb1, 0xad, 0x66, 0xd7, - 0x52, 0x1b, 0x19, 0xbd, 0xcc, 0x85, 0x5d, 0x21, 0x43, 0x8f, 0xe0, 0x9a, 0x04, 0x8d, 0x2c, 0x0b, - 0x63, 0x1b, 0xdb, 0x6a, 0x8e, 0xc3, 0xaa, 0x02, 0x16, 0x4a, 0xd1, 0x4f, 0x40, 0x28, 0x1a, 0x27, - 0xa6, 0xe3, 0x62, 0x5b, 0xcd, 0x73, 0x54, 0x89, 0xcb, 0xf6, 0xb8, 0x08, 0x7d, 0x0f, 0x77, 0x5c, - 0x93, 0x50, 0x83, 0xc9, 0x42, 0xa3, 0x46, 0x34, 0x84, 0xd4, 0x02, 0x77, 0xbe, 0xde, 0x10, 0x53, - 0xa8, 0x11, 0x4e, 0xa1, 0x46, 0x2f, 0x44, 0xe8, 0x2a, 0x53, 0x6f, 0x99, 0xae, 0x2b, 0xbd, 0x8b, - 0xde, 0x68, 0x7f, 0xce, 0xc0, 0x72, 0x72, 0x8d, 0xbb, 0x63, 0xec, 0x51, 0xb4, 0x06, 0x25, 0x1b, - 0x13, 0x2b, 0x70, 0x86, 0x6c, 0x0c, 0xf2, 0xb8, 0x17, 0xf5, 0xa4, 0x08, 0xed, 0x83, 0x42, 0xf0, - 0x18, 0x07, 0x0e, 0xfd, 0xc8, 0x63, 0x5a, 0xdd, 0xfe, 0xe9, 0xe5, 0xc1, 0xe3, 0xc4, 0x8d, 0xae, - 0xd4, 0xd1, 0x23, 0x6d, 0xf4, 0x73, 0x28, 0xc6, 0x4b, 0xc9, 0x2c, 0x5c, 0x4a, 0x0c, 0x46, 0xbf, - 0x9e, 0xec, 0xd7, 0xec, 0xe2, 0x91, 0xba, 0xbf, 0x34, 0xd1, 0xb1, 0xfb, 0x53, 0x1d, 0x9b, 0xbb, - 0xd2, 0x84, 0xd9, 0x5f, 0xba, 0xd0, 0xb3, 0xda, 0x2e, 0x28, 0xe1, 0xd2, 0x78, 0xf9, 0xf7, 0x8c, - 0xb8, 0x31, 0x4a, 0x50, 0x68, 0xf5, 0x8c, 0x76, 0x67, 0xef, 0x48, 0xf6, 0x46, 0xcf, 0x78, 0xd7, - 0xd4, 0x3b, 0xa2, 0x37, 0xca, 0xa0, 0xb4, 0x7a, 0xc6, 0xae, 0xae, 0x1f, 0xe9, 0xb5, 0xcc, 0x4e, - 0x09, 0x8a, 0xd6, 0xa9, 0xe3, 0xda, 0xcc, 0x17, 0xd6, 0xcb, 0xe5, 0x64, 0x04, 0xd1, 0x63, 0x58, - 0xf6, 0x46, 0x03, 0x03, 0xb3, 0x48, 0x12, 0xc3, 0xf5, 0xfb, 0x7d, 0x6c, 0xf3, 0xdc, 0x64, 0xf4, - 0x6b, 0xde, 0x68, 0xc0, 0x23, 0x4c, 0x0e, 0xb9, 0x18, 0xb5, 0x01, 0x59, 0x01, 0xe6, 0xbb, 0x58, - 0xa2, 0x52, 0xd2, 0x0b, 0xc3, 0xbb, 0x1c, 0x6a, 0x45, 0x22, 0xf4, 0x12, 0xf2, 0xc2, 0xa4, 0x9c, - 0x88, 0xeb, 0x57, 0x48, 0xb4, 0x2e, 0x55, 0x34, 0x0b, 0x20, 0x0e, 0x3f, 0xba, 0x07, 0x61, 0xf8, - 0x0d, 0x27, 0x74, 0xbd, 0x28, 0x25, 0x6d, 0x1b, 0x21, 0xc8, 0x7a, 0xe6, 0x00, 0xcb, 0x26, 0xe5, - 0xbf, 0x0f, 0xb2, 0x4a, 0xa6, 0x96, 0x3d, 0xc8, 0x2a, 0xd9, 0x5a, 0xee, 0x20, 0xab, 0xe4, 0x6a, - 0xf9, 0x83, 0xac, 0x92, 0xaf, 0x15, 0x0e, 0xb2, 0x4a, 0xa1, 0xa6, 0x1c, 0x64, 0x15, 0xa5, 0x56, - 0xd4, 0x5c, 0xa8, 0x4c, 0xe4, 0x87, 0x75, 0x68, 0x22, 0xb1, 0x8e, 0xcd, 0x5b, 0x24, 0xa3, 0x97, - 0x63, 0x61, 0xc2, 0x9a, 0x32, 0x61, 0x2d, 0x55, 0x4b, 0x1f, 0x64, 0x95, 0x74, 0x2d, 0x33, 0xcf, - 0xb2, 0xf6, 0x23, 0x14, 0xa3, 0xd9, 0x8b, 0xee, 0x80, 0x9c, 0xbe, 0xcc, 0x4a, 0x86, 0x5b, 0x51, - 0x84, 0x20, 0x61, 0x21, 0x3b, 0xd7, 0xc2, 0xec, 0xf5, 0x30, 0x0b, 0x38, 0x18, 0xe3, 0x20, 0xb4, - 0xc0, 0x1f, 0x98, 0x85, 0x9c, 0xb4, 0xc0, 0x05, 0x09, 0x0b, 0xf9, 0x2b, 0xad, 0x21, 0xb6, 0xf0, - 0xd7, 0x14, 0xe4, 0x85, 0x09, 0xf4, 0x34, 0xb9, 0xb7, 0xce, 0xda, 0x67, 0x42, 0x4f, 0xc4, 0xbe, - 0xfa, 0x6c, 0x62, 0x5f, 0xbd, 0x3b, 0x0f, 0x9f, 0xd8, 0x56, 0xbf, 0x85, 0x8a, 0xeb, 0x10, 0x8a, - 0x3d, 0x43, 0x04, 0x46, 0x96, 0xd1, 0xa5, 0x5b, 0x5a, 0x59, 0x68, 0x08, 0x81, 0xf6, 0x47, 0x76, - 0x1a, 0x88, 0x68, 0xe3, 0xa9, 0x9d, 0xfa, 0xa2, 0xa9, 0x9d, 0xbe, 0xda, 0xd4, 0xce, 0x5c, 0x69, - 0x6a, 0x67, 0x3f, 0x7b, 0x6a, 0xe7, 0xbe, 0x60, 0x6a, 0xff, 0x25, 0x0d, 0x79, 0x11, 0x9b, 0xc5, - 0xe9, 0x8b, 0x62, 0x7a, 0xc5, 0xf4, 0x71, 0x7c, 0x22, 0x7d, 0x9b, 0x90, 0x73, 0x7d, 0xcb, 0x74, - 0xe5, 0x6c, 0x5e, 0x99, 0x56, 0x69, 0xda, 0x76, 0x80, 0x09, 0xd1, 0x05, 0x0e, 0x6d, 0x41, 0x3e, - 0xc0, 0x03, 0x9f, 0x62, 0x39, 0x91, 0x2f, 0xd1, 0x90, 0x40, 0xf4, 0x82, 0xed, 0x26, 0xd6, 0x88, - 0xef, 0x26, 0x51, 0x5c, 0xa6, 0x0b, 0x4b, 0x20, 0xf4, 0x08, 0x8b, 0x56, 0xa1, 0x24, 0x18, 0x8c, - 0x44, 0x17, 0x80, 0x10, 0x75, 0xcc, 0x01, 0xd6, 0xfe, 0x50, 0x00, 0x88, 0x57, 0xc4, 0xd2, 0x4b, - 0x68, 0x80, 0xcd, 0x41, 0x5c, 0x05, 0x62, 0x08, 0x55, 0xa5, 0x38, 0xac, 0x83, 0x27, 0xb0, 0x1c, - 0x01, 0xa3, 0x4a, 0x10, 0x05, 0x53, 0x0b, 0xa1, 0x51, 0x2d, 0x7c, 0x05, 0xa1, 0x7a, 0x58, 0x0d, - 0xa2, 0x66, 0x2a, 0x52, 0x2a, 0xeb, 0x61, 0x1d, 0x2a, 0x03, 0x4c, 0x88, 0xd9, 0xc7, 0xc4, 0x20, - 0xd8, 0xa3, 0xe1, 0xb1, 0x21, 0x14, 0x76, 0xd9, 0xce, 0xfb, 0x04, 0x96, 0x23, 0x50, 0x80, 0x2d, - 0xec, 0x8c, 0xa3, 0x83, 0x43, 0x2d, 0x7c, 0xa1, 0x4b, 0x39, 0xda, 0x80, 0xda, 0x19, 0xc6, 0x43, - 0xc3, 0x74, 0x9d, 0x71, 0x48, 0x2a, 0x8e, 0x0f, 0x55, 0x26, 0x6f, 0x72, 0x31, 0xa7, 0x3d, 0x85, - 0x75, 0x5e, 0x8b, 0x3c, 0x43, 0x86, 0xf0, 0xcb, 0xe0, 0xa3, 0xfe, 0x33, 0x4f, 0x12, 0xab, 0x8c, - 0xe6, 0x90, 0xb1, 0x74, 0x39, 0x49, 0x4b, 0x70, 0xc4, 0xbb, 0xc5, 0xef, 0xe0, 0x01, 0xb7, 0x24, - 0xf3, 0x32, 0xd7, 0x94, 0xb2, 0xd0, 0xd4, 0x1a, 0xe3, 0xd1, 0x39, 0xcd, 0x1c, 0x5b, 0x61, 0x87, - 0xc9, 0xc0, 0xf0, 0x00, 0x24, 0x4c, 0x14, 0xaf, 0xd6, 0x61, 0x6f, 0x84, 0x36, 0x8b, 0x53, 0x4c, - 0x6d, 0xc2, 0xea, 0x04, 0x75, 0x98, 0x8b, 0x04, 0x3d, 0x2c, 0xa4, 0xbf, 0x9b, 0xa0, 0x0f, 0x93, - 0x16, 0x9b, 0xf8, 0x0e, 0x56, 0x44, 0x3a, 0x4e, 0x5c, 0xff, 0xdc, 0xb0, 0x7c, 0x8f, 0x06, 0xbe, - 0x6b, 0x9c, 0x3b, 0x9e, 0xed, 0x9f, 0xab, 0xa5, 0xb0, 0x9f, 0x2f, 0x90, 0xb7, 0x3d, 0xfa, 0xe2, - 0xf9, 0x77, 0xa6, 0x3b, 0xc2, 0xfa, 0x2d, 0xae, 0xbd, 0xe7, 0xfa, 0xe7, 0x2d, 0xa1, 0xfb, 0x8e, - 0xab, 0xa2, 0xf7, 0x50, 0x97, 0xc1, 0x9f, 0x45, 0x5c, 0x5e, 0x4c, 0x7c, 0x5b, 0xa8, 0x4f, 0x33, - 0xbf, 0x80, 0xbc, 0x2f, 0x4e, 0x84, 0x15, 0x3e, 0xc2, 0xef, 0xcf, 0x1b, 0x1f, 0x47, 0x1c, 0xa5, - 0x4b, 0xb4, 0xf6, 0xcf, 0x0c, 0x14, 0x64, 0xcb, 0xa3, 0x37, 0x50, 0xa1, 0xd6, 0xd0, 0x19, 0x1a, - 0xa6, 0x10, 0xc8, 0xc9, 0xf5, 0x70, 0xee, 0x90, 0x68, 0xf4, 0xac, 0x61, 0x7b, 0x28, 0x1f, 0xf6, - 0x97, 0xf4, 0x32, 0x57, 0x0f, 0xe9, 0x5e, 0x43, 0x69, 0x64, 0x93, 0x88, 0x4c, 0x8c, 0xb5, 0x07, - 0xf3, 0xc9, 0x8e, 0x6d, 0x12, 0x53, 0xc1, 0x28, 0x7a, 0x62, 0x7e, 0xf9, 0xf4, 0x14, 0x07, 0x11, - 0x55, 0x66, 0x91, 0x5f, 0x47, 0x0c, 0x9e, 0xf0, 0xcb, 0x4f, 0x3c, 0xd7, 0x9b, 0x50, 0x4e, 0xfa, - 0xcd, 0x4e, 0x3e, 0x17, 0xd6, 0x5c, 0xd6, 0x8b, 0xf1, 0x32, 0x10, 0x64, 0x87, 0x7e, 0x20, 0x3e, - 0x4f, 0x72, 0x3a, 0xff, 0x5d, 0xdf, 0x00, 0x88, 0xbd, 0x45, 0x75, 0x50, 0x4e, 0x1c, 0x17, 0xf3, - 0x39, 0x27, 0xce, 0xe3, 0xd1, 0x73, 0xbd, 0x03, 0xe5, 0xa4, 0x33, 0xd1, 0xa9, 0x20, 0x15, 0x9f, - 0x0a, 0xd0, 0x63, 0xc8, 0x8d, 0x59, 0x76, 0x65, 0x88, 0x6e, 0x4c, 0x15, 0x40, 0xd3, 0xfb, 0xa8, - 0x0b, 0xc8, 0x4e, 0x11, 0x0a, 0xd2, 0x53, 0xed, 0x4f, 0x19, 0x76, 0xb2, 0x95, 0xe3, 0x76, 0x1b, - 0x32, 0xd4, 0x25, 0xf3, 0xb7, 0xdd, 0x10, 0xd8, 0xe8, 0xb9, 0x2c, 0x22, 0x0c, 0xcc, 0x3e, 0xde, - 0x78, 0x60, 0xa4, 0xdd, 0x8d, 0x4b, 0xb4, 0xf8, 0x1a, 0xc2, 0xa7, 0xfd, 0x25, 0x5d, 0x28, 0xd6, - 0xff, 0x95, 0x82, 0x4c, 0xcf, 0x25, 0xe8, 0x2b, 0xa8, 0x10, 0x6a, 0x7a, 0xb6, 0x19, 0xd8, 0x46, - 0xbc, 0x3c, 0x16, 0xf9, 0x50, 0xcc, 0x46, 0x3e, 0x5a, 0x05, 0x10, 0x89, 0x8c, 0x8f, 0x92, 0xfb, - 0x4b, 0x7a, 0x91, 0xcb, 0x38, 0xe0, 0x09, 0x2c, 0x8b, 0xbe, 0xb3, 0x70, 0x40, 0x9d, 0x13, 0xc7, - 0x62, 0x9f, 0x96, 0x19, 0x9e, 0x91, 0x1a, 0x7f, 0xd1, 0x8a, 0xe5, 0xe8, 0x29, 0x20, 0xd9, 0x4c, - 0x49, 0x74, 0x96, 0xa3, 0x97, 0xc5, 0x9b, 0x04, 0x7c, 0xa7, 0x0a, 0x65, 0xcb, 0x19, 0x32, 0xeb, - 0x64, 0xe4, 0x50, 0x5c, 0x3f, 0x82, 0xca, 0xc4, 0xaa, 0xbe, 0x38, 0x35, 0x05, 0xc8, 0x0d, 0x7c, - 0x1b, 0xbb, 0x9a, 0x07, 0xe5, 0x64, 0xaf, 0xcd, 0x24, 0xbe, 0x91, 0x24, 0x2e, 0x4a, 0x0a, 0xf4, - 0x1c, 0xc0, 0xb4, 0x6d, 0x87, 0x69, 0x45, 0xbb, 0xfa, 0x6c, 0x9b, 0x09, 0x9c, 0x76, 0x08, 0xd7, - 0x93, 0xf6, 0xd8, 0x18, 0xf3, 0x47, 0x14, 0xfd, 0x0c, 0x94, 0xf0, 0xb6, 0x4c, 0xd6, 0xc5, 0xca, - 0x14, 0xd5, 0x2b, 0x09, 0xd0, 0x23, 0xa8, 0x66, 0x01, 0x4a, 0xb2, 0x1d, 0x3a, 0x5e, 0x1f, 0x07, - 0xec, 0x33, 0xdd, 0x64, 0x9f, 0xef, 0x62, 0x15, 0x8a, 0x2e, 0x9f, 0x26, 0x8c, 0xa4, 0xaf, 0x6e, - 0xe4, 0xef, 0xca, 0x05, 0x9f, 0xad, 0x61, 0xdb, 0x3b, 0xf1, 0x59, 0x2f, 0xb2, 0x19, 0x62, 0xc4, - 0x97, 0x0a, 0x15, 0xbd, 0xc8, 0x24, 0xe2, 0x56, 0x43, 0x13, 0x13, 0xca, 0xb0, 0x4c, 0x89, 0x48, - 0x73, 0x44, 0x89, 0x09, 0x5b, 0xa6, 0xc0, 0x7c, 0x0d, 0x35, 0x8e, 0x09, 0x30, 0x0d, 0x4c, 0x8f, - 0x0c, 0x1c, 0x2a, 0x06, 0x46, 0x45, 0xbf, 0xc6, 0xe4, 0x7a, 0x2c, 0x66, 0x67, 0x14, 0x0e, 0x1d, - 0x06, 0xfe, 0x07, 0x4c, 0x78, 0xe9, 0x54, 0x74, 0xee, 0xc0, 0x5b, 0x2e, 0x61, 0x47, 0x49, 0x0e, - 0xf8, 0x60, 0x5a, 0x67, 0xfe, 0x89, 0xf8, 0x06, 0x95, 0xe6, 0x76, 0x84, 0x28, 0x82, 0x88, 0x79, - 0x4a, 0xf8, 0x26, 0x2f, 0x21, 0x62, 0x69, 0x04, 0x3d, 0x84, 0x6b, 0x62, 0x51, 0x9e, 0x6d, 0x9c, - 0x13, 0xcb, 0x74, 0x31, 0xdf, 0xcd, 0x2b, 0x3a, 0x5f, 0x4c, 0xd7, 0xb3, 0xdf, 0x71, 0x61, 0x84, - 0x0b, 0xac, 0x71, 0x88, 0x53, 0x62, 0x9c, 0x6e, 0x8d, 0x25, 0x6e, 0x05, 0x14, 0x81, 0xa3, 0x3e, - 0xdf, 0x48, 0x2b, 0x7a, 0x81, 0x03, 0xa8, 0x1f, 0xbd, 0x32, 0xa9, 0xcf, 0x37, 0x41, 0xf9, 0xaa, - 0x49, 0x7d, 0xb4, 0x26, 0x1d, 0x65, 0x5e, 0x0c, 0x08, 0xe1, 0xdb, 0x98, 0x5c, 0x6d, 0xd7, 0xb3, - 0xdf, 0x10, 0x12, 0x21, 0x98, 0x7d, 0x86, 0x28, 0xc7, 0x08, 0xdd, 0x1a, 0x33, 0x44, 0xb8, 0xd8, - 0x91, 0x67, 0x5a, 0x67, 0xd8, 0x56, 0x2b, 0xf1, 0x62, 0x8f, 0x85, 0x28, 0x8a, 0x29, 0x11, 0x88, - 0x6a, 0xc2, 0x8a, 0x00, 0xdc, 0x01, 0x9e, 0x50, 0xc3, 0xf5, 0x09, 0x55, 0xaf, 0xf1, 0xd7, 0xdc, - 0xe7, 0x43, 0x9f, 0xd0, 0xc8, 0x80, 0x4c, 0x9e, 0x5a, 0x8b, 0x0d, 0xc8, 0xc4, 0x45, 0x90, 0x13, - 0x46, 0x47, 0x89, 0xba, 0x1c, 0x43, 0xf6, 0x84, 0x08, 0x3d, 0x85, 0xeb, 0xc2, 0x04, 0x3b, 0x26, - 0xb0, 0x93, 0xb2, 0x38, 0x7f, 0x21, 0x8e, 0xe4, 0xd5, 0x71, 0x68, 0x12, 0x7e, 0xec, 0x94, 0x07, - 0x3b, 0x14, 0xc3, 0x4d, 0xeb, 0x4c, 0xa0, 0xaf, 0xc7, 0x35, 0xc3, 0xd0, 0x4d, 0xeb, 0x8c, 0x83, - 0xa7, 0xb9, 0x03, 0x6c, 0x8d, 0xd5, 0x1b, 0xd3, 0xdc, 0x3a, 0xb6, 0xc6, 0xd3, 0xdc, 0x1c, 0x7d, - 0x73, 0x8a, 0x9b, 0x83, 0xc3, 0xd0, 0x0c, 0x07, 0x74, 0xa4, 0xde, 0x8a, 0x43, 0xf3, 0x76, 0x40, - 0x47, 0xe8, 0x31, 0x2c, 0x47, 0xd9, 0x21, 0x84, 0x9e, 0x06, 0x98, 0x9c, 0xaa, 0xb7, 0x13, 0x85, - 0x6d, 0x8d, 0xbb, 0x52, 0x9c, 0xa8, 0x10, 0xaa, 0xaa, 0xc9, 0x0a, 0xa1, 0x51, 0x7e, 0x02, 0x4a, - 0xc7, 0x66, 0xa0, 0xae, 0x24, 0x72, 0xcc, 0x25, 0x91, 0x1d, 0x56, 0x27, 0x91, 0x9d, 0x7a, 0x6c, - 0xa7, 0xeb, 0xd9, 0x91, 0x9d, 0xb0, 0x1f, 0x19, 0xd6, 0x3a, 0xf7, 0x6c, 0xf5, 0x4e, 0x9c, 0x8c, - 0xae, 0x67, 0xb7, 0xce, 0xbd, 0xb8, 0x20, 0x4c, 0x7b, 0xcc, 0x8a, 0xea, 0x6e, 0x6c, 0xb0, 0xc9, - 0x25, 0xec, 0xe4, 0x2f, 0x73, 0xee, 0x07, 0x36, 0x0e, 0x1c, 0xaf, 0xaf, 0xde, 0xe3, 0xa0, 0xaa, - 0x48, 0x7b, 0x28, 0xd5, 0x9a, 0x70, 0xf3, 0x35, 0xa6, 0x3d, 0x7f, 0x28, 0xbf, 0x21, 0x89, 0x8e, - 0x7f, 0x3f, 0xc2, 0x84, 0xb2, 0xc3, 0x36, 0xff, 0x66, 0x30, 0xa6, 0x6e, 0x30, 0xaa, 0x5c, 0xde, - 0x0a, 0x2f, 0x16, 0x34, 0x03, 0x6e, 0x5d, 0xa4, 0x20, 0x43, 0xdf, 0x23, 0x18, 0x7d, 0x03, 0x05, - 0xa9, 0xad, 0xa6, 0xf8, 0x09, 0x6a, 0x65, 0xfe, 0x6d, 0x55, 0x88, 0x44, 0x35, 0xc8, 0x60, 0x4f, - 0x7c, 0x7d, 0x28, 0x3a, 0xfb, 0xa9, 0xbd, 0x84, 0xe5, 0xd7, 0x98, 0x8a, 0x2f, 0xe2, 0xc8, 0xbf, - 0x87, 0xec, 0xdb, 0x86, 0xf9, 0x17, 0xdf, 0x16, 0xa4, 0xc2, 0xcf, 0x10, 0x33, 0x90, 0xe8, 0xb6, - 0xad, 0xbd, 0x07, 0x94, 0x54, 0x96, 0x9e, 0x3d, 0x83, 0xbc, 0xd0, 0x93, 0x8e, 0xa9, 0x73, 0x2f, - 0x02, 0x24, 0x6e, 0x86, 0x5b, 0x3f, 0xc0, 0xed, 0x88, 0x59, 0xcc, 0xdd, 0xc8, 0xb9, 0x89, 0x4b, - 0x8c, 0xd4, 0x85, 0x4b, 0x8c, 0xd8, 0xf3, 0xe8, 0x26, 0x25, 0x9d, 0xf4, 0x5c, 0x5e, 0xa7, 0x68, - 0xa7, 0xa0, 0x4e, 0xf3, 0x4b, 0xff, 0x27, 0x2f, 0xcd, 0x53, 0x9f, 0x73, 0x69, 0x3e, 0x63, 0x25, - 0xdb, 0x3c, 0xc0, 0xd1, 0xc5, 0x95, 0x58, 0xc3, 0xe5, 0x97, 0x57, 0x5a, 0x9b, 0xc7, 0x35, 0xd2, - 0x99, 0x95, 0xf1, 0xd4, 0xd5, 0x32, 0xae, 0xbd, 0x84, 0x1b, 0x6c, 0xa1, 0x89, 0x2b, 0x2d, 0xe1, - 0xc1, 0xd4, 0xb5, 0x56, 0x6a, 0xfa, 0x5a, 0x4b, 0x3b, 0xe6, 0x05, 0x9c, 0x54, 0x96, 0xae, 0xfc, - 0x12, 0x20, 0x06, 0xce, 0xff, 0x07, 0x54, 0x42, 0x33, 0x81, 0xd7, 0x36, 0xa1, 0xc6, 0x68, 0x65, - 0xd0, 0xe2, 0xac, 0x46, 0x29, 0x4b, 0x4d, 0x5e, 0x7e, 0x69, 0xbb, 0xa2, 0x48, 0xa5, 0x42, 0xa2, - 0xcc, 0xc4, 0x25, 0x90, 0xb0, 0xaf, 0xce, 0x4d, 0x91, 0xc4, 0x6d, 0xff, 0x27, 0x0b, 0x8a, 0x0c, - 0xd0, 0x27, 0x64, 0x41, 0x75, 0xb2, 0xb3, 0xd0, 0xa3, 0x69, 0x82, 0x99, 0xed, 0x5b, 0xdf, 0x58, - 0x0c, 0x94, 0x3e, 0xbe, 0x03, 0x88, 0x1b, 0x04, 0xad, 0xcf, 0xd4, 0x9b, 0xec, 0xbd, 0xfa, 0x83, - 0xcb, 0x41, 0x92, 0xd8, 0x11, 0x21, 0x4c, 0xd6, 0x2f, 0xfa, 0xfa, 0x12, 0xcd, 0xc9, 0x1e, 0xaa, - 0x3f, 0xbe, 0x0a, 0x74, 0x62, 0x0d, 0xe1, 0xff, 0x1c, 0x67, 0xaf, 0x61, 0xb2, 0xbc, 0xe7, 0xac, - 0xe1, 0x62, 0x3d, 0xff, 0x08, 0x95, 0x89, 0xea, 0x42, 0x0f, 0x67, 0x7b, 0x75, 0xb1, 0x76, 0xeb, - 0x8f, 0x16, 0xe2, 0xa4, 0x85, 0x1e, 0x14, 0xa3, 0xba, 0x41, 0xda, 0x6c, 0xad, 0x64, 0x15, 0xd6, - 0xd7, 0x2f, 0xc5, 0x08, 0xd6, 0x9d, 0xf7, 0x70, 0xdd, 0xf1, 0xa7, 0x80, 0x3b, 0x95, 0xb0, 0xb4, - 0xde, 0xb2, 0x73, 0xe4, 0xdb, 0xd4, 0x6f, 0x9f, 0xc9, 0x73, 0x65, 0xdf, 0x77, 0x4d, 0xaf, 0xdf, - 0xf0, 0x83, 0xfe, 0xe6, 0xe4, 0xff, 0x9a, 0xd9, 0x53, 0xb8, 0x05, 0x7c, 0x32, 0xc6, 0x5b, 0x1f, - 0xf2, 0xfc, 0x08, 0xfa, 0xcd, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd3, 0x7a, 0xae, 0xc5, 0x94, - 0x1e, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/channelz/service/regenerate.sh b/examples/google.golang.org/grpc/channelz/service/regenerate.sh deleted file mode 100755 index 9c255b1..0000000 --- a/examples/google.golang.org/grpc/channelz/service/regenerate.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/channelz/v1 -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/channelz/v1/channelz.proto > grpc/channelz/v1/channelz.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/channelz/v1/*.proto -popd -rm -f ../grpc_channelz_v1/*.pb.go -cp "$TMP"/grpc/channelz/v1/*.pb.go ../grpc_channelz_v1/ - diff --git a/examples/google.golang.org/grpc/channelz/service/service.go b/examples/google.golang.org/grpc/channelz/service/service.go deleted file mode 100755 index 19c016b..0000000 --- a/examples/google.golang.org/grpc/channelz/service/service.go +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * 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. - * - */ - -//go:generate ./regenerate.sh - -// Package service provides an implementation for channelz service server. -package service - -import ( - "net" - - "github.com/golang/protobuf/ptypes" - wrpb "github.com/golang/protobuf/ptypes/wrappers" - "golang.org/x/net/context" - "google.golang.org/grpc" - channelzgrpc "google.golang.org/grpc/channelz/grpc_channelz_v1" - channelzpb "google.golang.org/grpc/channelz/grpc_channelz_v1" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/internal/channelz" -) - -// RegisterChannelzServiceToServer registers the channelz service to the given server. -func RegisterChannelzServiceToServer(s *grpc.Server) { - channelzgrpc.RegisterChannelzServer(s, &serverImpl{}) -} - -func newCZServer() channelzgrpc.ChannelzServer { - return &serverImpl{} -} - -type serverImpl struct{} - -func connectivityStateToProto(s connectivity.State) *channelzpb.ChannelConnectivityState { - switch s { - case connectivity.Idle: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_IDLE} - case connectivity.Connecting: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_CONNECTING} - case connectivity.Ready: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_READY} - case connectivity.TransientFailure: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_TRANSIENT_FAILURE} - case connectivity.Shutdown: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_SHUTDOWN} - default: - return &channelzpb.ChannelConnectivityState{State: channelzpb.ChannelConnectivityState_UNKNOWN} - } -} - -func channelMetricToProto(cm *channelz.ChannelMetric) *channelzpb.Channel { - c := &channelzpb.Channel{} - c.Ref = &channelzpb.ChannelRef{ChannelId: cm.ID, Name: cm.RefName} - - c.Data = &channelzpb.ChannelData{ - State: connectivityStateToProto(cm.ChannelData.State), - Target: cm.ChannelData.Target, - CallsStarted: cm.ChannelData.CallsStarted, - CallsSucceeded: cm.ChannelData.CallsSucceeded, - CallsFailed: cm.ChannelData.CallsFailed, - } - if ts, err := ptypes.TimestampProto(cm.ChannelData.LastCallStartedTimestamp); err == nil { - c.Data.LastCallStartedTimestamp = ts - } - nestedChans := make([]*channelzpb.ChannelRef, 0, len(cm.NestedChans)) - for id, ref := range cm.NestedChans { - nestedChans = append(nestedChans, &channelzpb.ChannelRef{ChannelId: id, Name: ref}) - } - c.ChannelRef = nestedChans - - subChans := make([]*channelzpb.SubchannelRef, 0, len(cm.SubChans)) - for id, ref := range cm.SubChans { - subChans = append(subChans, &channelzpb.SubchannelRef{SubchannelId: id, Name: ref}) - } - c.SubchannelRef = subChans - - sockets := make([]*channelzpb.SocketRef, 0, len(cm.Sockets)) - for id, ref := range cm.Sockets { - sockets = append(sockets, &channelzpb.SocketRef{SocketId: id, Name: ref}) - } - c.SocketRef = sockets - return c -} - -func subChannelMetricToProto(cm *channelz.SubChannelMetric) *channelzpb.Subchannel { - sc := &channelzpb.Subchannel{} - sc.Ref = &channelzpb.SubchannelRef{SubchannelId: cm.ID, Name: cm.RefName} - - sc.Data = &channelzpb.ChannelData{ - State: connectivityStateToProto(cm.ChannelData.State), - Target: cm.ChannelData.Target, - CallsStarted: cm.ChannelData.CallsStarted, - CallsSucceeded: cm.ChannelData.CallsSucceeded, - CallsFailed: cm.ChannelData.CallsFailed, - } - if ts, err := ptypes.TimestampProto(cm.ChannelData.LastCallStartedTimestamp); err == nil { - sc.Data.LastCallStartedTimestamp = ts - } - nestedChans := make([]*channelzpb.ChannelRef, 0, len(cm.NestedChans)) - for id, ref := range cm.NestedChans { - nestedChans = append(nestedChans, &channelzpb.ChannelRef{ChannelId: id, Name: ref}) - } - sc.ChannelRef = nestedChans - - subChans := make([]*channelzpb.SubchannelRef, 0, len(cm.SubChans)) - for id, ref := range cm.SubChans { - subChans = append(subChans, &channelzpb.SubchannelRef{SubchannelId: id, Name: ref}) - } - sc.SubchannelRef = subChans - - sockets := make([]*channelzpb.SocketRef, 0, len(cm.Sockets)) - for id, ref := range cm.Sockets { - sockets = append(sockets, &channelzpb.SocketRef{SocketId: id, Name: ref}) - } - sc.SocketRef = sockets - return sc -} - -func addrToProto(a net.Addr) *channelzpb.Address { - switch a.Network() { - case "udp": - // TODO: Address_OtherAddress{}. Need proto def for Value. - case "ip": - // Note zone info is discarded through the conversion. - return &channelzpb.Address{Address: &channelzpb.Address_TcpipAddress{TcpipAddress: &channelzpb.Address_TcpIpAddress{IpAddress: a.(*net.IPAddr).IP}}} - case "ip+net": - // Note mask info is discarded through the conversion. - return &channelzpb.Address{Address: &channelzpb.Address_TcpipAddress{TcpipAddress: &channelzpb.Address_TcpIpAddress{IpAddress: a.(*net.IPNet).IP}}} - case "tcp": - // Note zone info is discarded through the conversion. - return &channelzpb.Address{Address: &channelzpb.Address_TcpipAddress{TcpipAddress: &channelzpb.Address_TcpIpAddress{IpAddress: a.(*net.TCPAddr).IP, Port: int32(a.(*net.TCPAddr).Port)}}} - case "unix", "unixgram", "unixpacket": - return &channelzpb.Address{Address: &channelzpb.Address_UdsAddress_{UdsAddress: &channelzpb.Address_UdsAddress{Filename: a.String()}}} - default: - } - return &channelzpb.Address{} -} - -func socketMetricToProto(sm *channelz.SocketMetric) *channelzpb.Socket { - s := &channelzpb.Socket{} - s.Ref = &channelzpb.SocketRef{SocketId: sm.ID, Name: sm.RefName} - - s.Data = &channelzpb.SocketData{ - StreamsStarted: sm.SocketData.StreamsStarted, - StreamsSucceeded: sm.SocketData.StreamsSucceeded, - StreamsFailed: sm.SocketData.StreamsFailed, - MessagesSent: sm.SocketData.MessagesSent, - MessagesReceived: sm.SocketData.MessagesReceived, - KeepAlivesSent: sm.SocketData.KeepAlivesSent, - } - if ts, err := ptypes.TimestampProto(sm.SocketData.LastLocalStreamCreatedTimestamp); err == nil { - s.Data.LastLocalStreamCreatedTimestamp = ts - } - if ts, err := ptypes.TimestampProto(sm.SocketData.LastRemoteStreamCreatedTimestamp); err == nil { - s.Data.LastRemoteStreamCreatedTimestamp = ts - } - if ts, err := ptypes.TimestampProto(sm.SocketData.LastMessageSentTimestamp); err == nil { - s.Data.LastMessageSentTimestamp = ts - } - if ts, err := ptypes.TimestampProto(sm.SocketData.LastMessageReceivedTimestamp); err == nil { - s.Data.LastMessageReceivedTimestamp = ts - } - s.Data.LocalFlowControlWindow = &wrpb.Int64Value{Value: sm.SocketData.LocalFlowControlWindow} - s.Data.RemoteFlowControlWindow = &wrpb.Int64Value{Value: sm.SocketData.RemoteFlowControlWindow} - - if sm.SocketData.LocalAddr != nil { - s.Local = addrToProto(sm.SocketData.LocalAddr) - } - if sm.SocketData.RemoteAddr != nil { - s.Remote = addrToProto(sm.SocketData.RemoteAddr) - } - s.RemoteName = sm.SocketData.RemoteName - return s -} - -func (s *serverImpl) GetTopChannels(ctx context.Context, req *channelzpb.GetTopChannelsRequest) (*channelzpb.GetTopChannelsResponse, error) { - metrics, end := channelz.GetTopChannels(req.GetStartChannelId()) - resp := &channelzpb.GetTopChannelsResponse{} - for _, m := range metrics { - resp.Channel = append(resp.Channel, channelMetricToProto(m)) - } - resp.End = end - return resp, nil -} - -func serverMetricToProto(sm *channelz.ServerMetric) *channelzpb.Server { - s := &channelzpb.Server{} - s.Ref = &channelzpb.ServerRef{ServerId: sm.ID, Name: sm.RefName} - - s.Data = &channelzpb.ServerData{ - CallsStarted: sm.ServerData.CallsStarted, - CallsSucceeded: sm.ServerData.CallsSucceeded, - CallsFailed: sm.ServerData.CallsFailed, - } - - if ts, err := ptypes.TimestampProto(sm.ServerData.LastCallStartedTimestamp); err == nil { - s.Data.LastCallStartedTimestamp = ts - } - sockets := make([]*channelzpb.SocketRef, 0, len(sm.ListenSockets)) - for id, ref := range sm.ListenSockets { - sockets = append(sockets, &channelzpb.SocketRef{SocketId: id, Name: ref}) - } - s.ListenSocket = sockets - return s -} - -func (s *serverImpl) GetServers(ctx context.Context, req *channelzpb.GetServersRequest) (*channelzpb.GetServersResponse, error) { - metrics, end := channelz.GetServers(req.GetStartServerId()) - resp := &channelzpb.GetServersResponse{} - for _, m := range metrics { - resp.Server = append(resp.Server, serverMetricToProto(m)) - } - resp.End = end - return resp, nil -} - -func (s *serverImpl) GetServerSockets(ctx context.Context, req *channelzpb.GetServerSocketsRequest) (*channelzpb.GetServerSocketsResponse, error) { - metrics, end := channelz.GetServerSockets(req.GetServerId(), req.GetStartSocketId()) - resp := &channelzpb.GetServerSocketsResponse{} - for _, m := range metrics { - resp.SocketRef = append(resp.SocketRef, &channelzpb.SocketRef{SocketId: m.ID, Name: m.RefName}) - } - resp.End = end - return resp, nil -} - -func (s *serverImpl) GetChannel(ctx context.Context, req *channelzpb.GetChannelRequest) (*channelzpb.GetChannelResponse, error) { - var metric *channelz.ChannelMetric - if metric = channelz.GetChannel(req.GetChannelId()); metric == nil { - return &channelzpb.GetChannelResponse{}, nil - } - resp := &channelzpb.GetChannelResponse{Channel: channelMetricToProto(metric)} - return resp, nil -} - -func (s *serverImpl) GetSubchannel(ctx context.Context, req *channelzpb.GetSubchannelRequest) (*channelzpb.GetSubchannelResponse, error) { - var metric *channelz.SubChannelMetric - if metric = channelz.GetSubChannel(req.GetSubchannelId()); metric == nil { - return &channelzpb.GetSubchannelResponse{}, nil - } - resp := &channelzpb.GetSubchannelResponse{Subchannel: subChannelMetricToProto(metric)} - return resp, nil -} - -func (s *serverImpl) GetSocket(ctx context.Context, req *channelzpb.GetSocketRequest) (*channelzpb.GetSocketResponse, error) { - var metric *channelz.SocketMetric - if metric = channelz.GetSocket(req.GetSocketId()); metric == nil { - return &channelzpb.GetSocketResponse{}, nil - } - resp := &channelzpb.GetSocketResponse{Socket: socketMetricToProto(metric)} - return resp, nil -} diff --git a/examples/google.golang.org/grpc/channelz/service/service_test.go b/examples/google.golang.org/grpc/channelz/service/service_test.go deleted file mode 100755 index 398cd6c..0000000 --- a/examples/google.golang.org/grpc/channelz/service/service_test.go +++ /dev/null @@ -1,477 +0,0 @@ -/* - * - * 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. - * - */ - -package service - -import ( - "net" - "reflect" - "strconv" - "testing" - "time" - - "github.com/golang/protobuf/ptypes" - "golang.org/x/net/context" - channelzpb "google.golang.org/grpc/channelz/grpc_channelz_v1" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/internal/channelz" -) - -func init() { - channelz.TurnOn() -} - -// emptyTime is used for detecting unset value of time.Time type. -// For go1.7 and earlier, ptypes.Timestamp will fill in the loc field of time.Time -// with &utcLoc. However zero value of a time.Time type value loc field is nil. -// This behavior will make reflect.DeepEqual fail upon unset time.Time field, -// and cause false positive fatal error. -var emptyTime time.Time - -type dummyChannel struct { - state connectivity.State - target string - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTimestamp time.Time -} - -func (d *dummyChannel) ChannelzMetric() *channelz.ChannelInternalMetric { - return &channelz.ChannelInternalMetric{ - State: d.state, - Target: d.target, - CallsStarted: d.callsStarted, - CallsSucceeded: d.callsSucceeded, - CallsFailed: d.callsFailed, - LastCallStartedTimestamp: d.lastCallStartedTimestamp, - } -} - -type dummyServer struct { - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTimestamp time.Time -} - -func (d *dummyServer) ChannelzMetric() *channelz.ServerInternalMetric { - return &channelz.ServerInternalMetric{ - CallsStarted: d.callsStarted, - CallsSucceeded: d.callsSucceeded, - CallsFailed: d.callsFailed, - LastCallStartedTimestamp: d.lastCallStartedTimestamp, - } -} - -type dummySocket struct { - streamsStarted int64 - streamsSucceeded int64 - streamsFailed int64 - messagesSent int64 - messagesReceived int64 - keepAlivesSent int64 - lastLocalStreamCreatedTimestamp time.Time - lastRemoteStreamCreatedTimestamp time.Time - lastMessageSentTimestamp time.Time - lastMessageReceivedTimestamp time.Time - localFlowControlWindow int64 - remoteFlowControlWindow int64 - //socket options - localAddr net.Addr - remoteAddr net.Addr - // Security - remoteName string -} - -func (d *dummySocket) ChannelzMetric() *channelz.SocketInternalMetric { - return &channelz.SocketInternalMetric{ - StreamsStarted: d.streamsStarted, - StreamsSucceeded: d.streamsSucceeded, - StreamsFailed: d.streamsFailed, - MessagesSent: d.messagesSent, - MessagesReceived: d.messagesReceived, - KeepAlivesSent: d.keepAlivesSent, - LastLocalStreamCreatedTimestamp: d.lastLocalStreamCreatedTimestamp, - LastRemoteStreamCreatedTimestamp: d.lastRemoteStreamCreatedTimestamp, - LastMessageSentTimestamp: d.lastMessageSentTimestamp, - LastMessageReceivedTimestamp: d.lastMessageReceivedTimestamp, - LocalFlowControlWindow: d.localFlowControlWindow, - RemoteFlowControlWindow: d.remoteFlowControlWindow, - //socket options - LocalAddr: d.localAddr, - RemoteAddr: d.remoteAddr, - // Security - RemoteName: d.remoteName, - } -} - -func channelProtoToStruct(c *channelzpb.Channel) *dummyChannel { - dc := &dummyChannel{} - pdata := c.GetData() - switch pdata.GetState().GetState() { - case channelzpb.ChannelConnectivityState_UNKNOWN: - // TODO: what should we set here? - case channelzpb.ChannelConnectivityState_IDLE: - dc.state = connectivity.Idle - case channelzpb.ChannelConnectivityState_CONNECTING: - dc.state = connectivity.Connecting - case channelzpb.ChannelConnectivityState_READY: - dc.state = connectivity.Ready - case channelzpb.ChannelConnectivityState_TRANSIENT_FAILURE: - dc.state = connectivity.TransientFailure - case channelzpb.ChannelConnectivityState_SHUTDOWN: - dc.state = connectivity.Shutdown - } - dc.target = pdata.GetTarget() - dc.callsStarted = pdata.CallsStarted - dc.callsSucceeded = pdata.CallsSucceeded - dc.callsFailed = pdata.CallsFailed - if t, err := ptypes.Timestamp(pdata.GetLastCallStartedTimestamp()); err == nil { - if !t.Equal(emptyTime) { - dc.lastCallStartedTimestamp = t - } - } - return dc -} - -func serverProtoToStruct(s *channelzpb.Server) *dummyServer { - ds := &dummyServer{} - pdata := s.GetData() - ds.callsStarted = pdata.CallsStarted - ds.callsSucceeded = pdata.CallsSucceeded - ds.callsFailed = pdata.CallsFailed - if t, err := ptypes.Timestamp(pdata.GetLastCallStartedTimestamp()); err == nil { - if !t.Equal(emptyTime) { - ds.lastCallStartedTimestamp = t - } - } - return ds -} - -func protoToAddr(a *channelzpb.Address) net.Addr { - switch v := a.Address.(type) { - case *channelzpb.Address_TcpipAddress: - if port := v.TcpipAddress.GetPort(); port != 0 { - return &net.TCPAddr{IP: v.TcpipAddress.GetIpAddress(), Port: int(port)} - } - return &net.IPAddr{IP: v.TcpipAddress.GetIpAddress()} - case *channelzpb.Address_UdsAddress_: - return &net.UnixAddr{Name: v.UdsAddress.GetFilename(), Net: "unix"} - case *channelzpb.Address_OtherAddress_: - // TODO: - } - return nil -} - -func socketProtoToStruct(s *channelzpb.Socket) *dummySocket { - ds := &dummySocket{} - pdata := s.GetData() - ds.streamsStarted = pdata.GetStreamsStarted() - ds.streamsSucceeded = pdata.GetStreamsSucceeded() - ds.streamsFailed = pdata.GetStreamsFailed() - ds.messagesSent = pdata.GetMessagesSent() - ds.messagesReceived = pdata.GetMessagesReceived() - ds.keepAlivesSent = pdata.GetKeepAlivesSent() - if t, err := ptypes.Timestamp(pdata.GetLastLocalStreamCreatedTimestamp()); err == nil { - if !t.Equal(emptyTime) { - ds.lastLocalStreamCreatedTimestamp = t - } - } - if t, err := ptypes.Timestamp(pdata.GetLastRemoteStreamCreatedTimestamp()); err == nil { - if !t.Equal(emptyTime) { - ds.lastRemoteStreamCreatedTimestamp = t - } - } - if t, err := ptypes.Timestamp(pdata.GetLastMessageSentTimestamp()); err == nil { - if !t.Equal(emptyTime) { - ds.lastMessageSentTimestamp = t - } - } - if t, err := ptypes.Timestamp(pdata.GetLastMessageReceivedTimestamp()); err == nil { - if !t.Equal(emptyTime) { - ds.lastMessageReceivedTimestamp = t - } - } - if v := pdata.GetLocalFlowControlWindow(); v != nil { - ds.localFlowControlWindow = v.Value - } - if v := pdata.GetRemoteFlowControlWindow(); v != nil { - ds.remoteFlowControlWindow = v.Value - } - if local := s.GetLocal(); local != nil { - ds.localAddr = protoToAddr(local) - } - if remote := s.GetRemote(); remote != nil { - ds.remoteAddr = protoToAddr(remote) - } - ds.remoteName = s.GetRemoteName() - return ds -} - -func convertSocketRefSliceToMap(sktRefs []*channelzpb.SocketRef) map[int64]string { - m := make(map[int64]string) - for _, sr := range sktRefs { - m[sr.SocketId] = sr.Name - } - return m -} - -func TestGetTopChannels(t *testing.T) { - tcs := []*dummyChannel{ - { - state: connectivity.Connecting, - target: "test.channelz:1234", - callsStarted: 6, - callsSucceeded: 2, - callsFailed: 3, - lastCallStartedTimestamp: time.Now().UTC(), - }, - { - state: connectivity.Connecting, - target: "test.channelz:1234", - callsStarted: 1, - callsSucceeded: 2, - callsFailed: 3, - lastCallStartedTimestamp: time.Now().UTC(), - }, - { - state: connectivity.Shutdown, - target: "test.channelz:8888", - callsStarted: 0, - callsSucceeded: 0, - callsFailed: 0, - }, - {}, - } - channelz.NewChannelzStorage() - for _, c := range tcs { - channelz.RegisterChannel(c, 0, "") - } - s := newCZServer() - resp, _ := s.GetTopChannels(context.Background(), &channelzpb.GetTopChannelsRequest{StartChannelId: 0}) - if !resp.GetEnd() { - t.Fatalf("resp.GetEnd() want true, got %v", resp.GetEnd()) - } - for i, c := range resp.GetChannel() { - if !reflect.DeepEqual(channelProtoToStruct(c), tcs[i]) { - t.Fatalf("dummyChannel: %d, want: %#v, got: %#v", i, tcs[i], channelProtoToStruct(c)) - } - } - for i := 0; i < 50; i++ { - channelz.RegisterChannel(tcs[0], 0, "") - } - resp, _ = s.GetTopChannels(context.Background(), &channelzpb.GetTopChannelsRequest{StartChannelId: 0}) - if resp.GetEnd() { - t.Fatalf("resp.GetEnd() want false, got %v", resp.GetEnd()) - } -} - -func TestGetServers(t *testing.T) { - ss := []*dummyServer{ - { - callsStarted: 6, - callsSucceeded: 2, - callsFailed: 3, - lastCallStartedTimestamp: time.Now().UTC(), - }, - { - callsStarted: 1, - callsSucceeded: 2, - callsFailed: 3, - lastCallStartedTimestamp: time.Now().UTC(), - }, - { - callsStarted: 1, - callsSucceeded: 0, - callsFailed: 0, - lastCallStartedTimestamp: time.Now().UTC(), - }, - } - channelz.NewChannelzStorage() - for _, s := range ss { - channelz.RegisterServer(s, "") - } - svr := newCZServer() - resp, _ := svr.GetServers(context.Background(), &channelzpb.GetServersRequest{StartServerId: 0}) - if !resp.GetEnd() { - t.Fatalf("resp.GetEnd() want true, got %v", resp.GetEnd()) - } - for i, s := range resp.GetServer() { - if !reflect.DeepEqual(serverProtoToStruct(s), ss[i]) { - t.Fatalf("dummyServer: %d, want: %#v, got: %#v", i, ss[i], serverProtoToStruct(s)) - } - } - for i := 0; i < 50; i++ { - channelz.RegisterServer(ss[0], "") - } - resp, _ = svr.GetServers(context.Background(), &channelzpb.GetServersRequest{StartServerId: 0}) - if resp.GetEnd() { - t.Fatalf("resp.GetEnd() want false, got %v", resp.GetEnd()) - } -} - -func TestGetServerSockets(t *testing.T) { - channelz.NewChannelzStorage() - svrID := channelz.RegisterServer(&dummyServer{}, "") - refNames := []string{"listen socket 1", "normal socket 1", "normal socket 2"} - ids := make([]int64, 3) - ids[0] = channelz.RegisterListenSocket(&dummySocket{}, svrID, refNames[0]) - ids[1] = channelz.RegisterNormalSocket(&dummySocket{}, svrID, refNames[1]) - ids[2] = channelz.RegisterNormalSocket(&dummySocket{}, svrID, refNames[2]) - svr := newCZServer() - resp, _ := svr.GetServerSockets(context.Background(), &channelzpb.GetServerSocketsRequest{ServerId: svrID, StartSocketId: 0}) - if !resp.GetEnd() { - t.Fatalf("resp.GetEnd() want: true, got: %v", resp.GetEnd()) - } - // GetServerSockets only return normal sockets. - want := map[int64]string{ - ids[1]: refNames[1], - ids[2]: refNames[2], - } - if !reflect.DeepEqual(convertSocketRefSliceToMap(resp.GetSocketRef()), want) { - t.Fatalf("GetServerSockets want: %#v, got: %#v", want, resp.GetSocketRef()) - } - - for i := 0; i < 50; i++ { - channelz.RegisterNormalSocket(&dummySocket{}, svrID, "") - } - resp, _ = svr.GetServerSockets(context.Background(), &channelzpb.GetServerSocketsRequest{ServerId: svrID, StartSocketId: 0}) - if resp.GetEnd() { - t.Fatalf("resp.GetEnd() want false, got %v", resp.GetEnd()) - } -} - -func TestGetChannel(t *testing.T) { - channelz.NewChannelzStorage() - refNames := []string{"top channel 1", "nested channel 1", "nested channel 2", "nested channel 3"} - ids := make([]int64, 4) - ids[0] = channelz.RegisterChannel(&dummyChannel{}, 0, refNames[0]) - ids[1] = channelz.RegisterChannel(&dummyChannel{}, ids[0], refNames[1]) - ids[2] = channelz.RegisterSubChannel(&dummyChannel{}, ids[0], refNames[2]) - ids[3] = channelz.RegisterChannel(&dummyChannel{}, ids[1], refNames[3]) - svr := newCZServer() - resp, _ := svr.GetChannel(context.Background(), &channelzpb.GetChannelRequest{ChannelId: ids[0]}) - metrics := resp.GetChannel() - subChans := metrics.GetSubchannelRef() - if len(subChans) != 1 || subChans[0].GetName() != refNames[2] || subChans[0].GetSubchannelId() != ids[2] { - t.Fatalf("GetSubChannelRef() want %#v, got %#v", []*channelzpb.SubchannelRef{{SubchannelId: ids[2], Name: refNames[2]}}, subChans) - } - nestedChans := metrics.GetChannelRef() - if len(nestedChans) != 1 || nestedChans[0].GetName() != refNames[1] || nestedChans[0].GetChannelId() != ids[1] { - t.Fatalf("GetChannelRef() want %#v, got %#v", []*channelzpb.ChannelRef{{ChannelId: ids[1], Name: refNames[1]}}, nestedChans) - } - - resp, _ = svr.GetChannel(context.Background(), &channelzpb.GetChannelRequest{ChannelId: ids[1]}) - metrics = resp.GetChannel() - nestedChans = metrics.GetChannelRef() - if len(nestedChans) != 1 || nestedChans[0].GetName() != refNames[3] || nestedChans[0].GetChannelId() != ids[3] { - t.Fatalf("GetChannelRef() want %#v, got %#v", []*channelzpb.ChannelRef{{ChannelId: ids[3], Name: refNames[3]}}, nestedChans) - } -} - -func TestGetSubChannel(t *testing.T) { - channelz.NewChannelzStorage() - refNames := []string{"top channel 1", "sub channel 1", "socket 1", "socket 2"} - ids := make([]int64, 4) - ids[0] = channelz.RegisterChannel(&dummyChannel{}, 0, refNames[0]) - ids[1] = channelz.RegisterSubChannel(&dummyChannel{}, ids[0], refNames[1]) - ids[2] = channelz.RegisterNormalSocket(&dummySocket{}, ids[1], refNames[2]) - ids[3] = channelz.RegisterNormalSocket(&dummySocket{}, ids[1], refNames[3]) - svr := newCZServer() - resp, _ := svr.GetSubchannel(context.Background(), &channelzpb.GetSubchannelRequest{SubchannelId: ids[1]}) - metrics := resp.GetSubchannel() - want := map[int64]string{ - ids[2]: refNames[2], - ids[3]: refNames[3], - } - if !reflect.DeepEqual(convertSocketRefSliceToMap(metrics.GetSocketRef()), want) { - t.Fatalf("GetSocketRef() want %#v: got: %#v", want, metrics.GetSocketRef()) - } -} - -func TestGetSocket(t *testing.T) { - channelz.NewChannelzStorage() - ss := []*dummySocket{ - { - streamsStarted: 10, - streamsSucceeded: 2, - streamsFailed: 3, - messagesSent: 20, - messagesReceived: 10, - keepAlivesSent: 2, - lastLocalStreamCreatedTimestamp: time.Now().UTC(), - lastRemoteStreamCreatedTimestamp: time.Now().UTC(), - lastMessageSentTimestamp: time.Now().UTC(), - lastMessageReceivedTimestamp: time.Now().UTC(), - localFlowControlWindow: 65536, - remoteFlowControlWindow: 1024, - localAddr: &net.TCPAddr{IP: net.ParseIP("1.0.0.1"), Port: 10001}, - remoteAddr: &net.TCPAddr{IP: net.ParseIP("12.0.0.1"), Port: 10002}, - remoteName: "remote.remote", - }, - { - streamsStarted: 10, - streamsSucceeded: 2, - streamsFailed: 3, - messagesSent: 20, - messagesReceived: 10, - keepAlivesSent: 2, - lastRemoteStreamCreatedTimestamp: time.Now().UTC(), - lastMessageSentTimestamp: time.Now().UTC(), - lastMessageReceivedTimestamp: time.Now().UTC(), - localFlowControlWindow: 65536, - remoteFlowControlWindow: 1024, - localAddr: &net.UnixAddr{Name: "file.path", Net: "unix"}, - remoteAddr: &net.UnixAddr{Name: "another.path", Net: "unix"}, - remoteName: "remote.remote", - }, - { - streamsStarted: 5, - streamsSucceeded: 2, - streamsFailed: 3, - messagesSent: 20, - messagesReceived: 10, - keepAlivesSent: 2, - lastLocalStreamCreatedTimestamp: time.Now().UTC(), - lastMessageSentTimestamp: time.Now().UTC(), - lastMessageReceivedTimestamp: time.Now().UTC(), - localFlowControlWindow: 65536, - remoteFlowControlWindow: 10240, - localAddr: &net.IPAddr{IP: net.ParseIP("1.0.0.1")}, - remoteAddr: &net.IPAddr{IP: net.ParseIP("9.0.0.1")}, - remoteName: "", - }, - { - localAddr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 10001}, - }, - } - svr := newCZServer() - ids := make([]int64, len(ss)) - svrID := channelz.RegisterServer(&dummyServer{}, "") - for i, s := range ss { - ids[i] = channelz.RegisterNormalSocket(s, svrID, strconv.Itoa(i)) - } - for i, s := range ss { - resp, _ := svr.GetSocket(context.Background(), &channelzpb.GetSocketRequest{SocketId: ids[i]}) - metrics := resp.GetSocket() - if !reflect.DeepEqual(metrics.GetRef(), &channelzpb.SocketRef{SocketId: ids[i], Name: strconv.Itoa(i)}) || !reflect.DeepEqual(socketProtoToStruct(metrics), s) { - t.Fatalf("resp.GetSocket() want: metrics.GetRef() = %#v and %#v, got: metrics.GetRef() = %#v and %#v", &channelzpb.SocketRef{SocketId: ids[i], Name: strconv.Itoa(i)}, s, metrics.GetRef(), socketProtoToStruct(metrics)) - } - } -} diff --git a/examples/google.golang.org/grpc/clientconn.go b/examples/google.golang.org/grpc/clientconn.go deleted file mode 100755 index 84ba9e5..0000000 --- a/examples/google.golang.org/grpc/clientconn.go +++ /dev/null @@ -1,1602 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "errors" - "fmt" - "math" - "net" - "reflect" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/trace" - "google.golang.org/grpc/balancer" - _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/internal/backoff" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/resolver" - _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. - _ "google.golang.org/grpc/resolver/passthrough" // To register passthrough resolver. - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -const ( - // minimum time to give a connection to complete - minConnectTimeout = 20 * time.Second - // must match grpclbName in grpclb/grpclb.go - grpclbName = "grpclb" -) - -var ( - // ErrClientConnClosing indicates that the operation is illegal because - // the ClientConn is closing. - // - // Deprecated: this error should not be relied upon by users; use the status - // code of Canceled instead. - ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing") - // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. - errConnDrain = errors.New("grpc: the connection is drained") - // errConnClosing indicates that the connection is closing. - errConnClosing = errors.New("grpc: the connection is closing") - // errConnUnavailable indicates that the connection is unavailable. - errConnUnavailable = errors.New("grpc: the connection is unavailable") - // errBalancerClosed indicates that the balancer is closed. - errBalancerClosed = errors.New("grpc: balancer is closed") - // We use an accessor so that minConnectTimeout can be - // atomically read and updated while testing. - getMinConnectTimeout = func() time.Duration { - return minConnectTimeout - } -) - -// The following errors are returned from Dial and DialContext -var ( - // errNoTransportSecurity indicates that there is no transport security - // being set for ClientConn. Users should either set one or explicitly - // call WithInsecure DialOption to disable security. - errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)") - // errTransportCredentialsMissing indicates that users want to transmit security - // information (e.g., oauth2 token) which requires secure connection on an insecure - // connection. - errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)") - // errCredentialsConflict indicates that grpc.WithTransportCredentials() - // and grpc.WithInsecure() are both called for a connection. - errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)") - // errNetworkIO indicates that the connection is down due to some network I/O error. - errNetworkIO = errors.New("grpc: failed with network I/O error") -) - -// dialOptions configure a Dial call. dialOptions are set by the DialOption -// values passed to Dial. -type dialOptions struct { - unaryInt UnaryClientInterceptor - streamInt StreamClientInterceptor - cp Compressor - dc Decompressor - bs backoff.Strategy - block bool - insecure bool - timeout time.Duration - scChan <-chan ServiceConfig - copts transport.ConnectOptions - callOptions []CallOption - // This is used by v1 balancer dial option WithBalancer to support v1 - // balancer, and also by WithBalancerName dial option. - balancerBuilder balancer.Builder - // This is to support grpclb. - resolverBuilder resolver.Builder - waitForHandshake bool - channelzParentID int64 - disableServiceConfig bool -} - -const ( - defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4 - defaultClientMaxSendMessageSize = math.MaxInt32 -) - -// RegisterChannelz turns on channelz service. -// This is an EXPERIMENTAL API. -func RegisterChannelz() { - channelz.TurnOn() -} - -// DialOption configures how we set up the connection. -type DialOption func(*dialOptions) - -// WithWaitForHandshake blocks until the initial settings frame is received from the -// server before assigning RPCs to the connection. -// Experimental API. -func WithWaitForHandshake() DialOption { - return func(o *dialOptions) { - o.waitForHandshake = true - } -} - -// WithWriteBufferSize lets you set the size of write buffer, this determines how much data can be batched -// before doing a write on the wire. -func WithWriteBufferSize(s int) DialOption { - return func(o *dialOptions) { - o.copts.WriteBufferSize = s - } -} - -// WithReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most -// for each read syscall. -func WithReadBufferSize(s int) DialOption { - return func(o *dialOptions) { - o.copts.ReadBufferSize = s - } -} - -// WithInitialWindowSize returns a DialOption which sets the value for initial window size on a stream. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func WithInitialWindowSize(s int32) DialOption { - return func(o *dialOptions) { - o.copts.InitialWindowSize = s - } -} - -// WithInitialConnWindowSize returns a DialOption which sets the value for initial window size on a connection. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func WithInitialConnWindowSize(s int32) DialOption { - return func(o *dialOptions) { - o.copts.InitialConnWindowSize = s - } -} - -// WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. -// -// Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. -func WithMaxMsgSize(s int) DialOption { - return WithDefaultCallOptions(MaxCallRecvMsgSize(s)) -} - -// WithDefaultCallOptions returns a DialOption which sets the default CallOptions for calls over the connection. -func WithDefaultCallOptions(cos ...CallOption) DialOption { - return func(o *dialOptions) { - o.callOptions = append(o.callOptions, cos...) - } -} - -// WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling. -// -// Deprecated: use WithDefaultCallOptions(CallCustomCodec(c)) instead. -func WithCodec(c Codec) DialOption { - return WithDefaultCallOptions(CallCustomCodec(c)) -} - -// WithCompressor returns a DialOption which sets a Compressor to use for -// message compression. It has lower priority than the compressor set by -// the UseCompressor CallOption. -// -// Deprecated: use UseCompressor instead. -func WithCompressor(cp Compressor) DialOption { - return func(o *dialOptions) { - o.cp = cp - } -} - -// WithDecompressor returns a DialOption which sets a Decompressor to use for -// incoming message decompression. If incoming response messages are encoded -// using the decompressor's Type(), it will be used. Otherwise, the message -// encoding will be used to look up the compressor registered via -// encoding.RegisterCompressor, which will then be used to decompress the -// message. If no compressor is registered for the encoding, an Unimplemented -// status error will be returned. -// -// Deprecated: use encoding.RegisterCompressor instead. -func WithDecompressor(dc Decompressor) DialOption { - return func(o *dialOptions) { - o.dc = dc - } -} - -// WithBalancer returns a DialOption which sets a load balancer with the v1 API. -// Name resolver will be ignored if this DialOption is specified. -// -// Deprecated: use the new balancer APIs in balancer package and WithBalancerName. -func WithBalancer(b Balancer) DialOption { - return func(o *dialOptions) { - o.balancerBuilder = &balancerWrapperBuilder{ - b: b, - } - } -} - -// WithBalancerName sets the balancer that the ClientConn will be initialized -// with. Balancer registered with balancerName will be used. This function -// panics if no balancer was registered by balancerName. -// -// The balancer cannot be overridden by balancer option specified by service -// config. -// -// This is an EXPERIMENTAL API. -func WithBalancerName(balancerName string) DialOption { - builder := balancer.Get(balancerName) - if builder == nil { - panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName)) - } - return func(o *dialOptions) { - o.balancerBuilder = builder - } -} - -// withResolverBuilder is only for grpclb. -func withResolverBuilder(b resolver.Builder) DialOption { - return func(o *dialOptions) { - o.resolverBuilder = b - } -} - -// WithServiceConfig returns a DialOption which has a channel to read the service configuration. -// -// Deprecated: service config should be received through name resolver, as specified here. -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -func WithServiceConfig(c <-chan ServiceConfig) DialOption { - return func(o *dialOptions) { - o.scChan = c - } -} - -// WithBackoffMaxDelay configures the dialer to use the provided maximum delay -// when backing off after failed connection attempts. -func WithBackoffMaxDelay(md time.Duration) DialOption { - return WithBackoffConfig(BackoffConfig{MaxDelay: md}) -} - -// WithBackoffConfig configures the dialer to use the provided backoff -// parameters after connection failures. -// -// Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up -// for use. -func WithBackoffConfig(b BackoffConfig) DialOption { - - return withBackoff(backoff.Exponential{ - MaxDelay: b.MaxDelay, - }) -} - -// withBackoff sets the backoff strategy used for connectRetryNum after a -// failed connection attempt. -// -// This can be exported if arbitrary backoff strategies are allowed by gRPC. -func withBackoff(bs backoff.Strategy) DialOption { - return func(o *dialOptions) { - o.bs = bs - } -} - -// WithBlock returns a DialOption which makes caller of Dial blocks until the underlying -// connection is up. Without this, Dial returns immediately and connecting the server -// happens in background. -func WithBlock() DialOption { - return func(o *dialOptions) { - o.block = true - } -} - -// WithInsecure returns a DialOption which disables transport security for this ClientConn. -// Note that transport security is required unless WithInsecure is set. -func WithInsecure() DialOption { - return func(o *dialOptions) { - o.insecure = true - } -} - -// WithTransportCredentials returns a DialOption which configures a -// connection level security credentials (e.g., TLS/SSL). -func WithTransportCredentials(creds credentials.TransportCredentials) DialOption { - return func(o *dialOptions) { - o.copts.TransportCredentials = creds - } -} - -// WithPerRPCCredentials returns a DialOption which sets -// credentials and places auth state on each outbound RPC. -func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption { - return func(o *dialOptions) { - o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds) - } -} - -// WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn -// initially. This is valid if and only if WithBlock() is present. -// -// Deprecated: use DialContext and context.WithTimeout instead. -func WithTimeout(d time.Duration) DialOption { - return func(o *dialOptions) { - o.timeout = d - } -} - -func withContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption { - return func(o *dialOptions) { - o.copts.Dialer = f - } -} - -func init() { - internal.WithContextDialer = withContextDialer - internal.WithResolverBuilder = withResolverBuilder -} - -// WithDialer returns a DialOption that specifies a function to use for dialing network addresses. -// If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's -// Temporary() method to decide if it should try to reconnect to the network address. -func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption { - return withContextDialer( - func(ctx context.Context, addr string) (net.Conn, error) { - if deadline, ok := ctx.Deadline(); ok { - return f(addr, deadline.Sub(time.Now())) - } - return f(addr, 0) - }) -} - -// WithStatsHandler returns a DialOption that specifies the stats handler -// for all the RPCs and underlying network connections in this ClientConn. -func WithStatsHandler(h stats.Handler) DialOption { - return func(o *dialOptions) { - o.copts.StatsHandler = h - } -} - -// FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on non-temporary dial errors. -// If f is true, and dialer returns a non-temporary error, gRPC will fail the connection to the network -// address and won't try to reconnect. -// The default value of FailOnNonTempDialError is false. -// This is an EXPERIMENTAL API. -func FailOnNonTempDialError(f bool) DialOption { - return func(o *dialOptions) { - o.copts.FailOnNonTempDialError = f - } -} - -// WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs. -func WithUserAgent(s string) DialOption { - return func(o *dialOptions) { - o.copts.UserAgent = s - } -} - -// WithKeepaliveParams returns a DialOption that specifies keepalive parameters for the client transport. -func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption { - return func(o *dialOptions) { - o.copts.KeepaliveParams = kp - } -} - -// WithUnaryInterceptor returns a DialOption that specifies the interceptor for unary RPCs. -func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption { - return func(o *dialOptions) { - o.unaryInt = f - } -} - -// WithStreamInterceptor returns a DialOption that specifies the interceptor for streaming RPCs. -func WithStreamInterceptor(f StreamClientInterceptor) DialOption { - return func(o *dialOptions) { - o.streamInt = f - } -} - -// WithAuthority returns a DialOption that specifies the value to be used as -// the :authority pseudo-header. This value only works with WithInsecure and -// has no effect if TransportCredentials are present. -func WithAuthority(a string) DialOption { - return func(o *dialOptions) { - o.copts.Authority = a - } -} - -// WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's -// parent. This function is used in nested channel creation (e.g. grpclb dial). -func WithChannelzParentID(id int64) DialOption { - return func(o *dialOptions) { - o.channelzParentID = id - } -} - -// WithDisableServiceConfig returns a DialOption that causes grpc to ignore any -// service config provided by the resolver and provides a hint to the resolver -// to not fetch service configs. -func WithDisableServiceConfig() DialOption { - return func(o *dialOptions) { - o.disableServiceConfig = true - } -} - -// Dial creates a client connection to the given target. -func Dial(target string, opts ...DialOption) (*ClientConn, error) { - return DialContext(context.Background(), target, opts...) -} - -// DialContext creates a client connection to the given target. By default, it's -// a non-blocking dial (the function won't wait for connections to be -// established, and connecting happens in the background). To make it a blocking -// dial, use WithBlock() dial option. -// -// In the non-blocking case, the ctx does not act against the connection. It -// only controls the setup steps. -// -// In the blocking case, ctx can be used to cancel or expire the pending -// connection. Once this function returns, the cancellation and expiration of -// ctx will be noop. Users should call ClientConn.Close to terminate all the -// pending operations after this function returns. -// -// The target name syntax is defined in -// https://github.com/grpc/grpc/blob/master/doc/naming.md. -// e.g. to use dns resolver, a "dns:///" prefix should be applied to the target. -func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) { - cc := &ClientConn{ - target: target, - csMgr: &connectivityStateManager{}, - conns: make(map[*addrConn]struct{}), - - blockingpicker: newPickerWrapper(), - } - cc.ctx, cc.cancel = context.WithCancel(context.Background()) - - for _, opt := range opts { - opt(&cc.dopts) - } - - if channelz.IsOn() { - if cc.dopts.channelzParentID != 0 { - cc.channelzID = channelz.RegisterChannel(cc, cc.dopts.channelzParentID, target) - } else { - cc.channelzID = channelz.RegisterChannel(cc, 0, target) - } - } - - if !cc.dopts.insecure { - if cc.dopts.copts.TransportCredentials == nil { - return nil, errNoTransportSecurity - } - } else { - if cc.dopts.copts.TransportCredentials != nil { - return nil, errCredentialsConflict - } - for _, cd := range cc.dopts.copts.PerRPCCredentials { - if cd.RequireTransportSecurity() { - return nil, errTransportCredentialsMissing - } - } - } - - cc.mkp = cc.dopts.copts.KeepaliveParams - - if cc.dopts.copts.Dialer == nil { - cc.dopts.copts.Dialer = newProxyDialer( - func(ctx context.Context, addr string) (net.Conn, error) { - network, addr := parseDialTarget(addr) - return dialContext(ctx, network, addr) - }, - ) - } - - if cc.dopts.copts.UserAgent != "" { - cc.dopts.copts.UserAgent += " " + grpcUA - } else { - cc.dopts.copts.UserAgent = grpcUA - } - - if cc.dopts.timeout > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout) - defer cancel() - } - - defer func() { - select { - case <-ctx.Done(): - conn, err = nil, ctx.Err() - default: - } - - if err != nil { - cc.Close() - } - }() - - scSet := false - if cc.dopts.scChan != nil { - // Try to get an initial service config. - select { - case sc, ok := <-cc.dopts.scChan: - if ok { - cc.sc = sc - scSet = true - } - default: - } - } - if cc.dopts.bs == nil { - cc.dopts.bs = backoff.Exponential{ - MaxDelay: DefaultBackoffConfig.MaxDelay, - } - } - if cc.dopts.resolverBuilder == nil { - // Only try to parse target when resolver builder is not already set. - cc.parsedTarget = parseTarget(cc.target) - grpclog.Infof("parsed scheme: %q", cc.parsedTarget.Scheme) - cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) - if cc.dopts.resolverBuilder == nil { - // If resolver builder is still nil, the parse target's scheme is - // not registered. Fallback to default resolver and set Endpoint to - // the original unparsed target. - grpclog.Infof("scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) - cc.parsedTarget = resolver.Target{ - Scheme: resolver.GetDefaultScheme(), - Endpoint: target, - } - cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) - } - } else { - cc.parsedTarget = resolver.Target{Endpoint: target} - } - creds := cc.dopts.copts.TransportCredentials - if creds != nil && creds.Info().ServerName != "" { - cc.authority = creds.Info().ServerName - } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" { - cc.authority = cc.dopts.copts.Authority - } else { - // Use endpoint from "scheme://authority/endpoint" as the default - // authority for ClientConn. - cc.authority = cc.parsedTarget.Endpoint - } - - if cc.dopts.scChan != nil && !scSet { - // Blocking wait for the initial service config. - select { - case sc, ok := <-cc.dopts.scChan: - if ok { - cc.sc = sc - } - case <-ctx.Done(): - return nil, ctx.Err() - } - } - if cc.dopts.scChan != nil { - go cc.scWatcher() - } - - var credsClone credentials.TransportCredentials - if creds := cc.dopts.copts.TransportCredentials; creds != nil { - credsClone = creds.Clone() - } - cc.balancerBuildOpts = balancer.BuildOptions{ - DialCreds: credsClone, - Dialer: cc.dopts.copts.Dialer, - ChannelzParentID: cc.channelzID, - } - - // Build the resolver. - cc.resolverWrapper, err = newCCResolverWrapper(cc) - if err != nil { - return nil, fmt.Errorf("failed to build resolver: %v", err) - } - // Start the resolver wrapper goroutine after resolverWrapper is created. - // - // If the goroutine is started before resolverWrapper is ready, the - // following may happen: The goroutine sends updates to cc. cc forwards - // those to balancer. Balancer creates new addrConn. addrConn fails to - // connect, and calls resolveNow(). resolveNow() tries to use the non-ready - // resolverWrapper. - cc.resolverWrapper.start() - - // A blocking dial blocks until the clientConn is ready. - if cc.dopts.block { - for { - s := cc.GetState() - if s == connectivity.Ready { - break - } - if !cc.WaitForStateChange(ctx, s) { - // ctx got timeout or canceled. - return nil, ctx.Err() - } - } - } - - return cc, nil -} - -// connectivityStateManager keeps the connectivity.State of ClientConn. -// This struct will eventually be exported so the balancers can access it. -type connectivityStateManager struct { - mu sync.Mutex - state connectivity.State - notifyChan chan struct{} -} - -// updateState updates the connectivity.State of ClientConn. -// If there's a change it notifies goroutines waiting on state change to -// happen. -func (csm *connectivityStateManager) updateState(state connectivity.State) { - csm.mu.Lock() - defer csm.mu.Unlock() - if csm.state == connectivity.Shutdown { - return - } - if csm.state == state { - return - } - csm.state = state - if csm.notifyChan != nil { - // There are other goroutines waiting on this channel. - close(csm.notifyChan) - csm.notifyChan = nil - } -} - -func (csm *connectivityStateManager) getState() connectivity.State { - csm.mu.Lock() - defer csm.mu.Unlock() - return csm.state -} - -func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} { - csm.mu.Lock() - defer csm.mu.Unlock() - if csm.notifyChan == nil { - csm.notifyChan = make(chan struct{}) - } - return csm.notifyChan -} - -// ClientConn represents a client connection to an RPC server. -type ClientConn struct { - ctx context.Context - cancel context.CancelFunc - - target string - parsedTarget resolver.Target - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerBuildOpts balancer.BuildOptions - resolverWrapper *ccResolverWrapper - blockingpicker *pickerWrapper - - mu sync.RWMutex - sc ServiceConfig - scRaw string - conns map[*addrConn]struct{} - // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters - curBalancerName string - preBalancerName string // previous balancer name. - curAddresses []resolver.Address - balancerWrapper *ccBalancerWrapper - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTime time.Time -} - -// WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or -// ctx expires. A true value is returned in former case and false in latter. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool { - ch := cc.csMgr.getNotifyChan() - if cc.csMgr.getState() != sourceState { - return true - } - select { - case <-ctx.Done(): - return false - case <-ch: - return true - } -} - -// GetState returns the connectivity.State of ClientConn. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) GetState() connectivity.State { - return cc.csMgr.getState() -} - -func (cc *ClientConn) scWatcher() { - for { - select { - case sc, ok := <-cc.dopts.scChan: - if !ok { - return - } - cc.mu.Lock() - // TODO: load balance policy runtime change is ignored. - // We may revist this decision in the future. - cc.sc = sc - cc.scRaw = "" - cc.mu.Unlock() - case <-cc.ctx.Done(): - return - } - } -} - -func (cc *ClientConn) handleResolvedAddrs(addrs []resolver.Address, err error) { - cc.mu.Lock() - defer cc.mu.Unlock() - if cc.conns == nil { - // cc was closed. - return - } - - if reflect.DeepEqual(cc.curAddresses, addrs) { - return - } - - cc.curAddresses = addrs - - if cc.dopts.balancerBuilder == nil { - // Only look at balancer types and switch balancer if balancer dial - // option is not set. - var isGRPCLB bool - for _, a := range addrs { - if a.Type == resolver.GRPCLB { - isGRPCLB = true - break - } - } - var newBalancerName string - if isGRPCLB { - newBalancerName = grpclbName - } else { - // Address list doesn't contain grpclb address. Try to pick a - // non-grpclb balancer. - newBalancerName = cc.curBalancerName - // If current balancer is grpclb, switch to the previous one. - if newBalancerName == grpclbName { - newBalancerName = cc.preBalancerName - } - // The following could be true in two cases: - // - the first time handling resolved addresses - // (curBalancerName="") - // - the first time handling non-grpclb addresses - // (curBalancerName="grpclb", preBalancerName="") - if newBalancerName == "" { - newBalancerName = PickFirstBalancerName - } - } - cc.switchBalancer(newBalancerName) - } else if cc.balancerWrapper == nil { - // Balancer dial option was set, and this is the first time handling - // resolved addresses. Build a balancer with dopts.balancerBuilder. - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) - } - - cc.balancerWrapper.handleResolvedAddrs(addrs, nil) -} - -// switchBalancer starts the switching from current balancer to the balancer -// with the given name. -// -// It will NOT send the current address list to the new balancer. If needed, -// caller of this function should send address list to the new balancer after -// this function returns. -// -// Caller must hold cc.mu. -func (cc *ClientConn) switchBalancer(name string) { - if cc.conns == nil { - return - } - - if strings.ToLower(cc.curBalancerName) == strings.ToLower(name) { - return - } - - grpclog.Infof("ClientConn switching balancer to %q", name) - if cc.dopts.balancerBuilder != nil { - grpclog.Infoln("ignoring balancer switching: Balancer DialOption used instead") - return - } - // TODO(bar switching) change this to two steps: drain and close. - // Keep track of sc in wrapper. - if cc.balancerWrapper != nil { - cc.balancerWrapper.close() - } - // Clear all stickiness state. - cc.blockingpicker.clearStickinessState() - - builder := balancer.Get(name) - if builder == nil { - grpclog.Infof("failed to get balancer builder for: %v, using pick_first instead", name) - builder = newPickfirstBuilder() - } - cc.preBalancerName = cc.curBalancerName - cc.curBalancerName = builder.Name() - cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) -} - -func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - // TODO(bar switching) send updates to all balancer wrappers when balancer - // gracefully switching is supported. - cc.balancerWrapper.handleSubConnStateChange(sc, s) - cc.mu.Unlock() -} - -// newAddrConn creates an addrConn for addrs and adds it to cc.conns. -// -// Caller needs to make sure len(addrs) > 0. -func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) { - ac := &addrConn{ - cc: cc, - addrs: addrs, - dopts: cc.dopts, - } - ac.ctx, ac.cancel = context.WithCancel(cc.ctx) - // Track ac in cc. This needs to be done before any getTransport(...) is called. - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return nil, ErrClientConnClosing - } - if channelz.IsOn() { - ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") - } - cc.conns[ac] = struct{}{} - cc.mu.Unlock() - return ac, nil -} - -// removeAddrConn removes the addrConn in the subConn from clientConn. -// It also tears down the ac with the given error. -func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) { - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return - } - delete(cc.conns, ac) - cc.mu.Unlock() - ac.tearDown(err) -} - -// ChannelzMetric returns ChannelInternalMetric of current ClientConn. -// This is an EXPERIMENTAL API. -func (cc *ClientConn) ChannelzMetric() *channelz.ChannelInternalMetric { - state := cc.GetState() - cc.czmu.RLock() - defer cc.czmu.RUnlock() - return &channelz.ChannelInternalMetric{ - State: state, - Target: cc.target, - CallsStarted: cc.callsStarted, - CallsSucceeded: cc.callsSucceeded, - CallsFailed: cc.callsFailed, - LastCallStartedTimestamp: cc.lastCallStartedTime, - } -} - -func (cc *ClientConn) incrCallsStarted() { - cc.czmu.Lock() - cc.callsStarted++ - // TODO(yuxuanli): will make this a time.Time pointer improve performance? - cc.lastCallStartedTime = time.Now() - cc.czmu.Unlock() -} - -func (cc *ClientConn) incrCallsSucceeded() { - cc.czmu.Lock() - cc.callsSucceeded++ - cc.czmu.Unlock() -} - -func (cc *ClientConn) incrCallsFailed() { - cc.czmu.Lock() - cc.callsFailed++ - cc.czmu.Unlock() -} - -// connect starts to creating transport and also starts the transport monitor -// goroutine for this ac. -// It does nothing if the ac is not IDLE. -// TODO(bar) Move this to the addrConn section. -// This was part of resetAddrConn, keep it here to make the diff look clean. -func (ac *addrConn) connect() error { - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - if ac.state != connectivity.Idle { - ac.mu.Unlock() - return nil - } - ac.state = connectivity.Connecting - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.mu.Unlock() - - // Start a goroutine connecting to the server asynchronously. - go func() { - if err := ac.resetTransport(); err != nil { - grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - ac.transportMonitor() - }() - return nil -} - -// tryUpdateAddrs tries to update ac.addrs with the new addresses list. -// -// It checks whether current connected address of ac is in the new addrs list. -// - If true, it updates ac.addrs and returns true. The ac will keep using -// the existing connection. -// - If false, it does nothing and returns false. -func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { - ac.mu.Lock() - defer ac.mu.Unlock() - grpclog.Infof("addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs) - if ac.state == connectivity.Shutdown { - ac.addrs = addrs - return true - } - - var curAddrFound bool - for _, a := range addrs { - if reflect.DeepEqual(ac.curAddr, a) { - curAddrFound = true - break - } - } - grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound) - if curAddrFound { - ac.addrs = addrs - ac.reconnectIdx = 0 // Start reconnecting from beginning in the new list. - } - - return curAddrFound -} - -// GetMethodConfig gets the method config of the input method. -// If there's an exact match for input method (i.e. /service/method), we return -// the corresponding MethodConfig. -// If there isn't an exact match for the input method, we look for the default config -// under the service (i.e /service/). If there is a default MethodConfig for -// the service, we return it. -// Otherwise, we return an empty MethodConfig. -func (cc *ClientConn) GetMethodConfig(method string) MethodConfig { - // TODO: Avoid the locking here. - cc.mu.RLock() - defer cc.mu.RUnlock() - m, ok := cc.sc.Methods[method] - if !ok { - i := strings.LastIndex(method, "/") - m = cc.sc.Methods[method[:i+1]] - } - return m -} - -func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) { - t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{}) - if err != nil { - return nil, nil, toRPCErr(err) - } - return t, done, nil -} - -// handleServiceConfig parses the service config string in JSON format to Go native -// struct ServiceConfig, and store both the struct and the JSON string in ClientConn. -func (cc *ClientConn) handleServiceConfig(js string) error { - if cc.dopts.disableServiceConfig { - return nil - } - sc, err := parseServiceConfig(js) - if err != nil { - return err - } - cc.mu.Lock() - cc.scRaw = js - cc.sc = sc - if sc.LB != nil && *sc.LB != grpclbName { // "grpclb" is not a valid balancer option in service config. - if cc.curBalancerName == grpclbName { - // If current balancer is grpclb, there's at least one grpclb - // balancer address in the resolved list. Don't switch the balancer, - // but change the previous balancer name, so if a new resolved - // address list doesn't contain grpclb address, balancer will be - // switched to *sc.LB. - cc.preBalancerName = *sc.LB - } else { - cc.switchBalancer(*sc.LB) - cc.balancerWrapper.handleResolvedAddrs(cc.curAddresses, nil) - } - } - - if envConfigStickinessOn { - var newStickinessMDKey string - if sc.stickinessMetadataKey != nil && *sc.stickinessMetadataKey != "" { - newStickinessMDKey = *sc.stickinessMetadataKey - } - // newStickinessMDKey is "" if one of the following happens: - // - stickinessMetadataKey is set to "" - // - stickinessMetadataKey field doesn't exist in service config - cc.blockingpicker.updateStickinessMDKey(strings.ToLower(newStickinessMDKey)) - } - - cc.mu.Unlock() - return nil -} - -func (cc *ClientConn) resolveNow(o resolver.ResolveNowOption) { - cc.mu.RLock() - r := cc.resolverWrapper - cc.mu.RUnlock() - if r == nil { - return - } - go r.resolveNow(o) -} - -// Close tears down the ClientConn and all underlying connections. -func (cc *ClientConn) Close() error { - defer cc.cancel() - - cc.mu.Lock() - if cc.conns == nil { - cc.mu.Unlock() - return ErrClientConnClosing - } - conns := cc.conns - cc.conns = nil - cc.csMgr.updateState(connectivity.Shutdown) - - rWrapper := cc.resolverWrapper - cc.resolverWrapper = nil - bWrapper := cc.balancerWrapper - cc.balancerWrapper = nil - cc.mu.Unlock() - - cc.blockingpicker.close() - - if rWrapper != nil { - rWrapper.close() - } - if bWrapper != nil { - bWrapper.close() - } - - for ac := range conns { - ac.tearDown(ErrClientConnClosing) - } - if channelz.IsOn() { - channelz.RemoveEntry(cc.channelzID) - } - return nil -} - -// addrConn is a network connection to a given address. -type addrConn struct { - ctx context.Context - cancel context.CancelFunc - - cc *ClientConn - addrs []resolver.Address - dopts dialOptions - events trace.EventLog - acbw balancer.SubConn - - mu sync.Mutex - curAddr resolver.Address - reconnectIdx int // The index in addrs list to start reconnecting from. - state connectivity.State - // ready is closed and becomes nil when a new transport is up or failed - // due to timeout. - ready chan struct{} - transport transport.ClientTransport - - // The reason this addrConn is torn down. - tearDownErr error - - connectRetryNum int - // backoffDeadline is the time until which resetTransport needs to - // wait before increasing connectRetryNum count. - backoffDeadline time.Time - // connectDeadline is the time by which all connection - // negotiations must complete. - connectDeadline time.Time - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsSucceeded int64 - callsFailed int64 - lastCallStartedTime time.Time -} - -// adjustParams updates parameters used to create transports upon -// receiving a GoAway. -func (ac *addrConn) adjustParams(r transport.GoAwayReason) { - switch r { - case transport.GoAwayTooManyPings: - v := 2 * ac.dopts.copts.KeepaliveParams.Time - ac.cc.mu.Lock() - if v > ac.cc.mkp.Time { - ac.cc.mkp.Time = v - } - ac.cc.mu.Unlock() - } -} - -// printf records an event in ac's event log, unless ac has been closed. -// REQUIRES ac.mu is held. -func (ac *addrConn) printf(format string, a ...interface{}) { - if ac.events != nil { - ac.events.Printf(format, a...) - } -} - -// errorf records an error in ac's event log, unless ac has been closed. -// REQUIRES ac.mu is held. -func (ac *addrConn) errorf(format string, a ...interface{}) { - if ac.events != nil { - ac.events.Errorf(format, a...) - } -} - -// resetTransport recreates a transport to the address for ac. The old -// transport will close itself on error or when the clientconn is closed. -// The created transport must receive initial settings frame from the server. -// In case that doesn't happen, transportMonitor will kill the newly created -// transport after connectDeadline has expired. -// In case there was an error on the transport before the settings frame was -// received, resetTransport resumes connecting to backends after the one that -// was previously connected to. In case end of the list is reached, resetTransport -// backs off until the original deadline. -// If the DialOption WithWaitForHandshake was set, resetTrasport returns -// successfully only after server settings are received. -// -// TODO(bar) make sure all state transitions are valid. -func (ac *addrConn) resetTransport() error { - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - ac.transport = nil - ridx := ac.reconnectIdx - ac.mu.Unlock() - ac.cc.mu.RLock() - ac.dopts.copts.KeepaliveParams = ac.cc.mkp - ac.cc.mu.RUnlock() - var backoffDeadline, connectDeadline time.Time - for connectRetryNum := 0; ; connectRetryNum++ { - ac.mu.Lock() - if ac.backoffDeadline.IsZero() { - // This means either a successful HTTP2 connection was established - // or this is the first time this addrConn is trying to establish a - // connection. - backoffFor := ac.dopts.bs.Backoff(connectRetryNum) // time.Duration. - // This will be the duration that dial gets to finish. - dialDuration := getMinConnectTimeout() - if backoffFor > dialDuration { - // Give dial more time as we keep failing to connect. - dialDuration = backoffFor - } - start := time.Now() - backoffDeadline = start.Add(backoffFor) - connectDeadline = start.Add(dialDuration) - ridx = 0 // Start connecting from the beginning. - } else { - // Continue trying to connect with the same deadlines. - connectRetryNum = ac.connectRetryNum - backoffDeadline = ac.backoffDeadline - connectDeadline = ac.connectDeadline - ac.backoffDeadline = time.Time{} - ac.connectDeadline = time.Time{} - ac.connectRetryNum = 0 - } - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return errConnClosing - } - ac.printf("connecting") - if ac.state != connectivity.Connecting { - ac.state = connectivity.Connecting - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - } - // copy ac.addrs in case of race - addrsIter := make([]resolver.Address, len(ac.addrs)) - copy(addrsIter, ac.addrs) - copts := ac.dopts.copts - ac.mu.Unlock() - connected, err := ac.createTransport(connectRetryNum, ridx, backoffDeadline, connectDeadline, addrsIter, copts) - if err != nil { - return err - } - if connected { - return nil - } - } -} - -// createTransport creates a connection to one of the backends in addrs. -// It returns true if a connection was established. -func (ac *addrConn) createTransport(connectRetryNum, ridx int, backoffDeadline, connectDeadline time.Time, addrs []resolver.Address, copts transport.ConnectOptions) (bool, error) { - for i := ridx; i < len(addrs); i++ { - addr := addrs[i] - target := transport.TargetInfo{ - Addr: addr.Addr, - Metadata: addr.Metadata, - Authority: ac.cc.authority, - } - done := make(chan struct{}) - onPrefaceReceipt := func() { - ac.mu.Lock() - close(done) - if !ac.backoffDeadline.IsZero() { - // If we haven't already started reconnecting to - // other backends. - // Note, this can happen when writer notices an error - // and triggers resetTransport while at the same time - // reader receives the preface and invokes this closure. - ac.backoffDeadline = time.Time{} - ac.connectDeadline = time.Time{} - ac.connectRetryNum = 0 - } - ac.mu.Unlock() - } - // Do not cancel in the success path because of - // this issue in Go1.6: https://github.com/golang/go/issues/15078. - connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) - if channelz.IsOn() { - copts.ChannelzParentID = ac.channelzID - } - newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt) - if err != nil { - cancel() - ac.cc.blockingpicker.updateConnectionError(err) - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - // ac.tearDown(...) has been invoked. - ac.mu.Unlock() - return false, errConnClosing - } - ac.mu.Unlock() - grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err) - continue - } - if ac.dopts.waitForHandshake { - select { - case <-done: - case <-connectCtx.Done(): - // Didn't receive server preface, must kill this new transport now. - grpclog.Warningf("grpc: addrConn.createTransport failed to receive server preface before deadline.") - newTr.Close() - break - case <-ac.ctx.Done(): - } - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - // ac.tearDonn(...) has been invoked. - newTr.Close() - return false, errConnClosing - } - ac.printf("ready") - ac.state = connectivity.Ready - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.transport = newTr - ac.curAddr = addr - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - select { - case <-done: - // If the server has responded back with preface already, - // don't set the reconnect parameters. - default: - ac.connectRetryNum = connectRetryNum - ac.backoffDeadline = backoffDeadline - ac.connectDeadline = connectDeadline - ac.reconnectIdx = i + 1 // Start reconnecting from the next backend in the list. - } - ac.mu.Unlock() - return true, nil - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return false, errConnClosing - } - ac.state = connectivity.TransientFailure - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.cc.resolveNow(resolver.ResolveNowOption{}) - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - ac.mu.Unlock() - timer := time.NewTimer(backoffDeadline.Sub(time.Now())) - select { - case <-timer.C: - case <-ac.ctx.Done(): - timer.Stop() - return false, ac.ctx.Err() - } - return false, nil -} - -// Run in a goroutine to track the error in transport and create the -// new transport if an error happens. It returns when the channel is closing. -func (ac *addrConn) transportMonitor() { - for { - var timer *time.Timer - var cdeadline <-chan time.Time - ac.mu.Lock() - t := ac.transport - if !ac.connectDeadline.IsZero() { - timer = time.NewTimer(ac.connectDeadline.Sub(time.Now())) - cdeadline = timer.C - } - ac.mu.Unlock() - // Block until we receive a goaway or an error occurs. - select { - case <-t.GoAway(): - done := t.Error() - cleanup := t.Close - // Since this transport will be orphaned (won't have a transportMonitor) - // we need to launch a goroutine to keep track of clientConn.Close() - // happening since it might not be noticed by any other goroutine for a while. - go func() { - <-done - cleanup() - }() - case <-t.Error(): - // In case this is triggered because clientConn.Close() - // was called, we want to immeditately close the transport - // since no other goroutine might notice it for a while. - t.Close() - case <-cdeadline: - ac.mu.Lock() - // This implies that client received server preface. - if ac.backoffDeadline.IsZero() { - ac.mu.Unlock() - continue - } - ac.mu.Unlock() - timer = nil - // No server preface received until deadline. - // Kill the connection. - grpclog.Warningf("grpc: addrConn.transportMonitor didn't get server preface after waiting. Closing the new transport now.") - t.Close() - } - if timer != nil { - timer.Stop() - } - // If a GoAway happened, regardless of error, adjust our keepalive - // parameters as appropriate. - select { - case <-t.GoAway(): - ac.adjustParams(t.GetGoAwayReason()) - default: - } - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - ac.mu.Unlock() - return - } - // Set connectivity state to TransientFailure before calling - // resetTransport. Transition READY->CONNECTING is not valid. - ac.state = connectivity.TransientFailure - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - ac.cc.resolveNow(resolver.ResolveNowOption{}) - ac.curAddr = resolver.Address{} - ac.mu.Unlock() - if err := ac.resetTransport(); err != nil { - ac.mu.Lock() - ac.printf("transport exiting: %v", err) - ac.mu.Unlock() - grpclog.Warningf("grpc: addrConn.transportMonitor exits due to: %v", err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - } -} - -// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or -// iv) transport is in connectivity.TransientFailure and there is a balancer/failfast is true. -func (ac *addrConn) wait(ctx context.Context, hasBalancer, failfast bool) (transport.ClientTransport, error) { - for { - ac.mu.Lock() - switch { - case ac.state == connectivity.Shutdown: - if failfast || !hasBalancer { - // RPC is failfast or balancer is nil. This RPC should fail with ac.tearDownErr. - err := ac.tearDownErr - ac.mu.Unlock() - return nil, err - } - ac.mu.Unlock() - return nil, errConnClosing - case ac.state == connectivity.Ready: - ct := ac.transport - ac.mu.Unlock() - return ct, nil - case ac.state == connectivity.TransientFailure: - if failfast || hasBalancer { - ac.mu.Unlock() - return nil, errConnUnavailable - } - } - ready := ac.ready - if ready == nil { - ready = make(chan struct{}) - ac.ready = ready - } - ac.mu.Unlock() - select { - case <-ctx.Done(): - return nil, toRPCErr(ctx.Err()) - // Wait until the new transport is ready or failed. - case <-ready: - } - } -} - -// getReadyTransport returns the transport if ac's state is READY. -// Otherwise it returns nil, false. -// If ac's state is IDLE, it will trigger ac to connect. -func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { - ac.mu.Lock() - if ac.state == connectivity.Ready { - t := ac.transport - ac.mu.Unlock() - return t, true - } - var idle bool - if ac.state == connectivity.Idle { - idle = true - } - ac.mu.Unlock() - // Trigger idle ac to connect. - if idle { - ac.connect() - } - return nil, false -} - -// tearDown starts to tear down the addrConn. -// TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in -// some edge cases (e.g., the caller opens and closes many addrConn's in a -// tight loop. -// tearDown doesn't remove ac from ac.cc.conns. -func (ac *addrConn) tearDown(err error) { - ac.cancel() - ac.mu.Lock() - defer ac.mu.Unlock() - if ac.state == connectivity.Shutdown { - return - } - ac.curAddr = resolver.Address{} - if err == errConnDrain && ac.transport != nil { - // GracefulClose(...) may be executed multiple times when - // i) receiving multiple GoAway frames from the server; or - // ii) there are concurrent name resolver/Balancer triggered - // address removal and GoAway. - ac.transport.GracefulClose() - } - ac.state = connectivity.Shutdown - ac.tearDownErr = err - ac.cc.handleSubConnStateChange(ac.acbw, ac.state) - if ac.events != nil { - ac.events.Finish() - ac.events = nil - } - if ac.ready != nil { - close(ac.ready) - ac.ready = nil - } - if channelz.IsOn() { - channelz.RemoveEntry(ac.channelzID) - } -} - -func (ac *addrConn) getState() connectivity.State { - ac.mu.Lock() - defer ac.mu.Unlock() - return ac.state -} - -func (ac *addrConn) getCurAddr() (ret resolver.Address) { - ac.mu.Lock() - ret = ac.curAddr - ac.mu.Unlock() - return -} - -func (ac *addrConn) ChannelzMetric() *channelz.ChannelInternalMetric { - ac.mu.Lock() - addr := ac.curAddr.Addr - ac.mu.Unlock() - state := ac.getState() - ac.czmu.RLock() - defer ac.czmu.RUnlock() - return &channelz.ChannelInternalMetric{ - State: state, - Target: addr, - CallsStarted: ac.callsStarted, - CallsSucceeded: ac.callsSucceeded, - CallsFailed: ac.callsFailed, - LastCallStartedTimestamp: ac.lastCallStartedTime, - } -} - -func (ac *addrConn) incrCallsStarted() { - ac.czmu.Lock() - ac.callsStarted++ - ac.lastCallStartedTime = time.Now() - ac.czmu.Unlock() -} - -func (ac *addrConn) incrCallsSucceeded() { - ac.czmu.Lock() - ac.callsSucceeded++ - ac.czmu.Unlock() -} - -func (ac *addrConn) incrCallsFailed() { - ac.czmu.Lock() - ac.callsFailed++ - ac.czmu.Unlock() -} - -// ErrClientConnTimeout indicates that the ClientConn cannot establish the -// underlying connections within the specified timeout. -// -// Deprecated: This error is never returned by grpc and should not be -// referenced by users. -var ErrClientConnTimeout = errors.New("grpc: timed out when dialing") diff --git a/examples/google.golang.org/grpc/clientconn_test.go b/examples/google.golang.org/grpc/clientconn_test.go deleted file mode 100755 index fd239d3..0000000 --- a/examples/google.golang.org/grpc/clientconn_test.go +++ /dev/null @@ -1,678 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "math" - "net" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/internal/backoff" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - _ "google.golang.org/grpc/resolver/passthrough" - "google.golang.org/grpc/testdata" -) - -var ( - mutableMinConnectTimeout = time.Second * 20 -) - -func init() { - getMinConnectTimeout = func() time.Duration { - return time.Duration(atomic.LoadInt64((*int64)(&mutableMinConnectTimeout))) - } -} - -func assertState(wantState connectivity.State, cc *ClientConn) (connectivity.State, bool) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - var state connectivity.State - for state = cc.GetState(); state != wantState && cc.WaitForStateChange(ctx, state); state = cc.GetState() { - } - return state, state == wantState -} - -func TestDialWithMultipleBackendsNotSendingServerPreface(t *testing.T) { - defer leakcheck.Check(t) - numServers := 2 - servers := make([]net.Listener, numServers) - var err error - for i := 0; i < numServers; i++ { - servers[i], err = net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error while listening. Err: %v", err) - } - } - dones := make([]chan struct{}, numServers) - for i := 0; i < numServers; i++ { - dones[i] = make(chan struct{}) - } - for i := 0; i < numServers; i++ { - go func(i int) { - defer func() { - close(dones[i]) - }() - conn, err := servers[i].Accept() - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - defer conn.Close() - switch i { - case 0: // 1st server accepts the connection and immediately closes it. - case 1: // 2nd server accepts the connection and sends settings frames. - framer := http2.NewFramer(conn, conn) - if err := framer.WriteSettings(http2.Setting{}); err != nil { - t.Errorf("Error while writing settings frame. %v", err) - return - } - conn.SetDeadline(time.Now().Add(time.Second)) - buf := make([]byte, 1024) - for { // Make sure the connection stays healthy. - _, err = conn.Read(buf) - if err == nil { - continue - } - if nerr, ok := err.(net.Error); !ok || !nerr.Timeout() { - t.Errorf("Server expected the conn.Read(_) to timeout instead got error: %v", err) - } - return - } - } - }(i) - } - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - resolvedAddrs := make([]resolver.Address, numServers) - for i := 0; i < numServers; i++ { - resolvedAddrs[i] = resolver.Address{Addr: servers[i].Addr().String()} - } - r.InitialAddrs(resolvedAddrs) - client, err := Dial(r.Scheme()+":///test.server", WithInsecure()) - if err != nil { - t.Errorf("Dial failed. Err: %v", err) - } else { - defer client.Close() - } - time.Sleep(time.Second) // Close the servers after a second for cleanup. - for _, s := range servers { - s.Close() - } - for _, done := range dones { - <-done - } -} - -func TestDialWaitsForServerSettings(t *testing.T) { - defer leakcheck.Check(t) - server, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error while listening. Err: %v", err) - } - defer server.Close() - done := make(chan struct{}) - sent := make(chan struct{}) - dialDone := make(chan struct{}) - go func() { // Launch the server. - defer func() { - close(done) - }() - conn, err := server.Accept() - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - defer conn.Close() - // Sleep for a little bit to make sure that Dial on client - // side blocks until settings are received. - time.Sleep(500 * time.Millisecond) - framer := http2.NewFramer(conn, conn) - close(sent) - if err := framer.WriteSettings(http2.Setting{}); err != nil { - t.Errorf("Error while writing settings. Err: %v", err) - return - } - <-dialDone // Close conn only after dial returns. - }() - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - client, err := DialContext(ctx, server.Addr().String(), WithInsecure(), WithWaitForHandshake(), WithBlock()) - close(dialDone) - if err != nil { - cancel() - t.Fatalf("Error while dialing. Err: %v", err) - } - defer client.Close() - select { - case <-sent: - default: - t.Fatalf("Dial returned before server settings were sent") - } - <-done - -} - -func TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) { - mctBkp := getMinConnectTimeout() - // Call this only after transportMonitor goroutine has ended. - defer func() { - atomic.StoreInt64((*int64)(&mutableMinConnectTimeout), int64(mctBkp)) - - }() - defer leakcheck.Check(t) - atomic.StoreInt64((*int64)(&mutableMinConnectTimeout), int64(time.Millisecond)*500) - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error while listening. Err: %v", err) - } - var ( - conn2 net.Conn - over uint32 - ) - defer func() { - lis.Close() - // conn2 shouldn't be closed until the client has - // observed a successful test. - if conn2 != nil { - conn2.Close() - } - }() - done := make(chan struct{}) - go func() { // Launch the server. - defer close(done) - conn1, err := lis.Accept() - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - defer conn1.Close() - // Don't send server settings and the client should close the connection and try again. - conn2, err = lis.Accept() // Accept a reconnection request from client. - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - framer := http2.NewFramer(conn2, conn2) - if err = framer.WriteSettings(http2.Setting{}); err != nil { - t.Errorf("Error while writing settings. Err: %v", err) - return - } - b := make([]byte, 8) - for { - _, err = conn2.Read(b) - if err == nil { - continue - } - if atomic.LoadUint32(&over) == 1 { - // The connection stayed alive for the timer. - // Success. - return - } - t.Errorf("Unexpected error while reading. Err: %v, want timeout error", err) - break - } - }() - client, err := Dial(lis.Addr().String(), WithInsecure()) - if err != nil { - t.Fatalf("Error while dialing. Err: %v", err) - } - time.Sleep(time.Second * 2) // Let things play out. - atomic.StoreUint32(&over, 1) - lis.Close() - client.Close() - <-done -} - -func TestBackoffWhenNoServerPrefaceReceived(t *testing.T) { - defer leakcheck.Check(t) - server, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error while listening. Err: %v", err) - } - defer server.Close() - done := make(chan struct{}) - go func() { // Launch the server. - defer func() { - close(done) - }() - conn, err := server.Accept() // Accept the connection only to close it immediately. - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - prevAt := time.Now() - conn.Close() - var prevDuration time.Duration - // Make sure the retry attempts are backed off properly. - for i := 0; i < 3; i++ { - conn, err := server.Accept() - if err != nil { - t.Errorf("Error while accepting. Err: %v", err) - return - } - meow := time.Now() - conn.Close() - dr := meow.Sub(prevAt) - if dr <= prevDuration { - t.Errorf("Client backoff did not increase with retries. Previous duration: %v, current duration: %v", prevDuration, dr) - return - } - prevDuration = dr - prevAt = meow - } - }() - client, err := Dial(server.Addr().String(), WithInsecure()) - if err != nil { - t.Fatalf("Error while dialing. Err: %v", err) - } - defer client.Close() - <-done - -} - -func TestConnectivityStates(t *testing.T) { - defer leakcheck.Check(t) - servers, resolver, cleanup := startServers(t, 2, math.MaxUint32) - defer cleanup() - cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure()) - if err != nil { - t.Fatalf("Dial(\"foo.bar.com\", WithBalancer(_)) = _, %v, want _ ", err) - } - defer cc.Close() - wantState := connectivity.Ready - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - // Send an update to delete the server connection (tearDown addrConn). - update := []*naming.Update{ - { - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }, - } - resolver.w.inject(update) - wantState = connectivity.TransientFailure - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - update[0] = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - resolver.w.inject(update) - wantState = connectivity.Ready - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - -} - -func TestWithTimeout(t *testing.T) { - defer leakcheck.Check(t) - conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) - if err == nil { - conn.Close() - } - if err != context.DeadlineExceeded { - t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) - } -} - -func TestWithTransportCredentialsTLS(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - defer leakcheck.Check(t) - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := DialContext(ctx, "passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithBlock()) - if err == nil { - conn.Close() - } - if err != context.DeadlineExceeded { - t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) - } -} - -func TestDefaultAuthority(t *testing.T) { - defer leakcheck.Check(t) - target := "Non-Existent.Server:8080" - conn, err := Dial(target, WithInsecure()) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, ", err) - } - defer conn.Close() - if conn.authority != target { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, target) - } -} - -func TestTLSServerNameOverwrite(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName) - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds)) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, ", err) - } - defer conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestWithAuthority(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - conn, err := Dial("passthrough:///Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName)) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, ", err) - } - defer conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestWithAuthorityAndTLS(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName) - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(creds), WithAuthority("no.effect.authority")) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, ", err) - } - defer conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestDialContextCancel(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { - t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) - } -} - -// blockingBalancer mimics the behavior of balancers whose initialization takes a long time. -// In this test, reading from blockingBalancer.Notify() blocks forever. -type blockingBalancer struct { - ch chan []Address -} - -func newBlockingBalancer() Balancer { - return &blockingBalancer{ch: make(chan []Address)} -} -func (b *blockingBalancer) Start(target string, config BalancerConfig) error { - return nil -} -func (b *blockingBalancer) Up(addr Address) func(error) { - return nil -} -func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - return Address{}, nil, nil -} -func (b *blockingBalancer) Notify() <-chan []Address { - return b.ch -} -func (b *blockingBalancer) Close() error { - close(b.ch) - return nil -} - -func TestDialWithBlockingBalancer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - dialDone := make(chan struct{}) - go func() { - DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) - close(dialDone) - }() - cancel() - <-dialDone -} - -// securePerRPCCredentials always requires transport security. -type securePerRPCCredentials struct{} - -func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return nil, nil -} - -func (c securePerRPCCredentials) RequireTransportSecurity() bool { - return true -} - -func TestCredentialsMisuse(t *testing.T) { - defer leakcheck.Check(t) - tlsCreds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - t.Fatalf("Failed to create authenticator %v", err) - } - // Two conflicting credential configurations - if _, err := Dial("passthrough:///Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { - t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) - } - // security info on insecure connection - if _, err := Dial("passthrough:///Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { - t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) - } -} - -func TestWithBackoffConfigDefault(t *testing.T) { - defer leakcheck.Check(t) - testBackoffConfigSet(t, &DefaultBackoffConfig) -} - -func TestWithBackoffConfig(t *testing.T) { - defer leakcheck.Check(t) - b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2} - expected := b - testBackoffConfigSet(t, &expected, WithBackoffConfig(b)) -} - -func TestWithBackoffMaxDelay(t *testing.T) { - defer leakcheck.Check(t) - md := DefaultBackoffConfig.MaxDelay / 2 - expected := BackoffConfig{MaxDelay: md} - testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md)) -} - -func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { - opts = append(opts, WithInsecure()) - conn, err := Dial("passthrough:///foo:80", opts...) - if err != nil { - t.Fatalf("unexpected error dialing connection: %v", err) - } - defer conn.Close() - - if conn.dopts.bs == nil { - t.Fatalf("backoff config not set") - } - - actual, ok := conn.dopts.bs.(backoff.Exponential) - if !ok { - t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) - } - - expectedValue := backoff.Exponential{ - MaxDelay: expected.MaxDelay, - } - if actual != expectedValue { - t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) - } -} - -// emptyBalancer returns an empty set of servers. -type emptyBalancer struct { - ch chan []Address -} - -func newEmptyBalancer() Balancer { - return &emptyBalancer{ch: make(chan []Address, 1)} -} -func (b *emptyBalancer) Start(_ string, _ BalancerConfig) error { - b.ch <- nil - return nil -} -func (b *emptyBalancer) Up(_ Address) func(error) { - return nil -} -func (b *emptyBalancer) Get(_ context.Context, _ BalancerGetOptions) (Address, func(), error) { - return Address{}, nil, nil -} -func (b *emptyBalancer) Notify() <-chan []Address { - return b.ch -} -func (b *emptyBalancer) Close() error { - close(b.ch) - return nil -} - -func TestNonblockingDialWithEmptyBalancer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - dialDone := make(chan error) - go func() { - dialDone <- func() error { - conn, err := DialContext(ctx, "Non-Existent.Server:80", WithInsecure(), WithBalancer(newEmptyBalancer())) - if err != nil { - return err - } - return conn.Close() - }() - }() - if err := <-dialDone; err != nil { - t.Fatalf("unexpected error dialing connection: %s", err) - } -} - -func TestResolverServiceConfigBeforeAddressNotPanic(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - // SwitchBalancer before NewAddress. There was no balancer created, this - // makes sure we don't call close on nil balancerWrapper. - r.NewServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) // This should not panic. - - time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn. -} - -func TestResolverEmptyUpdateNotPanic(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - // This make sure we don't create addrConn with empty address list. - r.NewAddress([]resolver.Address{}) // This should not panic. - - time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn. -} - -func TestClientUpdatesParamsAfterGoAway(t *testing.T) { - defer leakcheck.Check(t) - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen. Err: %v", err) - } - defer lis.Close() - addr := lis.Addr().String() - s := NewServer() - go s.Serve(lis) - defer s.Stop() - cc, err := Dial(addr, WithBlock(), WithInsecure(), WithKeepaliveParams(keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 100 * time.Millisecond, - PermitWithoutStream: true, - })) - if err != nil { - t.Fatalf("Dial(%s, _) = _, %v, want _, ", addr, err) - } - defer cc.Close() - time.Sleep(1 * time.Second) - cc.mu.RLock() - defer cc.mu.RUnlock() - v := cc.mkp.Time - if v < 100*time.Millisecond { - t.Fatalf("cc.dopts.copts.Keepalive.Time = %v , want 100ms", v) - } -} - -func TestDisableServiceConfigOption(t *testing.T) { - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - addr := r.Scheme() + ":///non.existent" - cc, err := Dial(addr, WithInsecure(), WithDisableServiceConfig()) - if err != nil { - t.Fatalf("Dial(%s, _) = _, %v, want _, ", addr, err) - } - defer cc.Close() - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": true - } - ] -}`) - time.Sleep(1 * time.Second) - m := cc.GetMethodConfig("/foo/Bar") - if m.WaitForReady != nil { - t.Fatalf("want: method (\"/foo/bar/\") config to be empty, got: %v", m) - } -} diff --git a/examples/google.golang.org/grpc/codec.go b/examples/google.golang.org/grpc/codec.go deleted file mode 100755 index 1297765..0000000 --- a/examples/google.golang.org/grpc/codec.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "google.golang.org/grpc/encoding" - _ "google.golang.org/grpc/encoding/proto" // to register the Codec for "proto" -) - -// baseCodec contains the functionality of both Codec and encoding.Codec, but -// omits the name/string, which vary between the two and are not needed for -// anything besides the registry in the encoding package. -type baseCodec interface { - Marshal(v interface{}) ([]byte, error) - Unmarshal(data []byte, v interface{}) error -} - -var _ baseCodec = Codec(nil) -var _ baseCodec = encoding.Codec(nil) - -// Codec defines the interface gRPC uses to encode and decode messages. -// Note that implementations of this interface must be thread safe; -// a Codec's methods can be called from concurrent goroutines. -// -// Deprecated: use encoding.Codec instead. -type Codec interface { - // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) - // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error - // String returns the name of the Codec implementation. This is unused by - // gRPC. - String() string -} diff --git a/examples/google.golang.org/grpc/codec_test.go b/examples/google.golang.org/grpc/codec_test.go deleted file mode 100755 index 3fda708..0000000 --- a/examples/google.golang.org/grpc/codec_test.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "testing" - - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/encoding/proto" -) - -func TestGetCodecForProtoIsNotNil(t *testing.T) { - if encoding.GetCodec(proto.Name) == nil { - t.Fatalf("encoding.GetCodec(%q) must not be nil by default", proto.Name) - } -} diff --git a/examples/google.golang.org/grpc/codegen.sh b/examples/google.golang.org/grpc/codegen.sh deleted file mode 100755 index 4cdc6ba..0000000 --- a/examples/google.golang.org/grpc/codegen.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -# This script serves as an example to demonstrate how to generate the gRPC-Go -# interface and the related messages from .proto file. -# -# It assumes the installation of i) Google proto buffer compiler at -# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen -# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have -# not, please install them first. -# -# We recommend running this script at $GOPATH/src. -# -# If this is not what you need, feel free to make your own scripts. Again, this -# script is for demonstration purpose. -# -proto=$1 -protoc --go_out=plugins=grpc:. $proto diff --git a/examples/google.golang.org/grpc/codes/code_string.go b/examples/google.golang.org/grpc/codes/code_string.go deleted file mode 100755 index 0b206a5..0000000 --- a/examples/google.golang.org/grpc/codes/code_string.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package codes - -import "strconv" - -func (c Code) String() string { - switch c { - case OK: - return "OK" - case Canceled: - return "Canceled" - case Unknown: - return "Unknown" - case InvalidArgument: - return "InvalidArgument" - case DeadlineExceeded: - return "DeadlineExceeded" - case NotFound: - return "NotFound" - case AlreadyExists: - return "AlreadyExists" - case PermissionDenied: - return "PermissionDenied" - case ResourceExhausted: - return "ResourceExhausted" - case FailedPrecondition: - return "FailedPrecondition" - case Aborted: - return "Aborted" - case OutOfRange: - return "OutOfRange" - case Unimplemented: - return "Unimplemented" - case Internal: - return "Internal" - case Unavailable: - return "Unavailable" - case DataLoss: - return "DataLoss" - case Unauthenticated: - return "Unauthenticated" - default: - return "Code(" + strconv.FormatInt(int64(c), 10) + ")" - } -} diff --git a/examples/google.golang.org/grpc/codes/codes.go b/examples/google.golang.org/grpc/codes/codes.go deleted file mode 100755 index d9b9d57..0000000 --- a/examples/google.golang.org/grpc/codes/codes.go +++ /dev/null @@ -1,197 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package codes defines the canonical error codes used by gRPC. It is -// consistent across various languages. -package codes // import "google.golang.org/grpc/codes" - -import ( - "fmt" - "strconv" -) - -// A Code is an unsigned 32-bit error code as defined in the gRPC spec. -type Code uint32 - -const ( - // OK is returned on success. - OK Code = 0 - - // Canceled indicates the operation was canceled (typically by the caller). - Canceled Code = 1 - - // Unknown error. An example of where this error may be returned is - // if a Status value received from another address space belongs to - // an error-space that is not known in this address space. Also - // errors raised by APIs that do not return enough error information - // may be converted to this error. - Unknown Code = 2 - - // InvalidArgument indicates client specified an invalid argument. - // Note that this differs from FailedPrecondition. It indicates arguments - // that are problematic regardless of the state of the system - // (e.g., a malformed file name). - InvalidArgument Code = 3 - - // DeadlineExceeded means operation expired before completion. - // For operations that change the state of the system, this error may be - // returned even if the operation has completed successfully. For - // example, a successful response from a server could have been delayed - // long enough for the deadline to expire. - DeadlineExceeded Code = 4 - - // NotFound means some requested entity (e.g., file or directory) was - // not found. - NotFound Code = 5 - - // AlreadyExists means an attempt to create an entity failed because one - // already exists. - AlreadyExists Code = 6 - - // PermissionDenied indicates the caller does not have permission to - // execute the specified operation. It must not be used for rejections - // caused by exhausting some resource (use ResourceExhausted - // instead for those errors). It must not be - // used if the caller cannot be identified (use Unauthenticated - // instead for those errors). - PermissionDenied Code = 7 - - // ResourceExhausted indicates some resource has been exhausted, perhaps - // a per-user quota, or perhaps the entire file system is out of space. - ResourceExhausted Code = 8 - - // FailedPrecondition indicates operation was rejected because the - // system is not in a state required for the operation's execution. - // For example, directory to be deleted may be non-empty, an rmdir - // operation is applied to a non-directory, etc. - // - // A litmus test that may help a service implementor in deciding - // between FailedPrecondition, Aborted, and Unavailable: - // (a) Use Unavailable if the client can retry just the failing call. - // (b) Use Aborted if the client should retry at a higher-level - // (e.g., restarting a read-modify-write sequence). - // (c) Use FailedPrecondition if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" - // fails because the directory is non-empty, FailedPrecondition - // should be returned since the client should not retry unless - // they have first fixed up the directory by deleting files from it. - // (d) Use FailedPrecondition if the client performs conditional - // REST Get/Update/Delete on a resource and the resource on the - // server does not match the condition. E.g., conflicting - // read-modify-write on the same resource. - FailedPrecondition Code = 9 - - // Aborted indicates the operation was aborted, typically due to a - // concurrency issue like sequencer check failures, transaction aborts, - // etc. - // - // See litmus test above for deciding between FailedPrecondition, - // Aborted, and Unavailable. - Aborted Code = 10 - - // OutOfRange means operation was attempted past the valid range. - // E.g., seeking or reading past end of file. - // - // Unlike InvalidArgument, this error indicates a problem that may - // be fixed if the system state changes. For example, a 32-bit file - // system will generate InvalidArgument if asked to read at an - // offset that is not in the range [0,2^32-1], but it will generate - // OutOfRange if asked to read from an offset past the current - // file size. - // - // There is a fair bit of overlap between FailedPrecondition and - // OutOfRange. We recommend using OutOfRange (the more specific - // error) when it applies so that callers who are iterating through - // a space can easily look for an OutOfRange error to detect when - // they are done. - OutOfRange Code = 11 - - // Unimplemented indicates operation is not implemented or not - // supported/enabled in this service. - Unimplemented Code = 12 - - // Internal errors. Means some invariants expected by underlying - // system has been broken. If you see one of these errors, - // something is very broken. - Internal Code = 13 - - // Unavailable indicates the service is currently unavailable. - // This is a most likely a transient condition and may be corrected - // by retrying with a backoff. - // - // See litmus test above for deciding between FailedPrecondition, - // Aborted, and Unavailable. - Unavailable Code = 14 - - // DataLoss indicates unrecoverable data loss or corruption. - DataLoss Code = 15 - - // Unauthenticated indicates the request does not have valid - // authentication credentials for the operation. - Unauthenticated Code = 16 - - _maxCode = 17 -) - -var strToCode = map[string]Code{ - `"OK"`: OK, - `"CANCELLED"`:/* [sic] */ Canceled, - `"UNKNOWN"`: Unknown, - `"INVALID_ARGUMENT"`: InvalidArgument, - `"DEADLINE_EXCEEDED"`: DeadlineExceeded, - `"NOT_FOUND"`: NotFound, - `"ALREADY_EXISTS"`: AlreadyExists, - `"PERMISSION_DENIED"`: PermissionDenied, - `"RESOURCE_EXHAUSTED"`: ResourceExhausted, - `"FAILED_PRECONDITION"`: FailedPrecondition, - `"ABORTED"`: Aborted, - `"OUT_OF_RANGE"`: OutOfRange, - `"UNIMPLEMENTED"`: Unimplemented, - `"INTERNAL"`: Internal, - `"UNAVAILABLE"`: Unavailable, - `"DATA_LOSS"`: DataLoss, - `"UNAUTHENTICATED"`: Unauthenticated, -} - -// UnmarshalJSON unmarshals b into the Code. -func (c *Code) UnmarshalJSON(b []byte) error { - // From json.Unmarshaler: By convention, to approximate the behavior of - // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as - // a no-op. - if string(b) == "null" { - return nil - } - if c == nil { - return fmt.Errorf("nil receiver passed to UnmarshalJSON") - } - - if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { - if ci >= _maxCode { - return fmt.Errorf("invalid code: %q", ci) - } - - *c = Code(ci) - return nil - } - - if jc, ok := strToCode[string(b)]; ok { - *c = jc - return nil - } - return fmt.Errorf("invalid code: %q", string(b)) -} diff --git a/examples/google.golang.org/grpc/codes/codes_test.go b/examples/google.golang.org/grpc/codes/codes_test.go deleted file mode 100755 index d3e32d2..0000000 --- a/examples/google.golang.org/grpc/codes/codes_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package codes - -import ( - "encoding/json" - "reflect" - "testing" - - cpb "google.golang.org/genproto/googleapis/rpc/code" -) - -func TestUnmarshalJSON(t *testing.T) { - for s, v := range cpb.Code_value { - want := Code(v) - var got Code - if err := got.UnmarshalJSON([]byte(`"` + s + `"`)); err != nil || got != want { - t.Errorf("got.UnmarshalJSON(%q) = %v; want . got=%v; want %v", s, err, got, want) - } - } -} - -func TestJSONUnmarshal(t *testing.T) { - var got []Code - want := []Code{OK, NotFound, Internal, Canceled} - in := `["OK", "NOT_FOUND", "INTERNAL", "CANCELLED"]` - err := json.Unmarshal([]byte(in), &got) - if err != nil || !reflect.DeepEqual(got, want) { - t.Fatalf("json.Unmarshal(%q, &got) = %v; want . got=%v; want %v", in, err, got, want) - } -} - -func TestUnmarshalJSON_NilReceiver(t *testing.T) { - var got *Code - in := OK.String() - if err := got.UnmarshalJSON([]byte(in)); err == nil { - t.Errorf("got.UnmarshalJSON(%q) = nil; want . got=%v", in, got) - } -} - -func TestUnmarshalJSON_UnknownInput(t *testing.T) { - var got Code - for _, in := range [][]byte{[]byte(""), []byte("xxx"), []byte("Code(17)"), nil} { - if err := got.UnmarshalJSON([]byte(in)); err == nil { - t.Errorf("got.UnmarshalJSON(%q) = nil; want . got=%v", in, got) - } - } -} - -func TestUnmarshalJSON_MarshalUnmarshal(t *testing.T) { - for i := 0; i < _maxCode; i++ { - var cUnMarshaled Code - c := Code(i) - - cJSON, err := json.Marshal(c) - if err != nil { - t.Errorf("marshalling %q failed: %v", c, err) - } - - if err := json.Unmarshal(cJSON, &cUnMarshaled); err != nil { - t.Errorf("unmarshalling code failed: %s", err) - } - - if c != cUnMarshaled { - t.Errorf("code is %q after marshalling/unmarshalling, expected %q", cUnMarshaled, c) - } - } -} diff --git a/examples/google.golang.org/grpc/connectivity/connectivity.go b/examples/google.golang.org/grpc/connectivity/connectivity.go deleted file mode 100755 index 568ef5d..0000000 --- a/examples/google.golang.org/grpc/connectivity/connectivity.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package connectivity defines connectivity semantics. -// For details, see https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md. -// All APIs in this package are experimental. -package connectivity - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" -) - -// State indicates the state of connectivity. -// It can be the state of a ClientConn or SubConn. -type State int - -func (s State) String() string { - switch s { - case Idle: - return "IDLE" - case Connecting: - return "CONNECTING" - case Ready: - return "READY" - case TransientFailure: - return "TRANSIENT_FAILURE" - case Shutdown: - return "SHUTDOWN" - default: - grpclog.Errorf("unknown connectivity state: %d", s) - return "Invalid-State" - } -} - -const ( - // Idle indicates the ClientConn is idle. - Idle State = iota - // Connecting indicates the ClienConn is connecting. - Connecting - // Ready indicates the ClientConn is ready for work. - Ready - // TransientFailure indicates the ClientConn has seen a failure but expects to recover. - TransientFailure - // Shutdown indicates the ClientConn has started shutting down. - Shutdown -) - -// Reporter reports the connectivity states. -type Reporter interface { - // CurrentState returns the current state of the reporter. - CurrentState() State - // WaitForStateChange blocks until the reporter's state is different from the given state, - // and returns true. - // It returns false if <-ctx.Done() can proceed (ctx got timeout or got canceled). - WaitForStateChange(context.Context, State) bool -} diff --git a/examples/google.golang.org/grpc/credentials/alts/alts.go b/examples/google.golang.org/grpc/credentials/alts/alts.go deleted file mode 100755 index 9400565..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/alts.go +++ /dev/null @@ -1,329 +0,0 @@ -/* - * - * 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. - * - */ - -// Package alts implements the ALTS credential support by gRPC library, which -// encapsulates all the state needed by a client to authenticate with a server -// using ALTS and make various assertions, e.g., about the client's identity, -// role, or whether it is authorized to make a particular call. -// This package is experimental. -package alts - -import ( - "errors" - "fmt" - "net" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/alts/core" - "google.golang.org/grpc/credentials/alts/core/handshaker" - "google.golang.org/grpc/credentials/alts/core/handshaker/service" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - "google.golang.org/grpc/grpclog" -) - -const ( - // hypervisorHandshakerServiceAddress represents the default ALTS gRPC - // handshaker service address in the hypervisor. - hypervisorHandshakerServiceAddress = "metadata.google.internal:8080" - // defaultTimeout specifies the server handshake timeout. - defaultTimeout = 30.0 * time.Second - // The following constants specify the minimum and maximum acceptable - // protocol versions. - protocolVersionMaxMajor = 2 - protocolVersionMaxMinor = 1 - protocolVersionMinMajor = 2 - protocolVersionMinMinor = 1 -) - -var ( - once sync.Once - maxRPCVersion = &altspb.RpcProtocolVersions_Version{ - Major: protocolVersionMaxMajor, - Minor: protocolVersionMaxMinor, - } - minRPCVersion = &altspb.RpcProtocolVersions_Version{ - Major: protocolVersionMinMajor, - Minor: protocolVersionMinMinor, - } - // ErrUntrustedPlatform is returned from ClientHandshake and - // ServerHandshake is running on a platform where the trustworthiness of - // the handshaker service is not guaranteed. - ErrUntrustedPlatform = errors.New("untrusted platform") -) - -// AuthInfo exposes security information from the ALTS handshake to the -// application. This interface is to be implemented by ALTS. Users should not -// need a brand new implementation of this interface. For situations like -// testing, any new implementation should embed this interface. This allows -// ALTS to add new methods to this interface. -type AuthInfo interface { - // ApplicationProtocol returns application protocol negotiated for the - // ALTS connection. - ApplicationProtocol() string - // RecordProtocol returns the record protocol negotiated for the ALTS - // connection. - RecordProtocol() string - // SecurityLevel returns the security level of the created ALTS secure - // channel. - SecurityLevel() altspb.SecurityLevel - // PeerServiceAccount returns the peer service account. - PeerServiceAccount() string - // LocalServiceAccount returns the local service account. - LocalServiceAccount() string - // PeerRPCVersions returns the RPC version supported by the peer. - PeerRPCVersions() *altspb.RpcProtocolVersions -} - -// ClientOptions contains the client-side options of an ALTS channel. These -// options will be passed to the underlying ALTS handshaker. -type ClientOptions struct { - // TargetServiceAccounts contains a list of expected target service - // accounts. - TargetServiceAccounts []string - // HandshakerServiceAddress represents the ALTS handshaker gRPC service - // address to connect to. - HandshakerServiceAddress string -} - -// DefaultClientOptions creates a new ClientOptions object with the default -// values. -func DefaultClientOptions() *ClientOptions { - return &ClientOptions{ - HandshakerServiceAddress: hypervisorHandshakerServiceAddress, - } -} - -// ServerOptions contains the server-side options of an ALTS channel. These -// options will be passed to the underlying ALTS handshaker. -type ServerOptions struct { - // HandshakerServiceAddress represents the ALTS handshaker gRPC service - // address to connect to. - HandshakerServiceAddress string -} - -// DefaultServerOptions creates a new ServerOptions object with the default -// values. -func DefaultServerOptions() *ServerOptions { - return &ServerOptions{ - HandshakerServiceAddress: hypervisorHandshakerServiceAddress, - } -} - -// altsTC is the credentials required for authenticating a connection using ALTS. -// It implements credentials.TransportCredentials interface. -type altsTC struct { - info *credentials.ProtocolInfo - side core.Side - accounts []string - hsAddress string -} - -// NewClientCreds constructs a client-side ALTS TransportCredentials object. -func NewClientCreds(opts *ClientOptions) credentials.TransportCredentials { - return newALTS(core.ClientSide, opts.TargetServiceAccounts, opts.HandshakerServiceAddress) -} - -// NewServerCreds constructs a server-side ALTS TransportCredentials object. -func NewServerCreds(opts *ServerOptions) credentials.TransportCredentials { - return newALTS(core.ServerSide, nil, opts.HandshakerServiceAddress) -} - -func newALTS(side core.Side, accounts []string, hsAddress string) credentials.TransportCredentials { - once.Do(func() { - vmOnGCP = isRunningOnGCP() - }) - - if hsAddress == "" { - hsAddress = hypervisorHandshakerServiceAddress - } - return &altsTC{ - info: &credentials.ProtocolInfo{ - SecurityProtocol: "alts", - SecurityVersion: "1.0", - }, - side: side, - accounts: accounts, - hsAddress: hsAddress, - } -} - -// ClientHandshake implements the client side handshake protocol. -func (g *altsTC) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ credentials.AuthInfo, err error) { - if !vmOnGCP { - return nil, nil, ErrUntrustedPlatform - } - - // Connecting to ALTS handshaker service. - hsConn, err := service.Dial(g.hsAddress) - if err != nil { - return nil, nil, err - } - // Do not close hsConn since it is shared with other handshakes. - - // Possible context leak: - // The cancel function for the child context we create will only be - // called a non-nil error is returned. - var cancel context.CancelFunc - ctx, cancel = context.WithCancel(ctx) - defer func() { - if err != nil { - cancel() - } - }() - - opts := handshaker.DefaultClientHandshakerOptions() - opts.TargetServiceAccounts = g.accounts - opts.RPCVersions = &altspb.RpcProtocolVersions{ - MaxRpcVersion: maxRPCVersion, - MinRpcVersion: minRPCVersion, - } - chs, err := handshaker.NewClientHandshaker(ctx, hsConn, rawConn, opts) - defer func() { - if err != nil { - chs.Close() - } - }() - if err != nil { - return nil, nil, err - } - secConn, authInfo, err := chs.ClientHandshake(ctx) - if err != nil { - return nil, nil, err - } - altsAuthInfo, ok := authInfo.(AuthInfo) - if !ok { - return nil, nil, errors.New("client-side auth info is not of type alts.AuthInfo") - } - match, _ := checkRPCVersions(opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) - if !match { - return nil, nil, fmt.Errorf("server-side RPC versions are not compatible with this client, local versions: %v, peer versions: %v", opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) - } - return secConn, authInfo, nil -} - -// ServerHandshake implements the server side ALTS handshaker. -func (g *altsTC) ServerHandshake(rawConn net.Conn) (_ net.Conn, _ credentials.AuthInfo, err error) { - if !vmOnGCP { - return nil, nil, ErrUntrustedPlatform - } - // Connecting to ALTS handshaker service. - hsConn, err := service.Dial(g.hsAddress) - if err != nil { - return nil, nil, err - } - // Do not close hsConn since it's shared with other handshakes. - - ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) - defer cancel() - opts := handshaker.DefaultServerHandshakerOptions() - opts.RPCVersions = &altspb.RpcProtocolVersions{ - MaxRpcVersion: maxRPCVersion, - MinRpcVersion: minRPCVersion, - } - shs, err := handshaker.NewServerHandshaker(ctx, hsConn, rawConn, opts) - defer func() { - if err != nil { - shs.Close() - } - }() - if err != nil { - return nil, nil, err - } - secConn, authInfo, err := shs.ServerHandshake(ctx) - if err != nil { - return nil, nil, err - } - altsAuthInfo, ok := authInfo.(AuthInfo) - if !ok { - return nil, nil, errors.New("server-side auth info is not of type alts.AuthInfo") - } - match, _ := checkRPCVersions(opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) - if !match { - return nil, nil, fmt.Errorf("client-side RPC versions is not compatible with this server, local versions: %v, peer versions: %v", opts.RPCVersions, altsAuthInfo.PeerRPCVersions()) - } - return secConn, authInfo, nil -} - -func (g *altsTC) Info() credentials.ProtocolInfo { - return *g.info -} - -func (g *altsTC) Clone() credentials.TransportCredentials { - info := *g.info - var accounts []string - if g.accounts != nil { - accounts = make([]string, len(g.accounts)) - copy(accounts, g.accounts) - } - return &altsTC{ - info: &info, - side: g.side, - hsAddress: g.hsAddress, - accounts: accounts, - } -} - -func (g *altsTC) OverrideServerName(serverNameOverride string) error { - g.info.ServerName = serverNameOverride - return nil -} - -// compareRPCVersion returns 0 if v1 == v2, 1 if v1 > v2 and -1 if v1 < v2. -func compareRPCVersions(v1, v2 *altspb.RpcProtocolVersions_Version) int { - switch { - case v1.GetMajor() > v2.GetMajor(), - v1.GetMajor() == v2.GetMajor() && v1.GetMinor() > v2.GetMinor(): - return 1 - case v1.GetMajor() < v2.GetMajor(), - v1.GetMajor() == v2.GetMajor() && v1.GetMinor() < v2.GetMinor(): - return -1 - } - return 0 -} - -// checkRPCVersions performs a version check between local and peer rpc protocol -// versions. This function returns true if the check passes which means both -// parties agreed on a common rpc protocol to use, and false otherwise. The -// function also returns the highest common RPC protocol version both parties -// agreed on. -func checkRPCVersions(local, peer *altspb.RpcProtocolVersions) (bool, *altspb.RpcProtocolVersions_Version) { - if local == nil || peer == nil { - grpclog.Error("invalid checkRPCVersions argument, either local or peer is nil.") - return false, nil - } - - // maxCommonVersion is MIN(local.max, peer.max). - maxCommonVersion := local.GetMaxRpcVersion() - if compareRPCVersions(local.GetMaxRpcVersion(), peer.GetMaxRpcVersion()) > 0 { - maxCommonVersion = peer.GetMaxRpcVersion() - } - - // minCommonVersion is MAX(local.min, peer.min). - minCommonVersion := peer.GetMinRpcVersion() - if compareRPCVersions(local.GetMinRpcVersion(), peer.GetMinRpcVersion()) > 0 { - minCommonVersion = local.GetMinRpcVersion() - } - - if compareRPCVersions(maxCommonVersion, minCommonVersion) < 0 { - return false, nil - } - return true, maxCommonVersion -} diff --git a/examples/google.golang.org/grpc/credentials/alts/alts_test.go b/examples/google.golang.org/grpc/credentials/alts/alts_test.go deleted file mode 100755 index 6b041d9..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/alts_test.go +++ /dev/null @@ -1,290 +0,0 @@ -/* - * - * 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. - * - */ - -package alts - -import ( - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" -) - -func TestInfoServerName(t *testing.T) { - // This is not testing any handshaker functionality, so it's fine to only - // use NewServerCreds and not NewClientCreds. - alts := NewServerCreds(DefaultServerOptions()) - if got, want := alts.Info().ServerName, ""; got != want { - t.Fatalf("%v.Info().ServerName = %v, want %v", alts, got, want) - } -} - -func TestOverrideServerName(t *testing.T) { - wantServerName := "server.name" - // This is not testing any handshaker functionality, so it's fine to only - // use NewServerCreds and not NewClientCreds. - c := NewServerCreds(DefaultServerOptions()) - c.OverrideServerName(wantServerName) - if got, want := c.Info().ServerName, wantServerName; got != want { - t.Fatalf("c.Info().ServerName = %v, want %v", got, want) - } -} - -func TestCloneClient(t *testing.T) { - wantServerName := "server.name" - opt := DefaultClientOptions() - opt.TargetServiceAccounts = []string{"not", "empty"} - c := NewClientCreds(opt) - c.OverrideServerName(wantServerName) - cc := c.Clone() - if got, want := cc.Info().ServerName, wantServerName; got != want { - t.Fatalf("cc.Info().ServerName = %v, want %v", got, want) - } - cc.OverrideServerName("") - if got, want := c.Info().ServerName, wantServerName; got != want { - t.Fatalf("Change in clone should not affect the original, c.Info().ServerName = %v, want %v", got, want) - } - if got, want := cc.Info().ServerName, ""; got != want { - t.Fatalf("cc.Info().ServerName = %v, want %v", got, want) - } - - ct := c.(*altsTC) - cct := cc.(*altsTC) - - if ct.side != cct.side { - t.Errorf("cc.side = %q, want %q", cct.side, ct.side) - } - if ct.hsAddress != cct.hsAddress { - t.Errorf("cc.hsAddress = %q, want %q", cct.hsAddress, ct.hsAddress) - } - if !reflect.DeepEqual(ct.accounts, cct.accounts) { - t.Errorf("cc.accounts = %q, want %q", cct.accounts, ct.accounts) - } -} - -func TestCloneServer(t *testing.T) { - wantServerName := "server.name" - c := NewServerCreds(DefaultServerOptions()) - c.OverrideServerName(wantServerName) - cc := c.Clone() - if got, want := cc.Info().ServerName, wantServerName; got != want { - t.Fatalf("cc.Info().ServerName = %v, want %v", got, want) - } - cc.OverrideServerName("") - if got, want := c.Info().ServerName, wantServerName; got != want { - t.Fatalf("Change in clone should not affect the original, c.Info().ServerName = %v, want %v", got, want) - } - if got, want := cc.Info().ServerName, ""; got != want { - t.Fatalf("cc.Info().ServerName = %v, want %v", got, want) - } - - ct := c.(*altsTC) - cct := cc.(*altsTC) - - if ct.side != cct.side { - t.Errorf("cc.side = %q, want %q", cct.side, ct.side) - } - if ct.hsAddress != cct.hsAddress { - t.Errorf("cc.hsAddress = %q, want %q", cct.hsAddress, ct.hsAddress) - } - if !reflect.DeepEqual(ct.accounts, cct.accounts) { - t.Errorf("cc.accounts = %q, want %q", cct.accounts, ct.accounts) - } -} - -func TestInfo(t *testing.T) { - // This is not testing any handshaker functionality, so it's fine to only - // use NewServerCreds and not NewClientCreds. - c := NewServerCreds(DefaultServerOptions()) - info := c.Info() - if got, want := info.ProtocolVersion, ""; got != want { - t.Errorf("info.ProtocolVersion=%v, want %v", got, want) - } - if got, want := info.SecurityProtocol, "alts"; got != want { - t.Errorf("info.SecurityProtocol=%v, want %v", got, want) - } - if got, want := info.SecurityVersion, "1.0"; got != want { - t.Errorf("info.SecurityVersion=%v, want %v", got, want) - } - if got, want := info.ServerName, ""; got != want { - t.Errorf("info.ServerName=%v, want %v", got, want) - } -} - -func TestCompareRPCVersions(t *testing.T) { - for _, tc := range []struct { - v1 *altspb.RpcProtocolVersions_Version - v2 *altspb.RpcProtocolVersions_Version - output int - }{ - { - version(3, 2), - version(2, 1), - 1, - }, - { - version(3, 2), - version(3, 1), - 1, - }, - { - version(2, 1), - version(3, 2), - -1, - }, - { - version(3, 1), - version(3, 2), - -1, - }, - { - version(3, 2), - version(3, 2), - 0, - }, - } { - if got, want := compareRPCVersions(tc.v1, tc.v2), tc.output; got != want { - t.Errorf("compareRPCVersions(%v, %v)=%v, want %v", tc.v1, tc.v2, got, want) - } - } -} - -func TestCheckRPCVersions(t *testing.T) { - for _, tc := range []struct { - desc string - local *altspb.RpcProtocolVersions - peer *altspb.RpcProtocolVersions - output bool - maxCommonVersion *altspb.RpcProtocolVersions_Version - }{ - { - "local.max > peer.max and local.min > peer.min", - versions(2, 1, 3, 2), - versions(1, 2, 2, 1), - true, - version(2, 1), - }, - { - "local.max > peer.max and local.min < peer.min", - versions(1, 2, 3, 2), - versions(2, 1, 2, 1), - true, - version(2, 1), - }, - { - "local.max > peer.max and local.min = peer.min", - versions(2, 1, 3, 2), - versions(2, 1, 2, 1), - true, - version(2, 1), - }, - { - "local.max < peer.max and local.min > peer.min", - versions(2, 1, 2, 1), - versions(1, 2, 3, 2), - true, - version(2, 1), - }, - { - "local.max = peer.max and local.min > peer.min", - versions(2, 1, 2, 1), - versions(1, 2, 2, 1), - true, - version(2, 1), - }, - { - "local.max < peer.max and local.min < peer.min", - versions(1, 2, 2, 1), - versions(2, 1, 3, 2), - true, - version(2, 1), - }, - { - "local.max < peer.max and local.min = peer.min", - versions(1, 2, 2, 1), - versions(1, 2, 3, 2), - true, - version(2, 1), - }, - { - "local.max = peer.max and local.min < peer.min", - versions(1, 2, 2, 1), - versions(2, 1, 2, 1), - true, - version(2, 1), - }, - { - "all equal", - versions(2, 1, 2, 1), - versions(2, 1, 2, 1), - true, - version(2, 1), - }, - { - "max is smaller than min", - versions(2, 1, 1, 2), - versions(2, 1, 1, 2), - false, - nil, - }, - { - "no overlap, local > peer", - versions(4, 3, 6, 5), - versions(1, 0, 2, 1), - false, - nil, - }, - { - "no overlap, local < peer", - versions(1, 0, 2, 1), - versions(4, 3, 6, 5), - false, - nil, - }, - { - "no overlap, max < min", - versions(6, 5, 4, 3), - versions(2, 1, 1, 0), - false, - nil, - }, - } { - output, maxCommonVersion := checkRPCVersions(tc.local, tc.peer) - if got, want := output, tc.output; got != want { - t.Errorf("%v: checkRPCVersions(%v, %v)=(%v, _), want (%v, _)", tc.desc, tc.local, tc.peer, got, want) - } - if got, want := maxCommonVersion, tc.maxCommonVersion; !proto.Equal(got, want) { - t.Errorf("%v: checkRPCVersions(%v, %v)=(_, %v), want (_, %v)", tc.desc, tc.local, tc.peer, got, want) - } - } -} - -func version(major, minor uint32) *altspb.RpcProtocolVersions_Version { - return &altspb.RpcProtocolVersions_Version{ - Major: major, - Minor: minor, - } -} - -func versions(minMajor, minMinor, maxMajor, maxMinor uint32) *altspb.RpcProtocolVersions { - return &altspb.RpcProtocolVersions{ - MinRpcVersion: version(minMajor, minMinor), - MaxRpcVersion: version(maxMajor, maxMinor), - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo.go b/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo.go deleted file mode 100755 index 2fe54b7..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * 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. - * - */ - -// Package authinfo provide authentication information returned by handshakers. -package authinfo - -import ( - "google.golang.org/grpc/credentials" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" -) - -var _ credentials.AuthInfo = (*altsAuthInfo)(nil) - -// altsAuthInfo exposes security information from the ALTS handshake to the -// application. altsAuthInfo is immutable and implements credentials.AuthInfo. -type altsAuthInfo struct { - p *altspb.AltsContext -} - -// New returns a new altsAuthInfo object given handshaker results. -func New(result *altspb.HandshakerResult) credentials.AuthInfo { - return newAuthInfo(result) -} - -func newAuthInfo(result *altspb.HandshakerResult) *altsAuthInfo { - return &altsAuthInfo{ - p: &altspb.AltsContext{ - ApplicationProtocol: result.GetApplicationProtocol(), - RecordProtocol: result.GetRecordProtocol(), - // TODO: assign security level from result. - SecurityLevel: altspb.SecurityLevel_INTEGRITY_AND_PRIVACY, - PeerServiceAccount: result.GetPeerIdentity().GetServiceAccount(), - LocalServiceAccount: result.GetLocalIdentity().GetServiceAccount(), - PeerRpcVersions: result.GetPeerRpcVersions(), - }, - } -} - -// AuthType identifies the context as providing ALTS authentication information. -func (s *altsAuthInfo) AuthType() string { - return "alts" -} - -// ApplicationProtocol returns the context's application protocol. -func (s *altsAuthInfo) ApplicationProtocol() string { - return s.p.GetApplicationProtocol() -} - -// RecordProtocol returns the context's record protocol. -func (s *altsAuthInfo) RecordProtocol() string { - return s.p.GetRecordProtocol() -} - -// SecurityLevel returns the context's security level. -func (s *altsAuthInfo) SecurityLevel() altspb.SecurityLevel { - return s.p.GetSecurityLevel() -} - -// PeerServiceAccount returns the context's peer service account. -func (s *altsAuthInfo) PeerServiceAccount() string { - return s.p.GetPeerServiceAccount() -} - -// LocalServiceAccount returns the context's local service account. -func (s *altsAuthInfo) LocalServiceAccount() string { - return s.p.GetLocalServiceAccount() -} - -// PeerRPCVersions returns the context's peer RPC versions. -func (s *altsAuthInfo) PeerRPCVersions() *altspb.RpcProtocolVersions { - return s.p.GetPeerRpcVersions() -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo_test.go b/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo_test.go deleted file mode 100755 index 635d804..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/authinfo/authinfo_test.go +++ /dev/null @@ -1,134 +0,0 @@ -/* - * - * 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. - * - */ - -package authinfo - -import ( - "reflect" - "testing" - - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" -) - -const ( - testAppProtocol = "my_app" - testRecordProtocol = "very_secure_protocol" - testPeerAccount = "peer_service_account" - testLocalAccount = "local_service_account" - testPeerHostname = "peer_hostname" - testLocalHostname = "local_hostname" -) - -func TestALTSAuthInfo(t *testing.T) { - for _, tc := range []struct { - result *altspb.HandshakerResult - outAppProtocol string - outRecordProtocol string - outSecurityLevel altspb.SecurityLevel - outPeerAccount string - outLocalAccount string - outPeerRPCVersions *altspb.RpcProtocolVersions - }{ - { - &altspb.HandshakerResult{ - ApplicationProtocol: testAppProtocol, - RecordProtocol: testRecordProtocol, - PeerIdentity: &altspb.Identity{ - IdentityOneof: &altspb.Identity_ServiceAccount{ - ServiceAccount: testPeerAccount, - }, - }, - LocalIdentity: &altspb.Identity{ - IdentityOneof: &altspb.Identity_ServiceAccount{ - ServiceAccount: testLocalAccount, - }, - }, - }, - testAppProtocol, - testRecordProtocol, - altspb.SecurityLevel_INTEGRITY_AND_PRIVACY, - testPeerAccount, - testLocalAccount, - nil, - }, - { - &altspb.HandshakerResult{ - ApplicationProtocol: testAppProtocol, - RecordProtocol: testRecordProtocol, - PeerIdentity: &altspb.Identity{ - IdentityOneof: &altspb.Identity_Hostname{ - Hostname: testPeerHostname, - }, - }, - LocalIdentity: &altspb.Identity{ - IdentityOneof: &altspb.Identity_Hostname{ - Hostname: testLocalHostname, - }, - }, - PeerRpcVersions: &altspb.RpcProtocolVersions{ - MaxRpcVersion: &altspb.RpcProtocolVersions_Version{ - Major: 20, - Minor: 21, - }, - MinRpcVersion: &altspb.RpcProtocolVersions_Version{ - Major: 10, - Minor: 11, - }, - }, - }, - testAppProtocol, - testRecordProtocol, - altspb.SecurityLevel_INTEGRITY_AND_PRIVACY, - "", - "", - &altspb.RpcProtocolVersions{ - MaxRpcVersion: &altspb.RpcProtocolVersions_Version{ - Major: 20, - Minor: 21, - }, - MinRpcVersion: &altspb.RpcProtocolVersions_Version{ - Major: 10, - Minor: 11, - }, - }, - }, - } { - authInfo := newAuthInfo(tc.result) - if got, want := authInfo.AuthType(), "alts"; got != want { - t.Errorf("authInfo.AuthType()=%v, want %v", got, want) - } - if got, want := authInfo.ApplicationProtocol(), tc.outAppProtocol; got != want { - t.Errorf("authInfo.ApplicationProtocol()=%v, want %v", got, want) - } - if got, want := authInfo.RecordProtocol(), tc.outRecordProtocol; got != want { - t.Errorf("authInfo.RecordProtocol()=%v, want %v", got, want) - } - if got, want := authInfo.SecurityLevel(), tc.outSecurityLevel; got != want { - t.Errorf("authInfo.SecurityLevel()=%v, want %v", got, want) - } - if got, want := authInfo.PeerServiceAccount(), tc.outPeerAccount; got != want { - t.Errorf("authInfo.PeerServiceAccount()=%v, want %v", got, want) - } - if got, want := authInfo.LocalServiceAccount(), tc.outLocalAccount; got != want { - t.Errorf("authInfo.LocalServiceAccount()=%v, want %v", got, want) - } - if got, want := authInfo.PeerRPCVersions(), tc.outPeerRPCVersions; !reflect.DeepEqual(got, want) { - t.Errorf("authinfo.PeerRpcVersions()=%v, want %v", got, want) - } - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/common.go b/examples/google.golang.org/grpc/credentials/alts/core/common.go deleted file mode 100755 index b7baf77..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/common.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * 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. - * - */ - -//go:generate ./regenerate.sh - -// Package core contains common core functionality for ALTS. -// Disclaimer: users should NEVER reference this package directly. -package core - -import ( - "net" - - "golang.org/x/net/context" - "google.golang.org/grpc/credentials" -) - -const ( - // ClientSide identifies the client in this communication. - ClientSide Side = iota - // ServerSide identifies the server in this communication. - ServerSide -) - -// PeerNotRespondingError is returned when a peer server is not responding -// after a channel has been established. It is treated as a temporary connection -// error and re-connection to the server should be attempted. -var PeerNotRespondingError = &peerNotRespondingError{} - -// Side identifies the party's role: client or server. -type Side int - -type peerNotRespondingError struct{} - -// Return an error message for the purpose of logging. -func (e *peerNotRespondingError) Error() string { - return "peer server is not responding and re-connection should be attempted." -} - -// Temporary indicates if this connection error is temporary or fatal. -func (e *peerNotRespondingError) Temporary() bool { - return true -} - -// Handshaker defines a ALTS handshaker interface. -type Handshaker interface { - // ClientHandshake starts and completes a client-side handshaking and - // returns a secure connection and corresponding auth information. - ClientHandshake(ctx context.Context) (net.Conn, credentials.AuthInfo, error) - // ServerHandshake starts and completes a server-side handshaking and - // returns a secure connection and corresponding auth information. - ServerHandshake(ctx context.Context) (net.Conn, credentials.AuthInfo, error) - // Close terminates the Handshaker. It should be called when the caller - // obtains the secure connection. - Close() -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey.go deleted file mode 100755 index 43726e8..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey.go +++ /dev/null @@ -1,131 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/sha256" - "encoding/binary" - "fmt" - "strconv" -) - -// rekeyAEAD holds the necessary information for an AEAD based on -// AES-GCM that performs nonce-based key derivation and XORs the -// nonce with a random mask. -type rekeyAEAD struct { - kdfKey []byte - kdfCounter []byte - nonceMask []byte - nonceBuf []byte - gcmAEAD cipher.AEAD -} - -// KeySizeError signals that the given key does not have the correct size. -type KeySizeError int - -func (k KeySizeError) Error() string { - return "alts/conn: invalid key size " + strconv.Itoa(int(k)) -} - -// newRekeyAEAD creates a new instance of aes128gcm with rekeying. -// The key argument should be 44 bytes, the first 32 bytes are used as a key -// for HKDF-expand and the remainining 12 bytes are used as a random mask for -// the counter. -func newRekeyAEAD(key []byte) (*rekeyAEAD, error) { - k := len(key) - if k != kdfKeyLen+nonceLen { - return nil, KeySizeError(k) - } - return &rekeyAEAD{ - kdfKey: key[:kdfKeyLen], - kdfCounter: make([]byte, kdfCounterLen), - nonceMask: key[kdfKeyLen:], - nonceBuf: make([]byte, nonceLen), - gcmAEAD: nil, - }, nil -} - -// Seal rekeys if nonce[2:8] is different than in the last call, masks the nonce, -// and calls Seal for aes128gcm. -func (s *rekeyAEAD) Seal(dst, nonce, plaintext, additionalData []byte) []byte { - if err := s.rekeyIfRequired(nonce); err != nil { - panic(fmt.Sprintf("Rekeying failed with: %s", err.Error())) - } - maskNonce(s.nonceBuf, nonce, s.nonceMask) - return s.gcmAEAD.Seal(dst, s.nonceBuf, plaintext, additionalData) -} - -// Open rekeys if nonce[2:8] is different than in the last call, masks the nonce, -// and calls Open for aes128gcm. -func (s *rekeyAEAD) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { - if err := s.rekeyIfRequired(nonce); err != nil { - return nil, err - } - maskNonce(s.nonceBuf, nonce, s.nonceMask) - return s.gcmAEAD.Open(dst, s.nonceBuf, ciphertext, additionalData) -} - -// rekeyIfRequired creates a new aes128gcm AEAD if the existing AEAD is nil -// or cannot be used with given nonce. -func (s *rekeyAEAD) rekeyIfRequired(nonce []byte) error { - newKdfCounter := nonce[kdfCounterOffset : kdfCounterOffset+kdfCounterLen] - if s.gcmAEAD != nil && bytes.Equal(newKdfCounter, s.kdfCounter) { - return nil - } - copy(s.kdfCounter, newKdfCounter) - a, err := aes.NewCipher(hkdfExpand(s.kdfKey, s.kdfCounter)) - if err != nil { - return err - } - s.gcmAEAD, err = cipher.NewGCM(a) - return err -} - -// maskNonce XORs the given nonce with the mask and stores the result in dst. -func maskNonce(dst, nonce, mask []byte) { - nonce1 := binary.LittleEndian.Uint64(nonce[:sizeUint64]) - nonce2 := binary.LittleEndian.Uint32(nonce[sizeUint64:]) - mask1 := binary.LittleEndian.Uint64(mask[:sizeUint64]) - mask2 := binary.LittleEndian.Uint32(mask[sizeUint64:]) - binary.LittleEndian.PutUint64(dst[:sizeUint64], nonce1^mask1) - binary.LittleEndian.PutUint32(dst[sizeUint64:], nonce2^mask2) -} - -// NonceSize returns the required nonce size. -func (s *rekeyAEAD) NonceSize() int { - return s.gcmAEAD.NonceSize() -} - -// Overhead returns the ciphertext overhead. -func (s *rekeyAEAD) Overhead() int { - return s.gcmAEAD.Overhead() -} - -// hkdfExpand computes the first 16 bytes of the HKDF-expand function -// defined in RFC5869. -func hkdfExpand(key, info []byte) []byte { - mac := hmac.New(sha256.New, key) - mac.Write(info) - mac.Write([]byte{0x01}[:]) - return mac.Sum(nil)[:aeadKeyLen] -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey_test.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey_test.go deleted file mode 100755 index d639b38..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aeadrekey_test.go +++ /dev/null @@ -1,263 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "bytes" - "encoding/hex" - "testing" -) - -// cryptoTestVector is struct for a rekey test vector -type rekeyAEADTestVector struct { - desc string - key, nonce, plaintext, aad, ciphertext []byte -} - -// Test encrypt and decrypt using (adapted) test vectors for AES-GCM. -func TestAES128GCMRekeyEncrypt(t *testing.T) { - for _, test := range []rekeyAEADTestVector{ - // NIST vectors from: - // http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf - // - // IEEE vectors from: - // http://www.ieee802.org/1/files/public/docs2011/bn-randall-test-vectors-0511-v1.pdf - // - // Key expanded by setting - // expandedKey = (key || - // key ^ {0x01,..,0x01} || - // key ^ {0x02,..,0x02})[0:44]. - { - desc: "Derived from NIST test vector 1", - key: dehex("0000000000000000000000000000000001010101010101010101010101010101020202020202020202020202"), - nonce: dehex("000000000000000000000000"), - aad: dehex(""), - plaintext: dehex(""), - ciphertext: dehex("85e873e002f6ebdc4060954eb8675508"), - }, - { - desc: "Derived from NIST test vector 2", - key: dehex("0000000000000000000000000000000001010101010101010101010101010101020202020202020202020202"), - nonce: dehex("000000000000000000000000"), - aad: dehex(""), - plaintext: dehex("00000000000000000000000000000000"), - ciphertext: dehex("51e9a8cb23ca2512c8256afff8e72d681aca19a1148ac115e83df4888cc00d11"), - }, - { - desc: "Derived from NIST test vector 3", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("cafebabefacedbaddecaf888"), - aad: dehex(""), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255"), - ciphertext: dehex("1018ed5a1402a86516d6576d70b2ffccca261b94df88b58f53b64dfba435d18b2f6e3b7869f9353d4ac8cf09afb1663daa7b4017e6fc2c177c0c087c0df1162129952213cee1bc6e9c8495dd705e1f3d"), - }, - { - desc: "Derived from NIST test vector 4", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("cafebabefacedbaddecaf888"), - aad: dehex("feedfacedeadbeeffeedfacedeadbeefabaddad2"), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"), - ciphertext: dehex("1018ed5a1402a86516d6576d70b2ffccca261b94df88b58f53b64dfba435d18b2f6e3b7869f9353d4ac8cf09afb1663daa7b4017e6fc2c177c0c087c4764565d077e9124001ddb27fc0848c5"), - }, - { - desc: "Derived from adapted NIST test vector 4 for KDF counter boundary (flip nonce bit 15)", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("ca7ebabefacedbaddecaf888"), - aad: dehex("feedfacedeadbeeffeedfacedeadbeefabaddad2"), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"), - ciphertext: dehex("e650d3c0fb879327f2d03287fa93cd07342b136215adbca00c3bd5099ec41832b1d18e0423ed26bb12c6cd09debb29230a94c0cee15903656f85edb6fc509b1b28216382172ecbcc31e1e9b1"), - }, - { - desc: "Derived from adapted NIST test vector 4 for KDF counter boundary (flip nonce bit 16)", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("cafebbbefacedbaddecaf888"), - aad: dehex("feedfacedeadbeeffeedfacedeadbeefabaddad2"), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"), - ciphertext: dehex("c0121e6c954d0767f96630c33450999791b2da2ad05c4190169ccad9ac86ff1c721e3d82f2ad22ab463bab4a0754b7dd68ca4de7ea2531b625eda01f89312b2ab957d5c7f8568dd95fcdcd1f"), - }, - { - desc: "Derived from adapted NIST test vector 4 for KDF counter boundary (flip nonce bit 63)", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("cafebabefacedb2ddecaf888"), - aad: dehex("feedfacedeadbeeffeedfacedeadbeefabaddad2"), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"), - ciphertext: dehex("8af37ea5684a4d81d4fd817261fd9743099e7e6a025eaacf8e54b124fb5743149e05cb89f4a49467fe2e5e5965f29a19f99416b0016b54585d12553783ba59e9f782e82e097c336bf7989f08"), - }, - { - desc: "Derived from adapted NIST test vector 4 for KDF counter boundary (flip nonce bit 64)", - key: dehex("feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f688d96"), - nonce: dehex("cafebabefacedbaddfcaf888"), - aad: dehex("feedfacedeadbeeffeedfacedeadbeefabaddad2"), - plaintext: dehex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"), - ciphertext: dehex("fbd528448d0346bfa878634864d407a35a039de9db2f1feb8e965b3ae9356ce6289441d77f8f0df294891f37ea438b223e3bf2bdc53d4c5a74fb680bb312a8dec6f7252cbcd7f5799750ad78"), - }, - { - desc: "Derived from IEEE 2.1.1 54-byte auth", - key: dehex("ad7a2bd03eac835a6f620fdcb506b345ac7b2ad13fad825b6e630eddb407b244af7829d23cae81586d600dde"), - nonce: dehex("12153524c0895e81b2c28465"), - aad: dehex("d609b1f056637a0d46df998d88e5222ab2c2846512153524c0895e8108000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340001"), - plaintext: dehex(""), - ciphertext: dehex("3ea0b584f3c85e93f9320ea591699efb"), - }, - { - desc: "Derived from IEEE 2.1.2 54-byte auth", - key: dehex("e3c08a8f06c6e3ad95a70557b23f75483ce33021a9c72b7025666204c69c0b72e1c2888d04c4e1af97a50755"), - nonce: dehex("12153524c0895e81b2c28465"), - aad: dehex("d609b1f056637a0d46df998d88e5222ab2c2846512153524c0895e8108000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340001"), - plaintext: dehex(""), - ciphertext: dehex("294e028bf1fe6f14c4e8f7305c933eb5"), - }, - { - desc: "Derived from IEEE 2.2.1 60-byte crypt", - key: dehex("ad7a2bd03eac835a6f620fdcb506b345ac7b2ad13fad825b6e630eddb407b244af7829d23cae81586d600dde"), - nonce: dehex("12153524c0895e81b2c28465"), - aad: dehex("d609b1f056637a0d46df998d88e52e00b2c2846512153524c0895e81"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a0002"), - ciphertext: dehex("db3d25719c6b0a3ca6145c159d5c6ed9aff9c6e0b79f17019ea923b8665ddf52137ad611f0d1bf417a7ca85e45afe106ff9c7569d335d086ae6c03f00987ccd6"), - }, - { - desc: "Derived from IEEE 2.2.2 60-byte crypt", - key: dehex("e3c08a8f06c6e3ad95a70557b23f75483ce33021a9c72b7025666204c69c0b72e1c2888d04c4e1af97a50755"), - nonce: dehex("12153524c0895e81b2c28465"), - aad: dehex("d609b1f056637a0d46df998d88e52e00b2c2846512153524c0895e81"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a0002"), - ciphertext: dehex("1641f28ec13afcc8f7903389787201051644914933e9202bb9d06aa020c2a67ef51dfe7bc00a856c55b8f8133e77f659132502bad63f5713d57d0c11e0f871ed"), - }, - { - desc: "Derived from IEEE 2.3.1 60-byte auth", - key: dehex("071b113b0ca743fecccf3d051f737382061a103a0da642ffcdce3c041e727283051913390ea541fccecd3f07"), - nonce: dehex("f0761e8dcd3d000176d457ed"), - aad: dehex("e20106d7cd0df0761e8dcd3d88e5400076d457ed08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a0003"), - plaintext: dehex(""), - ciphertext: dehex("58837a10562b0f1f8edbe58ca55811d3"), - }, - { - desc: "Derived from IEEE 2.3.2 60-byte auth", - key: dehex("691d3ee909d7f54167fd1ca0b5d769081f2bde1aee655fdbab80bd5295ae6be76b1f3ceb0bd5f74365ff1ea2"), - nonce: dehex("f0761e8dcd3d000176d457ed"), - aad: dehex("e20106d7cd0df0761e8dcd3d88e5400076d457ed08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a0003"), - plaintext: dehex(""), - ciphertext: dehex("c2722ff6ca29a257718a529d1f0c6a3b"), - }, - { - desc: "Derived from IEEE 2.4.1 54-byte crypt", - key: dehex("071b113b0ca743fecccf3d051f737382061a103a0da642ffcdce3c041e727283051913390ea541fccecd3f07"), - nonce: dehex("f0761e8dcd3d000176d457ed"), - aad: dehex("e20106d7cd0df0761e8dcd3d88e54c2a76d457ed"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340004"), - ciphertext: dehex("fd96b715b93a13346af51e8acdf792cdc7b2686f8574c70e6b0cbf16291ded427ad73fec48cd298e0528a1f4c644a949fc31dc9279706ddba33f"), - }, - { - desc: "Derived from IEEE 2.4.2 54-byte crypt", - key: dehex("691d3ee909d7f54167fd1ca0b5d769081f2bde1aee655fdbab80bd5295ae6be76b1f3ceb0bd5f74365ff1ea2"), - nonce: dehex("f0761e8dcd3d000176d457ed"), - aad: dehex("e20106d7cd0df0761e8dcd3d88e54c2a76d457ed"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340004"), - ciphertext: dehex("b68f6300c2e9ae833bdc070e24021a3477118e78ccf84e11a485d861476c300f175353d5cdf92008a4f878e6cc3577768085c50a0e98fda6cbb8"), - }, - { - desc: "Derived from IEEE 2.5.1 65-byte auth", - key: dehex("013fe00b5f11be7f866d0cbbc55a7a90003ee10a5e10bf7e876c0dbac45b7b91033de2095d13bc7d846f0eb9"), - nonce: dehex("7cfde9f9e33724c68932d612"), - aad: dehex("84c5d513d2aaf6e5bbd2727788e523008932d6127cfde9f9e33724c608000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0005"), - plaintext: dehex(""), - ciphertext: dehex("cca20eecda6283f09bb3543dd99edb9b"), - }, - { - desc: "Derived from IEEE 2.5.2 65-byte auth", - key: dehex("83c093b58de7ffe1c0da926ac43fb3609ac1c80fee1b624497ef942e2f79a82381c291b78fe5fde3c2d89068"), - nonce: dehex("7cfde9f9e33724c68932d612"), - aad: dehex("84c5d513d2aaf6e5bbd2727788e523008932d6127cfde9f9e33724c608000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0005"), - plaintext: dehex(""), - ciphertext: dehex("b232cc1da5117bf15003734fa599d271"), - }, - { - desc: "Derived from IEEE 2.6.1 61-byte crypt", - key: dehex("013fe00b5f11be7f866d0cbbc55a7a90003ee10a5e10bf7e876c0dbac45b7b91033de2095d13bc7d846f0eb9"), - nonce: dehex("7cfde9f9e33724c68932d612"), - aad: dehex("84c5d513d2aaf6e5bbd2727788e52f008932d6127cfde9f9e33724c6"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b0006"), - ciphertext: dehex("ff1910d35ad7e5657890c7c560146fd038707f204b66edbc3d161f8ace244b985921023c436e3a1c3532ecd5d09a056d70be583f0d10829d9387d07d33d872e490"), - }, - { - desc: "Derived from IEEE 2.6.2 61-byte crypt", - key: dehex("83c093b58de7ffe1c0da926ac43fb3609ac1c80fee1b624497ef942e2f79a82381c291b78fe5fde3c2d89068"), - nonce: dehex("7cfde9f9e33724c68932d612"), - aad: dehex("84c5d513d2aaf6e5bbd2727788e52f008932d6127cfde9f9e33724c6"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b0006"), - ciphertext: dehex("0db4cf956b5f97eca4eab82a6955307f9ae02a32dd7d93f83d66ad04e1cfdc5182ad12abdea5bbb619a1bd5fb9a573590fba908e9c7a46c1f7ba0905d1b55ffda4"), - }, - { - desc: "Derived from IEEE 2.7.1 79-byte crypt", - key: dehex("88ee087fd95da9fbf6725aa9d757b0cd89ef097ed85ca8faf7735ba8d656b1cc8aec0a7ddb5fabf9f47058ab"), - nonce: dehex("7ae8e2ca4ec500012e58495c"), - aad: dehex("68f2e77696ce7ae8e2ca4ec588e541002e58495c08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d0007"), - plaintext: dehex(""), - ciphertext: dehex("813f0e630f96fb2d030f58d83f5cdfd0"), - }, - { - desc: "Derived from IEEE 2.7.2 79-byte crypt", - key: dehex("4c973dbc7364621674f8b5b89e5c15511fced9216490fb1c1a2caa0ffe0407e54e953fbe7166601476fab7ba"), - nonce: dehex("7ae8e2ca4ec500012e58495c"), - aad: dehex("68f2e77696ce7ae8e2ca4ec588e541002e58495c08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d0007"), - plaintext: dehex(""), - ciphertext: dehex("77e5a44c21eb07188aacbd74d1980e97"), - }, - { - desc: "Derived from IEEE 2.8.1 61-byte crypt", - key: dehex("88ee087fd95da9fbf6725aa9d757b0cd89ef097ed85ca8faf7735ba8d656b1cc8aec0a7ddb5fabf9f47058ab"), - nonce: dehex("7ae8e2ca4ec500012e58495c"), - aad: dehex("68f2e77696ce7ae8e2ca4ec588e54d002e58495c"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748490008"), - ciphertext: dehex("958ec3f6d60afeda99efd888f175e5fcd4c87b9bcc5c2f5426253a8b506296c8c43309ab2adb5939462541d95e80811e04e706b1498f2c407c7fb234f8cc01a647550ee6b557b35a7e3945381821f4"), - }, - { - desc: "Derived from IEEE 2.8.2 61-byte crypt", - key: dehex("4c973dbc7364621674f8b5b89e5c15511fced9216490fb1c1a2caa0ffe0407e54e953fbe7166601476fab7ba"), - nonce: dehex("7ae8e2ca4ec500012e58495c"), - aad: dehex("68f2e77696ce7ae8e2ca4ec588e54d002e58495c"), - plaintext: dehex("08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748490008"), - ciphertext: dehex("b44d072011cd36d272a9b7a98db9aa90cbc5c67b93ddce67c854503214e2e896ec7e9db649ed4bcf6f850aac0223d0cf92c83db80795c3a17ecc1248bb00591712b1ae71e268164196252162810b00"), - }} { - aead, err := newRekeyAEAD(test.key) - if err != nil { - t.Fatal("unexpected failure in newRekeyAEAD: ", err.Error()) - } - if got := aead.Seal(nil, test.nonce, test.plaintext, test.aad); !bytes.Equal(got, test.ciphertext) { - t.Errorf("Unexpected ciphertext for test vector '%s':\nciphertext=%s\nwant= %s", - test.desc, hex.EncodeToString(got), hex.EncodeToString(test.ciphertext)) - } - if got, err := aead.Open(nil, test.nonce, test.ciphertext, test.aad); err != nil || !bytes.Equal(got, test.plaintext) { - t.Errorf("Unexpected plaintext for test vector '%s':\nplaintext=%s (err=%v)\nwant= %s", - test.desc, hex.EncodeToString(got), err, hex.EncodeToString(test.plaintext)) - } - - } -} - -func dehex(s string) []byte { - if len(s) == 0 { - return make([]byte, 0) - } - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm.go deleted file mode 100755 index 0c4fe33..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "crypto/aes" - "crypto/cipher" - - "google.golang.org/grpc/credentials/alts/core" -) - -const ( - // Overflow length n in bytes, never encrypt more than 2^(n*8) frames (in - // each direction). - overflowLenAES128GCM = 5 -) - -// aes128gcm is the struct that holds necessary information for ALTS record. -// The counter value is NOT included in the payload during the encryption and -// decryption operations. -type aes128gcm struct { - // inCounter is used in ALTS record to check that incoming counters are - // as expected, since ALTS record guarantees that messages are unwrapped - // in the same order that the peer wrapped them. - inCounter counter - outCounter counter - aead cipher.AEAD -} - -// NewAES128GCM creates an instance that uses aes128gcm for ALTS record. -func NewAES128GCM(side core.Side, key []byte) (ALTSRecordCrypto, error) { - c, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - a, err := cipher.NewGCM(c) - if err != nil { - return nil, err - } - return &aes128gcm{ - inCounter: newInCounter(side, overflowLenAES128GCM), - outCounter: newOutCounter(side, overflowLenAES128GCM), - aead: a, - }, nil -} - -// Encrypt is the encryption function. dst can contain bytes at the beginning of -// the ciphertext that will not be encrypted but will be authenticated. If dst -// has enough capacity to hold these bytes, the ciphertext and the tag, no -// allocation and copy operations will be performed. dst and plaintext do not -// overlap. -func (s *aes128gcm) Encrypt(dst, plaintext []byte) ([]byte, error) { - // If we need to allocate an output buffer, we want to include space for - // GCM tag to avoid forcing ALTS record to reallocate as well. - dlen := len(dst) - dst, out := SliceForAppend(dst, len(plaintext)+GcmTagSize) - seq, err := s.outCounter.Value() - if err != nil { - return nil, err - } - data := out[:len(plaintext)] - copy(data, plaintext) // data may alias plaintext - - // Seal appends the ciphertext and the tag to its first argument and - // returns the updated slice. However, SliceForAppend above ensures that - // dst has enough capacity to avoid a reallocation and copy due to the - // append. - dst = s.aead.Seal(dst[:dlen], seq, data, nil) - s.outCounter.Inc() - return dst, nil -} - -func (s *aes128gcm) EncryptionOverhead() int { - return GcmTagSize -} - -func (s *aes128gcm) Decrypt(dst, ciphertext []byte) ([]byte, error) { - seq, err := s.inCounter.Value() - if err != nil { - return nil, err - } - // If dst is equal to ciphertext[:0], ciphertext storage is reused. - plaintext, err := s.aead.Open(dst, seq, ciphertext, nil) - if err != nil { - return nil, ErrAuth - } - s.inCounter.Inc() - return plaintext, nil -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm_test.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm_test.go deleted file mode 100755 index c2fca4d..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcm_test.go +++ /dev/null @@ -1,223 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "bytes" - "testing" - - "google.golang.org/grpc/credentials/alts/core" -) - -// cryptoTestVector is struct for a GCM test vector -type cryptoTestVector struct { - key, counter, plaintext, ciphertext, tag []byte - allocateDst bool -} - -// getGCMCryptoPair outputs a client/server pair on aes128gcm. -func getGCMCryptoPair(key []byte, counter []byte, t *testing.T) (ALTSRecordCrypto, ALTSRecordCrypto) { - client, err := NewAES128GCM(core.ClientSide, key) - if err != nil { - t.Fatalf("NewAES128GCM(ClientSide, key) = %v", err) - } - server, err := NewAES128GCM(core.ServerSide, key) - if err != nil { - t.Fatalf("NewAES128GCM(ServerSide, key) = %v", err) - } - // set counter if provided. - if counter != nil { - if counterSide(counter) == core.ClientSide { - client.(*aes128gcm).outCounter = counterFromValue(counter, overflowLenAES128GCM) - server.(*aes128gcm).inCounter = counterFromValue(counter, overflowLenAES128GCM) - } else { - server.(*aes128gcm).outCounter = counterFromValue(counter, overflowLenAES128GCM) - client.(*aes128gcm).inCounter = counterFromValue(counter, overflowLenAES128GCM) - } - } - return client, server -} - -func testGCMEncryptionDecryption(sender ALTSRecordCrypto, receiver ALTSRecordCrypto, test *cryptoTestVector, withCounter bool, t *testing.T) { - // Ciphertext is: counter + encrypted text + tag. - ciphertext := []byte(nil) - if withCounter { - ciphertext = append(ciphertext, test.counter...) - } - ciphertext = append(ciphertext, test.ciphertext...) - ciphertext = append(ciphertext, test.tag...) - - // Decrypt. - if got, err := receiver.Decrypt(nil, ciphertext); err != nil || !bytes.Equal(got, test.plaintext) { - t.Errorf("key=%v\ncounter=%v\ntag=%v\nciphertext=%v\nDecrypt = %v, %v\nwant: %v", - test.key, test.counter, test.tag, test.ciphertext, got, err, test.plaintext) - } - - // Encrypt. - var dst []byte - if test.allocateDst { - dst = make([]byte, len(test.plaintext)+sender.EncryptionOverhead()) - } - if got, err := sender.Encrypt(dst[:0], test.plaintext); err != nil || !bytes.Equal(got, ciphertext) { - t.Errorf("key=%v\ncounter=%v\nplaintext=%v\nEncrypt = %v, %v\nwant: %v", - test.key, test.counter, test.plaintext, got, err, ciphertext) - } -} - -// Test encrypt and decrypt using test vectors for aes128gcm. -func TestAES128GCMEncrypt(t *testing.T) { - for _, test := range []cryptoTestVector{ - { - key: dehex("11754cd72aec309bf52f7687212e8957"), - counter: dehex("3c819d9a9bed087615030b65"), - plaintext: nil, - ciphertext: nil, - tag: dehex("250327c674aaf477aef2675748cf6971"), - allocateDst: false, - }, - { - key: dehex("ca47248ac0b6f8372a97ac43508308ed"), - counter: dehex("ffd2b598feabc9019262d2be"), - plaintext: nil, - ciphertext: nil, - tag: dehex("60d20404af527d248d893ae495707d1a"), - allocateDst: false, - }, - { - key: dehex("7fddb57453c241d03efbed3ac44e371c"), - counter: dehex("ee283a3fc75575e33efd4887"), - plaintext: dehex("d5de42b461646c255c87bd2962d3b9a2"), - ciphertext: dehex("2ccda4a5415cb91e135c2a0f78c9b2fd"), - tag: dehex("b36d1df9b9d5e596f83e8b7f52971cb3"), - allocateDst: false, - }, - { - key: dehex("ab72c77b97cb5fe9a382d9fe81ffdbed"), - counter: dehex("54cc7dc2c37ec006bcc6d1da"), - plaintext: dehex("007c5e5b3e59df24a7c355584fc1518d"), - ciphertext: dehex("0e1bde206a07a9c2c1b65300f8c64997"), - tag: dehex("2b4401346697138c7a4891ee59867d0c"), - allocateDst: false, - }, - { - key: dehex("11754cd72aec309bf52f7687212e8957"), - counter: dehex("3c819d9a9bed087615030b65"), - plaintext: nil, - ciphertext: nil, - tag: dehex("250327c674aaf477aef2675748cf6971"), - allocateDst: true, - }, - { - key: dehex("ca47248ac0b6f8372a97ac43508308ed"), - counter: dehex("ffd2b598feabc9019262d2be"), - plaintext: nil, - ciphertext: nil, - tag: dehex("60d20404af527d248d893ae495707d1a"), - allocateDst: true, - }, - { - key: dehex("7fddb57453c241d03efbed3ac44e371c"), - counter: dehex("ee283a3fc75575e33efd4887"), - plaintext: dehex("d5de42b461646c255c87bd2962d3b9a2"), - ciphertext: dehex("2ccda4a5415cb91e135c2a0f78c9b2fd"), - tag: dehex("b36d1df9b9d5e596f83e8b7f52971cb3"), - allocateDst: true, - }, - { - key: dehex("ab72c77b97cb5fe9a382d9fe81ffdbed"), - counter: dehex("54cc7dc2c37ec006bcc6d1da"), - plaintext: dehex("007c5e5b3e59df24a7c355584fc1518d"), - ciphertext: dehex("0e1bde206a07a9c2c1b65300f8c64997"), - tag: dehex("2b4401346697138c7a4891ee59867d0c"), - allocateDst: true, - }, - } { - // Test encryption and decryption for aes128gcm. - client, server := getGCMCryptoPair(test.key, test.counter, t) - if counterSide(test.counter) == core.ClientSide { - testGCMEncryptionDecryption(client, server, &test, false, t) - } else { - testGCMEncryptionDecryption(server, client, &test, false, t) - } - } -} - -func testGCMEncryptRoundtrip(client ALTSRecordCrypto, server ALTSRecordCrypto, t *testing.T) { - // Encrypt. - const plaintext = "This is plaintext." - var err error - buf := []byte(plaintext) - buf, err = client.Encrypt(buf[:0], buf) - if err != nil { - t.Fatal("Encrypting with client-side context: unexpected error", err, "\n", - "Plaintext:", []byte(plaintext)) - } - - // Encrypt a second message. - const plaintext2 = "This is a second plaintext." - buf2 := []byte(plaintext2) - buf2, err = client.Encrypt(buf2[:0], buf2) - if err != nil { - t.Fatal("Encrypting with client-side context: unexpected error", err, "\n", - "Plaintext:", []byte(plaintext2)) - } - - // Decryption fails: cannot decrypt second message before first. - if got, err := server.Decrypt(nil, buf2); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want unexpected counter error:\n", - " Original plaintext:", []byte(plaintext2), "\n", - " Ciphertext:", buf2, "\n", - " Decrypted plaintext:", got) - } - - // Decryption fails: wrong counter space. - if got, err := client.Decrypt(nil, buf); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want counter space error:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", buf, "\n", - " Decrypted plaintext:", got) - } - - // Decrypt first message. - ciphertext := append([]byte(nil), buf...) - buf, err = server.Decrypt(buf[:0], buf) - if err != nil || string(buf) != plaintext { - t.Fatal("Decrypting client-side ciphertext with a server-side context did not produce original content:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", ciphertext, "\n", - " Decryption error:", err, "\n", - " Decrypted plaintext:", buf) - } - - // Decryption fails: replay attack. - if got, err := server.Decrypt(nil, buf); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want unexpected counter error:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", buf, "\n", - " Decrypted plaintext:", got) - } -} - -// Test encrypt and decrypt on roundtrip messages for aes128gcm. -func TestAES128GCMEncryptRoundtrip(t *testing.T) { - // Test for aes128gcm. - key := make([]byte, 16) - client, server := getGCMCryptoPair(key, nil, t) - testGCMEncryptRoundtrip(client, server, t) -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey.go deleted file mode 100755 index 4b5ecf4..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey.go +++ /dev/null @@ -1,116 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "crypto/cipher" - - "google.golang.org/grpc/credentials/alts/core" -) - -const ( - // Overflow length n in bytes, never encrypt more than 2^(n*8) frames (in - // each direction). - overflowLenAES128GCMRekey = 8 - nonceLen = 12 - aeadKeyLen = 16 - kdfKeyLen = 32 - kdfCounterOffset = 2 - kdfCounterLen = 6 - sizeUint64 = 8 -) - -// aes128gcmRekey is the struct that holds necessary information for ALTS record. -// The counter value is NOT included in the payload during the encryption and -// decryption operations. -type aes128gcmRekey struct { - // inCounter is used in ALTS record to check that incoming counters are - // as expected, since ALTS record guarantees that messages are unwrapped - // in the same order that the peer wrapped them. - inCounter counter - outCounter counter - inAEAD cipher.AEAD - outAEAD cipher.AEAD -} - -// NewAES128GCMRekey creates an instance that uses aes128gcm with rekeying -// for ALTS record. The key argument should be 44 bytes, the first 32 bytes -// are used as a key for HKDF-expand and the remainining 12 bytes are used -// as a random mask for the counter. -func NewAES128GCMRekey(side core.Side, key []byte) (ALTSRecordCrypto, error) { - inCounter := newInCounter(side, overflowLenAES128GCMRekey) - outCounter := newOutCounter(side, overflowLenAES128GCMRekey) - inAEAD, err := newRekeyAEAD(key) - if err != nil { - return nil, err - } - outAEAD, err := newRekeyAEAD(key) - if err != nil { - return nil, err - } - return &aes128gcmRekey{ - inCounter, - outCounter, - inAEAD, - outAEAD, - }, nil -} - -// Encrypt is the encryption function. dst can contain bytes at the beginning of -// the ciphertext that will not be encrypted but will be authenticated. If dst -// has enough capacity to hold these bytes, the ciphertext and the tag, no -// allocation and copy operations will be performed. dst and plaintext do not -// overlap. -func (s *aes128gcmRekey) Encrypt(dst, plaintext []byte) ([]byte, error) { - // If we need to allocate an output buffer, we want to include space for - // GCM tag to avoid forcing ALTS record to reallocate as well. - dlen := len(dst) - dst, out := SliceForAppend(dst, len(plaintext)+GcmTagSize) - seq, err := s.outCounter.Value() - if err != nil { - return nil, err - } - data := out[:len(plaintext)] - copy(data, plaintext) // data may alias plaintext - - // Seal appends the ciphertext and the tag to its first argument and - // returns the updated slice. However, SliceForAppend above ensures that - // dst has enough capacity to avoid a reallocation and copy due to the - // append. - dst = s.outAEAD.Seal(dst[:dlen], seq, data, nil) - s.outCounter.Inc() - return dst, nil -} - -func (s *aes128gcmRekey) EncryptionOverhead() int { - return GcmTagSize -} - -func (s *aes128gcmRekey) Decrypt(dst, ciphertext []byte) ([]byte, error) { - seq, err := s.inCounter.Value() - if err != nil { - return nil, err - } - plaintext, err := s.inAEAD.Open(dst, seq, ciphertext, nil) - if err != nil { - return nil, ErrAuth - } - s.inCounter.Inc() - return plaintext, nil -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey_test.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey_test.go deleted file mode 100755 index 9f31a0f..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/aes128gcmrekey_test.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "testing" - - "google.golang.org/grpc/credentials/alts/core" -) - -// cryptoTestVector is struct for a rekey test vector -type rekeyTestVector struct { - key, nonce, plaintext, ciphertext []byte -} - -// getGCMCryptoPair outputs a client/server pair on aes128gcmRekey. -func getRekeyCryptoPair(key []byte, counter []byte, t *testing.T) (ALTSRecordCrypto, ALTSRecordCrypto) { - client, err := NewAES128GCMRekey(core.ClientSide, key) - if err != nil { - t.Fatalf("NewAES128GCMRekey(ClientSide, key) = %v", err) - } - server, err := NewAES128GCMRekey(core.ServerSide, key) - if err != nil { - t.Fatalf("NewAES128GCMRekey(ServerSide, key) = %v", err) - } - // set counter if provided. - if counter != nil { - if counterSide(counter) == core.ClientSide { - client.(*aes128gcmRekey).outCounter = counterFromValue(counter, overflowLenAES128GCMRekey) - server.(*aes128gcmRekey).inCounter = counterFromValue(counter, overflowLenAES128GCMRekey) - } else { - server.(*aes128gcmRekey).outCounter = counterFromValue(counter, overflowLenAES128GCMRekey) - client.(*aes128gcmRekey).inCounter = counterFromValue(counter, overflowLenAES128GCMRekey) - } - } - return client, server -} - -func testRekeyEncryptRoundtrip(client ALTSRecordCrypto, server ALTSRecordCrypto, t *testing.T) { - // Encrypt. - const plaintext = "This is plaintext." - var err error - buf := []byte(plaintext) - buf, err = client.Encrypt(buf[:0], buf) - if err != nil { - t.Fatal("Encrypting with client-side context: unexpected error", err, "\n", - "Plaintext:", []byte(plaintext)) - } - - // Encrypt a second message. - const plaintext2 = "This is a second plaintext." - buf2 := []byte(plaintext2) - buf2, err = client.Encrypt(buf2[:0], buf2) - if err != nil { - t.Fatal("Encrypting with client-side context: unexpected error", err, "\n", - "Plaintext:", []byte(plaintext2)) - } - - // Decryption fails: cannot decrypt second message before first. - if got, err := server.Decrypt(nil, buf2); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want unexpected counter error:\n", - " Original plaintext:", []byte(plaintext2), "\n", - " Ciphertext:", buf2, "\n", - " Decrypted plaintext:", got) - } - - // Decryption fails: wrong counter space. - if got, err := client.Decrypt(nil, buf); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want counter space error:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", buf, "\n", - " Decrypted plaintext:", got) - } - - // Decrypt first message. - ciphertext := append([]byte(nil), buf...) - buf, err = server.Decrypt(buf[:0], buf) - if err != nil || string(buf) != plaintext { - t.Fatal("Decrypting client-side ciphertext with a server-side context did not produce original content:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", ciphertext, "\n", - " Decryption error:", err, "\n", - " Decrypted plaintext:", buf) - } - - // Decryption fails: replay attack. - if got, err := server.Decrypt(nil, buf); err == nil { - t.Error("Decrypting client-side ciphertext with a client-side context unexpectedly succeeded; want unexpected counter error:\n", - " Original plaintext:", []byte(plaintext), "\n", - " Ciphertext:", buf, "\n", - " Decrypted plaintext:", got) - } -} - -// Test encrypt and decrypt on roundtrip messages for aes128gcmRekey. -func TestAES128GCMRekeyEncryptRoundtrip(t *testing.T) { - // Test for aes128gcmRekey. - key := make([]byte, 44) - client, server := getRekeyCryptoPair(key, nil, t) - testRekeyEncryptRoundtrip(client, server, t) -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/common.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/common.go deleted file mode 100755 index 1795d0c..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/common.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "encoding/binary" - "errors" - "fmt" -) - -const ( - // GcmTagSize is the GCM tag size is the difference in length between - // plaintext and ciphertext. From crypto/cipher/gcm.go in Go crypto - // library. - GcmTagSize = 16 -) - -// ErrAuth occurs on authentication failure. -var ErrAuth = errors.New("message authentication failed") - -// SliceForAppend takes a slice and a requested number of bytes. It returns a -// slice with the contents of the given slice followed by that many bytes and a -// second slice that aliases into it and contains only the extra bytes. If the -// original slice has sufficient capacity then no allocation is performed. -func SliceForAppend(in []byte, n int) (head, tail []byte) { - if total := len(in) + n; cap(in) >= total { - head = in[:total] - } else { - head = make([]byte, total) - copy(head, in) - } - tail = head[len(in):] - return head, tail -} - -// ParseFramedMsg parse the provided buffer and returns a frame of the format -// msgLength+msg and any remaining bytes in that buffer. -func ParseFramedMsg(b []byte, maxLen uint32) ([]byte, []byte, error) { - // If the size field is not complete, return the provided buffer as - // remaining buffer. - if len(b) < MsgLenFieldSize { - return nil, b, nil - } - msgLenField := b[:MsgLenFieldSize] - length := binary.LittleEndian.Uint32(msgLenField) - if length > maxLen { - return nil, nil, fmt.Errorf("received the frame length %d larger than the limit %d", length, maxLen) - } - if len(b) < int(length)+4 { // account for the first 4 msg length bytes. - // Frame is not complete yet. - return nil, b, nil - } - return b[:MsgLenFieldSize+length], b[MsgLenFieldSize+length:], nil -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/counter.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/counter.go deleted file mode 100755 index 754dcfa..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/counter.go +++ /dev/null @@ -1,106 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "errors" - - "google.golang.org/grpc/credentials/alts/core" -) - -const counterLen = 12 - -var ( - errInvalidCounter = errors.New("invalid counter") -) - -// counter is a 96-bit, little-endian counter. -type counter struct { - value [counterLen]byte - invalid bool - overflowLen int -} - -// newOutCounter returns an outgoing counter initialized to the starting sequence -// number for the client/server side of a connection. -func newOutCounter(s core.Side, overflowLen int) (c counter) { - c.overflowLen = overflowLen - if s == core.ServerSide { - // Server counters in ALTS record have the little-endian high bit - // set. - c.value[counterLen-1] = 0x80 - } - return -} - -// newInCounter returns an incoming counter initialized to the starting sequence -// number for the client/server side of a connection. This is used in ALTS record -// to check that incoming counters are as expected, since ALTS record guarantees -// that messages are unwrapped in the same order that the peer wrapped them. -func newInCounter(s core.Side, overflowLen int) (c counter) { - c.overflowLen = overflowLen - if s == core.ClientSide { - // Server counters in ALTS record have the little-endian high bit - // set. - c.value[counterLen-1] = 0x80 - } - return -} - -// counterFromValue creates a new counter given an initial value. -func counterFromValue(value []byte, overflowLen int) (c counter) { - c.overflowLen = overflowLen - copy(c.value[:], value) - return -} - -// Value returns the current value of the counter as a byte slice. -func (c *counter) Value() ([]byte, error) { - if c.invalid { - return nil, errInvalidCounter - } - return c.value[:], nil -} - -// Inc increments the counter and checks for overflow. -func (c *counter) Inc() { - // If the counter is already invalid, there is not need to increase it. - if c.invalid { - return - } - i := 0 - for ; i < c.overflowLen; i++ { - c.value[i]++ - if c.value[i] != 0 { - break - } - } - if i == c.overflowLen { - c.invalid = true - } -} - -// counterSide returns the connection side (client/server) a sequence counter is -// associated with. -func counterSide(c []byte) core.Side { - if c[counterLen-1]&0x80 == 0x80 { - return core.ServerSide - } - return core.ClientSide -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/counter_test.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/counter_test.go deleted file mode 100755 index faf5636..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/counter_test.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "bytes" - "testing" - - "google.golang.org/grpc/credentials/alts/core" -) - -const ( - testOverflowLen = 5 -) - -func TestCounterSides(t *testing.T) { - for _, side := range []core.Side{core.ClientSide, core.ServerSide} { - outCounter := newOutCounter(side, testOverflowLen) - inCounter := newInCounter(side, testOverflowLen) - for i := 0; i < 1024; i++ { - value, _ := outCounter.Value() - if g, w := counterSide(value), side; g != w { - t.Errorf("after %d iterations, counterSide(outCounter.Value()) = %v, want %v", i, g, w) - break - } - value, _ = inCounter.Value() - if g, w := counterSide(value), side; g == w { - t.Errorf("after %d iterations, counterSide(inCounter.Value()) = %v, want %v", i, g, w) - break - } - outCounter.Inc() - inCounter.Inc() - } - } -} - -func TestCounterInc(t *testing.T) { - for _, test := range []struct { - counter []byte - want []byte - }{ - { - counter: []byte{0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - want: []byte{0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - }, - { - counter: []byte{0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80}, - want: []byte{0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80}, - }, - { - counter: []byte{0xff, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - want: []byte{0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - }, - { - counter: []byte{0x42, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - want: []byte{0x43, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - }, - { - counter: []byte{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - want: []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - }, - { - counter: []byte{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, - want: []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, - }, - } { - c := counterFromValue(test.counter, overflowLenAES128GCM) - c.Inc() - value, _ := c.Value() - if g, w := value, test.want; !bytes.Equal(g, w) || c.invalid { - t.Errorf("counter(%v).Inc() =\n%v, want\n%v", test.counter, g, w) - } - } -} - -func TestRolloverCounter(t *testing.T) { - for _, test := range []struct { - desc string - value []byte - overflowLen int - }{ - { - desc: "testing overflow without rekeying 1", - value: []byte{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, - overflowLen: 5, - }, - { - desc: "testing overflow without rekeying 2", - value: []byte{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - overflowLen: 5, - }, - { - desc: "testing overflow for rekeying mode 1", - value: []byte{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x80}, - overflowLen: 8, - }, - { - desc: "testing overflow for rekeying mode 2", - value: []byte{0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00}, - overflowLen: 8, - }, - } { - c := counterFromValue(test.value, overflowLenAES128GCM) - - // First Inc() + Value() should work. - c.Inc() - _, err := c.Value() - if err != nil { - t.Errorf("%v: first Inc() + Value() unexpectedly failed: %v, want error", test.desc, err) - } - // Second Inc() + Value() should fail. - c.Inc() - _, err = c.Value() - if err != errInvalidCounter { - t.Errorf("%v: second Inc() + Value() unexpectedly succeeded: want %v", test.desc, errInvalidCounter) - } - // Third Inc() + Value() should also fail because the counter is - // already in an invalid state. - c.Inc() - _, err = c.Value() - if err != errInvalidCounter { - t.Errorf("%v: Third Inc() + Value() unexpectedly succeeded: want %v", test.desc, errInvalidCounter) - } - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/record.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/record.go deleted file mode 100755 index cb514eb..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/record.go +++ /dev/null @@ -1,271 +0,0 @@ -/* - * - * 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. - * - */ - -// Package conn contains an implementation of a secure channel created by gRPC -// handshakers. -package conn - -import ( - "encoding/binary" - "fmt" - "math" - "net" - - "google.golang.org/grpc/credentials/alts/core" -) - -// ALTSRecordCrypto is the interface for gRPC ALTS record protocol. -type ALTSRecordCrypto interface { - // Encrypt encrypts the plaintext and computes the tag (if any) of dst - // and plaintext, dst and plaintext do not overlap. - Encrypt(dst, plaintext []byte) ([]byte, error) - // EncryptionOverhead returns the tag size (if any) in bytes. - EncryptionOverhead() int - // Decrypt decrypts ciphertext and verify the tag (if any). dst and - // ciphertext may alias exactly or not at all. To reuse ciphertext's - // storage for the decrypted output, use ciphertext[:0] as dst. - Decrypt(dst, ciphertext []byte) ([]byte, error) -} - -// ALTSRecordFunc is a function type for factory functions that create -// ALTSRecordCrypto instances. -type ALTSRecordFunc func(s core.Side, keyData []byte) (ALTSRecordCrypto, error) - -const ( - // MsgLenFieldSize is the byte size of the frame length field of a - // framed message. - MsgLenFieldSize = 4 - // The byte size of the message type field of a framed message. - msgTypeFieldSize = 4 - // The bytes size limit for a ALTS record message. - altsRecordLengthLimit = 1024 * 1024 // 1 MiB - // The default bytes size of a ALTS record message. - altsRecordDefaultLength = 4 * 1024 // 4KiB - // Message type value included in ALTS record framing. - altsRecordMsgType = uint32(0x06) - // The initial write buffer size. - altsWriteBufferInitialSize = 32 * 1024 // 32KiB - // The maximum write buffer size. This *must* be multiple of - // altsRecordDefaultLength. - altsWriteBufferMaxSize = 512 * 1024 // 512KiB -) - -var ( - protocols = make(map[string]ALTSRecordFunc) -) - -// RegisterProtocol register a ALTS record encryption protocol. -func RegisterProtocol(protocol string, f ALTSRecordFunc) error { - if _, ok := protocols[protocol]; ok { - return fmt.Errorf("protocol %v is already registered", protocol) - } - protocols[protocol] = f - return nil -} - -// conn represents a secured connection. It implements the net.Conn interface. -type conn struct { - net.Conn - crypto ALTSRecordCrypto - // buf holds data that has been read from the connection and decrypted, - // but has not yet been returned by Read. - buf []byte - payloadLengthLimit int - // protected holds data read from the network but have not yet been - // decrypted. This data might not compose a complete frame. - protected []byte - // writeBuf is a buffer used to contain encrypted frames before being - // written to the network. - writeBuf []byte - // nextFrame stores the next frame (in protected buffer) info. - nextFrame []byte - // overhead is the calculated overhead of each frame. - overhead int -} - -// NewConn creates a new secure channel instance given the other party role and -// handshaking result. -func NewConn(c net.Conn, side core.Side, recordProtocol string, key []byte, protected []byte) (net.Conn, error) { - newCrypto := protocols[recordProtocol] - if newCrypto == nil { - return nil, fmt.Errorf("negotiated unknown next_protocol %q", recordProtocol) - } - crypto, err := newCrypto(side, key) - if err != nil { - return nil, fmt.Errorf("protocol %q: %v", recordProtocol, err) - } - overhead := MsgLenFieldSize + msgTypeFieldSize + crypto.EncryptionOverhead() - payloadLengthLimit := altsRecordDefaultLength - overhead - if protected == nil { - // We pre-allocate protected to be of size - // 2*altsRecordDefaultLength-1 during initialization. We only - // read from the network into protected when protected does not - // contain a complete frame, which is at most - // altsRecordDefaultLength-1 (bytes). And we read at most - // altsRecordDefaultLength (bytes) data into protected at one - // time. Therefore, 2*altsRecordDefaultLength-1 is large enough - // to buffer data read from the network. - protected = make([]byte, 0, 2*altsRecordDefaultLength-1) - } - - altsConn := &conn{ - Conn: c, - crypto: crypto, - payloadLengthLimit: payloadLengthLimit, - protected: protected, - writeBuf: make([]byte, altsWriteBufferInitialSize), - nextFrame: protected, - overhead: overhead, - } - return altsConn, nil -} - -// Read reads and decrypts a frame from the underlying connection, and copies the -// decrypted payload into b. If the size of the payload is greater than len(b), -// Read retains the remaining bytes in an internal buffer, and subsequent calls -// to Read will read from this buffer until it is exhausted. -func (p *conn) Read(b []byte) (n int, err error) { - if len(p.buf) == 0 { - var framedMsg []byte - framedMsg, p.nextFrame, err = ParseFramedMsg(p.nextFrame, altsRecordLengthLimit) - if err != nil { - return n, err - } - // Check whether the next frame to be decrypted has been - // completely received yet. - if len(framedMsg) == 0 { - copy(p.protected, p.nextFrame) - p.protected = p.protected[:len(p.nextFrame)] - // Always copy next incomplete frame to the beginning of - // the protected buffer and reset nextFrame to it. - p.nextFrame = p.protected - } - // Check whether a complete frame has been received yet. - for len(framedMsg) == 0 { - if len(p.protected) == cap(p.protected) { - tmp := make([]byte, len(p.protected), cap(p.protected)+altsRecordDefaultLength) - copy(tmp, p.protected) - p.protected = tmp - } - n, err = p.Conn.Read(p.protected[len(p.protected):min(cap(p.protected), len(p.protected)+altsRecordDefaultLength)]) - if err != nil { - return 0, err - } - p.protected = p.protected[:len(p.protected)+n] - framedMsg, p.nextFrame, err = ParseFramedMsg(p.protected, altsRecordLengthLimit) - if err != nil { - return 0, err - } - } - // Now we have a complete frame, decrypted it. - msg := framedMsg[MsgLenFieldSize:] - msgType := binary.LittleEndian.Uint32(msg[:msgTypeFieldSize]) - if msgType&0xff != altsRecordMsgType { - return 0, fmt.Errorf("received frame with incorrect message type %v, expected lower byte %v", - msgType, altsRecordMsgType) - } - ciphertext := msg[msgTypeFieldSize:] - - // Decrypt requires that if the dst and ciphertext alias, they - // must alias exactly. Code here used to use msg[:0], but msg - // starts MsgLenFieldSize+msgTypeFieldSize bytes earlier than - // ciphertext, so they alias inexactly. Using ciphertext[:0] - // arranges the appropriate aliasing without needing to copy - // ciphertext or use a separate destination buffer. For more info - // check: https://golang.org/pkg/crypto/cipher/#AEAD. - p.buf, err = p.crypto.Decrypt(ciphertext[:0], ciphertext) - if err != nil { - return 0, err - } - } - - n = copy(b, p.buf) - p.buf = p.buf[n:] - return n, nil -} - -// Write encrypts, frames, and writes bytes from b to the underlying connection. -func (p *conn) Write(b []byte) (n int, err error) { - n = len(b) - // Calculate the output buffer size with framing and encryption overhead. - numOfFrames := int(math.Ceil(float64(len(b)) / float64(p.payloadLengthLimit))) - size := len(b) + numOfFrames*p.overhead - // If writeBuf is too small, increase its size up to the maximum size. - partialBSize := len(b) - if size > altsWriteBufferMaxSize { - size = altsWriteBufferMaxSize - const numOfFramesInMaxWriteBuf = altsWriteBufferMaxSize / altsRecordDefaultLength - partialBSize = numOfFramesInMaxWriteBuf * p.payloadLengthLimit - } - if len(p.writeBuf) < size { - p.writeBuf = make([]byte, size) - } - - for partialBStart := 0; partialBStart < len(b); partialBStart += partialBSize { - partialBEnd := partialBStart + partialBSize - if partialBEnd > len(b) { - partialBEnd = len(b) - } - partialB := b[partialBStart:partialBEnd] - writeBufIndex := 0 - for len(partialB) > 0 { - payloadLen := len(partialB) - if payloadLen > p.payloadLengthLimit { - payloadLen = p.payloadLengthLimit - } - buf := partialB[:payloadLen] - partialB = partialB[payloadLen:] - - // Write buffer contains: length, type, payload, and tag - // if any. - - // 1. Fill in type field. - msg := p.writeBuf[writeBufIndex+MsgLenFieldSize:] - binary.LittleEndian.PutUint32(msg, altsRecordMsgType) - - // 2. Encrypt the payload and create a tag if any. - msg, err = p.crypto.Encrypt(msg[:msgTypeFieldSize], buf) - if err != nil { - return n, err - } - - // 3. Fill in the size field. - binary.LittleEndian.PutUint32(p.writeBuf[writeBufIndex:], uint32(len(msg))) - - // 4. Increase writeBufIndex. - writeBufIndex += len(buf) + p.overhead - } - nn, err := p.Conn.Write(p.writeBuf[:writeBufIndex]) - if err != nil { - // We need to calculate the actual data size that was - // written. This means we need to remove header, - // encryption overheads, and any partially-written - // frame data. - numOfWrittenFrames := int(math.Floor(float64(nn) / float64(altsRecordDefaultLength))) - return partialBStart + numOfWrittenFrames*p.payloadLengthLimit, err - } - } - return n, nil -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/conn/record_test.go b/examples/google.golang.org/grpc/credentials/alts/core/conn/record_test.go deleted file mode 100755 index 5c3b8e2..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/conn/record_test.go +++ /dev/null @@ -1,274 +0,0 @@ -/* - * - * 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. - * - */ - -package conn - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "math" - "net" - "reflect" - "testing" - - "google.golang.org/grpc/credentials/alts/core" -) - -var ( - nextProtocols = []string{"ALTSRP_GCM_AES128"} - altsRecordFuncs = map[string]ALTSRecordFunc{ - // ALTS handshaker protocols. - "ALTSRP_GCM_AES128": func(s core.Side, keyData []byte) (ALTSRecordCrypto, error) { - return NewAES128GCM(s, keyData) - }, - } -) - -func init() { - for protocol, f := range altsRecordFuncs { - if err := RegisterProtocol(protocol, f); err != nil { - panic(err) - } - } -} - -// testConn mimics a net.Conn to the peer. -type testConn struct { - net.Conn - in *bytes.Buffer - out *bytes.Buffer -} - -func (c *testConn) Read(b []byte) (n int, err error) { - return c.in.Read(b) -} - -func (c *testConn) Write(b []byte) (n int, err error) { - return c.out.Write(b) -} - -func (c *testConn) Close() error { - return nil -} - -func newTestALTSRecordConn(in, out *bytes.Buffer, side core.Side, np string) *conn { - key := []byte{ - // 16 arbitrary bytes. - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xd2, 0x4c, 0xce, 0x4f, 0x49} - tc := testConn{ - in: in, - out: out, - } - c, err := NewConn(&tc, side, np, key, nil) - if err != nil { - panic(fmt.Sprintf("Unexpected error creating test ALTS record connection: %v", err)) - } - return c.(*conn) -} - -func newConnPair(np string) (client, server *conn) { - clientBuf := new(bytes.Buffer) - serverBuf := new(bytes.Buffer) - clientConn := newTestALTSRecordConn(clientBuf, serverBuf, core.ClientSide, np) - serverConn := newTestALTSRecordConn(serverBuf, clientBuf, core.ServerSide, np) - return clientConn, serverConn -} - -func testPingPong(t *testing.T, np string) { - clientConn, serverConn := newConnPair(np) - clientMsg := []byte("Client Message") - if n, err := clientConn.Write(clientMsg); n != len(clientMsg) || err != nil { - t.Fatalf("Client Write() = %v, %v; want %v, ", n, err, len(clientMsg)) - } - rcvClientMsg := make([]byte, len(clientMsg)) - if n, err := serverConn.Read(rcvClientMsg); n != len(rcvClientMsg) || err != nil { - t.Fatalf("Server Read() = %v, %v; want %v, ", n, err, len(rcvClientMsg)) - } - if !reflect.DeepEqual(clientMsg, rcvClientMsg) { - t.Fatalf("Client Write()/Server Read() = %v, want %v", rcvClientMsg, clientMsg) - } - - serverMsg := []byte("Server Message") - if n, err := serverConn.Write(serverMsg); n != len(serverMsg) || err != nil { - t.Fatalf("Server Write() = %v, %v; want %v, ", n, err, len(serverMsg)) - } - rcvServerMsg := make([]byte, len(serverMsg)) - if n, err := clientConn.Read(rcvServerMsg); n != len(rcvServerMsg) || err != nil { - t.Fatalf("Client Read() = %v, %v; want %v, ", n, err, len(rcvServerMsg)) - } - if !reflect.DeepEqual(serverMsg, rcvServerMsg) { - t.Fatalf("Server Write()/Client Read() = %v, want %v", rcvServerMsg, serverMsg) - } -} - -func TestPingPong(t *testing.T) { - for _, np := range nextProtocols { - testPingPong(t, np) - } -} - -func testSmallReadBuffer(t *testing.T, np string) { - clientConn, serverConn := newConnPair(np) - msg := []byte("Very Important Message") - if n, err := clientConn.Write(msg); err != nil { - t.Fatalf("Write() = %v, %v; want %v, ", n, err, len(msg)) - } - rcvMsg := make([]byte, len(msg)) - n := 2 // Arbitrary index to break rcvMsg in two. - rcvMsg1 := rcvMsg[:n] - rcvMsg2 := rcvMsg[n:] - if n, err := serverConn.Read(rcvMsg1); n != len(rcvMsg1) || err != nil { - t.Fatalf("Read() = %v, %v; want %v, ", n, err, len(rcvMsg1)) - } - if n, err := serverConn.Read(rcvMsg2); n != len(rcvMsg2) || err != nil { - t.Fatalf("Read() = %v, %v; want %v, ", n, err, len(rcvMsg2)) - } - if !reflect.DeepEqual(msg, rcvMsg) { - t.Fatalf("Write()/Read() = %v, want %v", rcvMsg, msg) - } -} - -func TestSmallReadBuffer(t *testing.T) { - for _, np := range nextProtocols { - testSmallReadBuffer(t, np) - } -} - -func testLargeMsg(t *testing.T, np string) { - clientConn, serverConn := newConnPair(np) - // msgLen is such that the length in the framing is larger than the - // default size of one frame. - msgLen := altsRecordDefaultLength - msgTypeFieldSize - clientConn.crypto.EncryptionOverhead() + 1 - msg := make([]byte, msgLen) - if n, err := clientConn.Write(msg); n != len(msg) || err != nil { - t.Fatalf("Write() = %v, %v; want %v, ", n, err, len(msg)) - } - rcvMsg := make([]byte, len(msg)) - if n, err := io.ReadFull(serverConn, rcvMsg); n != len(rcvMsg) || err != nil { - t.Fatalf("Read() = %v, %v; want %v, ", n, err, len(rcvMsg)) - } - if !reflect.DeepEqual(msg, rcvMsg) { - t.Fatalf("Write()/Server Read() = %v, want %v", rcvMsg, msg) - } -} - -func TestLargeMsg(t *testing.T) { - for _, np := range nextProtocols { - testLargeMsg(t, np) - } -} - -func testIncorrectMsgType(t *testing.T, np string) { - // framedMsg is an empty ciphertext with correct framing but wrong - // message type. - framedMsg := make([]byte, MsgLenFieldSize+msgTypeFieldSize) - binary.LittleEndian.PutUint32(framedMsg[:MsgLenFieldSize], msgTypeFieldSize) - wrongMsgType := uint32(0x22) - binary.LittleEndian.PutUint32(framedMsg[MsgLenFieldSize:], wrongMsgType) - - in := bytes.NewBuffer(framedMsg) - c := newTestALTSRecordConn(in, nil, core.ClientSide, np) - b := make([]byte, 1) - if n, err := c.Read(b); n != 0 || err == nil { - t.Fatalf("Read() = , want %v", fmt.Errorf("received frame with incorrect message type %v", wrongMsgType)) - } -} - -func TestIncorrectMsgType(t *testing.T) { - for _, np := range nextProtocols { - testIncorrectMsgType(t, np) - } -} - -func testFrameTooLarge(t *testing.T, np string) { - buf := new(bytes.Buffer) - clientConn := newTestALTSRecordConn(nil, buf, core.ClientSide, np) - serverConn := newTestALTSRecordConn(buf, nil, core.ServerSide, np) - // payloadLen is such that the length in the framing is larger than - // allowed in one frame. - payloadLen := altsRecordLengthLimit - msgTypeFieldSize - clientConn.crypto.EncryptionOverhead() + 1 - payload := make([]byte, payloadLen) - c, err := clientConn.crypto.Encrypt(nil, payload) - if err != nil { - t.Fatalf(fmt.Sprintf("Error encrypting message: %v", err)) - } - msgLen := msgTypeFieldSize + len(c) - framedMsg := make([]byte, MsgLenFieldSize+msgLen) - binary.LittleEndian.PutUint32(framedMsg[:MsgLenFieldSize], uint32(msgTypeFieldSize+len(c))) - msg := framedMsg[MsgLenFieldSize:] - binary.LittleEndian.PutUint32(msg[:msgTypeFieldSize], altsRecordMsgType) - copy(msg[msgTypeFieldSize:], c) - if _, err = buf.Write(framedMsg); err != nil { - t.Fatal(fmt.Sprintf("Unexpected error writing to buffer: %v", err)) - } - b := make([]byte, 1) - if n, err := serverConn.Read(b); n != 0 || err == nil { - t.Fatalf("Read() = , want %v", fmt.Errorf("received the frame length %d larger than the limit %d", altsRecordLengthLimit+1, altsRecordLengthLimit)) - } -} - -func TestFrameTooLarge(t *testing.T) { - for _, np := range nextProtocols { - testFrameTooLarge(t, np) - } -} - -func testWriteLargeData(t *testing.T, np string) { - // Test sending and receiving messages larger than the maximum write - // buffer size. - clientConn, serverConn := newConnPair(np) - // Message size is intentionally chosen to not be multiple of - // payloadLengthLimtit. - msgSize := altsWriteBufferMaxSize + (100 * 1024) - clientMsg := make([]byte, msgSize) - for i := 0; i < msgSize; i++ { - clientMsg[i] = 0xAA - } - if n, err := clientConn.Write(clientMsg); n != len(clientMsg) || err != nil { - t.Fatalf("Client Write() = %v, %v; want %v, ", n, err, len(clientMsg)) - } - // We need to keep reading until the entire message is received. The - // reason we set all bytes of the message to a value other than zero is - // to avoid ambiguous zero-init value of rcvClientMsg buffer and the - // actual received data. - rcvClientMsg := make([]byte, 0, msgSize) - numberOfExpectedFrames := int(math.Ceil(float64(msgSize) / float64(serverConn.payloadLengthLimit))) - for i := 0; i < numberOfExpectedFrames; i++ { - expectedRcvSize := serverConn.payloadLengthLimit - if i == numberOfExpectedFrames-1 { - // Last frame might be smaller. - expectedRcvSize = msgSize % serverConn.payloadLengthLimit - } - tmpBuf := make([]byte, expectedRcvSize) - if n, err := serverConn.Read(tmpBuf); n != len(tmpBuf) || err != nil { - t.Fatalf("Server Read() = %v, %v; want %v, ", n, err, len(tmpBuf)) - } - rcvClientMsg = append(rcvClientMsg, tmpBuf...) - } - if !reflect.DeepEqual(clientMsg, rcvClientMsg) { - t.Fatalf("Client Write()/Server Read() = %v, want %v", rcvClientMsg, clientMsg) - } -} - -func TestWriteLargeData(t *testing.T) { - for _, np := range nextProtocols { - testWriteLargeData(t, np) - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker.go b/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker.go deleted file mode 100755 index a204978..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker.go +++ /dev/null @@ -1,365 +0,0 @@ -/* - * - * 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. - * - */ - -// Package handshaker provides ALTS handshaking functionality for GCP. -package handshaker - -import ( - "errors" - "fmt" - "io" - "net" - "sync" - - "golang.org/x/net/context" - grpc "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/alts/core" - "google.golang.org/grpc/credentials/alts/core/authinfo" - "google.golang.org/grpc/credentials/alts/core/conn" - altsgrpc "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" -) - -const ( - // The maximum byte size of receive frames. - frameLimit = 64 * 1024 // 64 KB - rekeyRecordProtocolName = "ALTSRP_GCM_AES128_REKEY" - // maxPendingHandshakes represents the maximum number of concurrent - // handshakes. - maxPendingHandshakes = 100 -) - -var ( - hsProtocol = altspb.HandshakeProtocol_ALTS - appProtocols = []string{"grpc"} - recordProtocols = []string{rekeyRecordProtocolName} - keyLength = map[string]int{ - rekeyRecordProtocolName: 44, - } - altsRecordFuncs = map[string]conn.ALTSRecordFunc{ - // ALTS handshaker protocols. - rekeyRecordProtocolName: func(s core.Side, keyData []byte) (conn.ALTSRecordCrypto, error) { - return conn.NewAES128GCMRekey(s, keyData) - }, - } - // control number of concurrent created (but not closed) handshakers. - mu sync.Mutex - concurrentHandshakes = int64(0) - // errDropped occurs when maxPendingHandshakes is reached. - errDropped = errors.New("maximum number of concurrent ALTS handshakes is reached") -) - -func init() { - for protocol, f := range altsRecordFuncs { - if err := conn.RegisterProtocol(protocol, f); err != nil { - panic(err) - } - } -} - -func acquire(n int64) bool { - mu.Lock() - success := maxPendingHandshakes-concurrentHandshakes >= n - if success { - concurrentHandshakes += n - } - mu.Unlock() - return success -} - -func release(n int64) { - mu.Lock() - concurrentHandshakes -= n - if concurrentHandshakes < 0 { - mu.Unlock() - panic("bad release") - } - mu.Unlock() -} - -// ClientHandshakerOptions contains the client handshaker options that can -// provided by the caller. -type ClientHandshakerOptions struct { - // ClientIdentity is the handshaker client local identity. - ClientIdentity *altspb.Identity - // TargetName is the server service account name for secure name - // checking. - TargetName string - // TargetServiceAccounts contains a list of expected target service - // accounts. One of these accounts should match one of the accounts in - // the handshaker results. Otherwise, the handshake fails. - TargetServiceAccounts []string - // RPCVersions specifies the gRPC versions accepted by the client. - RPCVersions *altspb.RpcProtocolVersions -} - -// ServerHandshakerOptions contains the server handshaker options that can -// provided by the caller. -type ServerHandshakerOptions struct { - // RPCVersions specifies the gRPC versions accepted by the server. - RPCVersions *altspb.RpcProtocolVersions -} - -// DefaultClientHandshakerOptions returns the default client handshaker options. -func DefaultClientHandshakerOptions() *ClientHandshakerOptions { - return &ClientHandshakerOptions{} -} - -// DefaultServerHandshakerOptions returns the default client handshaker options. -func DefaultServerHandshakerOptions() *ServerHandshakerOptions { - return &ServerHandshakerOptions{} -} - -// TODO: add support for future local and remote endpoint in both client options -// and server options (server options struct does not exist now. When -// caller can provide endpoints, it should be created. - -// altsHandshaker is used to complete a ALTS handshaking between client and -// server. This handshaker talks to the ALTS handshaker service in the metadata -// server. -type altsHandshaker struct { - // RPC stream used to access the ALTS Handshaker service. - stream altsgrpc.HandshakerService_DoHandshakeClient - // the connection to the peer. - conn net.Conn - // client handshake options. - clientOpts *ClientHandshakerOptions - // server handshake options. - serverOpts *ServerHandshakerOptions - // defines the side doing the handshake, client or server. - side core.Side -} - -// NewClientHandshaker creates a ALTS handshaker for GCP which contains an RPC -// stub created using the passed conn and used to talk to the ALTS Handshaker -// service in the metadata server. -func NewClientHandshaker(ctx context.Context, conn *grpc.ClientConn, c net.Conn, opts *ClientHandshakerOptions) (core.Handshaker, error) { - stream, err := altsgrpc.NewHandshakerServiceClient(conn).DoHandshake(ctx, grpc.FailFast(false)) - if err != nil { - return nil, err - } - return &altsHandshaker{ - stream: stream, - conn: c, - clientOpts: opts, - side: core.ClientSide, - }, nil -} - -// NewServerHandshaker creates a ALTS handshaker for GCP which contains an RPC -// stub created using the passed conn and used to talk to the ALTS Handshaker -// service in the metadata server. -func NewServerHandshaker(ctx context.Context, conn *grpc.ClientConn, c net.Conn, opts *ServerHandshakerOptions) (core.Handshaker, error) { - stream, err := altsgrpc.NewHandshakerServiceClient(conn).DoHandshake(ctx, grpc.FailFast(false)) - if err != nil { - return nil, err - } - return &altsHandshaker{ - stream: stream, - conn: c, - serverOpts: opts, - side: core.ServerSide, - }, nil -} - -// ClientHandshake starts and completes a client ALTS handshaking for GCP. Once -// done, ClientHandshake returns a secure connection. -func (h *altsHandshaker) ClientHandshake(ctx context.Context) (net.Conn, credentials.AuthInfo, error) { - if !acquire(1) { - return nil, nil, errDropped - } - defer release(1) - - if h.side != core.ClientSide { - return nil, nil, errors.New("only handshakers created using NewClientHandshaker can perform a client handshaker") - } - - // Create target identities from service account list. - targetIdentities := make([]*altspb.Identity, 0, len(h.clientOpts.TargetServiceAccounts)) - for _, account := range h.clientOpts.TargetServiceAccounts { - targetIdentities = append(targetIdentities, &altspb.Identity{ - IdentityOneof: &altspb.Identity_ServiceAccount{ - ServiceAccount: account, - }, - }) - } - req := &altspb.HandshakerReq{ - ReqOneof: &altspb.HandshakerReq_ClientStart{ - ClientStart: &altspb.StartClientHandshakeReq{ - HandshakeSecurityProtocol: hsProtocol, - ApplicationProtocols: appProtocols, - RecordProtocols: recordProtocols, - TargetIdentities: targetIdentities, - LocalIdentity: h.clientOpts.ClientIdentity, - TargetName: h.clientOpts.TargetName, - RpcVersions: h.clientOpts.RPCVersions, - }, - }, - } - - conn, result, err := h.doHandshake(req) - if err != nil { - return nil, nil, err - } - authInfo := authinfo.New(result) - return conn, authInfo, nil -} - -// ServerHandshake starts and completes a server ALTS handshaking for GCP. Once -// done, ServerHandshake returns a secure connection. -func (h *altsHandshaker) ServerHandshake(ctx context.Context) (net.Conn, credentials.AuthInfo, error) { - if !acquire(1) { - return nil, nil, errDropped - } - defer release(1) - - if h.side != core.ServerSide { - return nil, nil, errors.New("only handshakers created using NewServerHandshaker can perform a server handshaker") - } - - p := make([]byte, frameLimit) - n, err := h.conn.Read(p) - if err != nil { - return nil, nil, err - } - - // Prepare server parameters. - // TODO: currently only ALTS parameters are provided. Might need to use - // more options in the future. - params := make(map[int32]*altspb.ServerHandshakeParameters) - params[int32(altspb.HandshakeProtocol_ALTS)] = &altspb.ServerHandshakeParameters{ - RecordProtocols: recordProtocols, - } - req := &altspb.HandshakerReq{ - ReqOneof: &altspb.HandshakerReq_ServerStart{ - ServerStart: &altspb.StartServerHandshakeReq{ - ApplicationProtocols: appProtocols, - HandshakeParameters: params, - InBytes: p[:n], - RpcVersions: h.serverOpts.RPCVersions, - }, - }, - } - - conn, result, err := h.doHandshake(req) - if err != nil { - return nil, nil, err - } - authInfo := authinfo.New(result) - return conn, authInfo, nil -} - -func (h *altsHandshaker) doHandshake(req *altspb.HandshakerReq) (net.Conn, *altspb.HandshakerResult, error) { - resp, err := h.accessHandshakerService(req) - if err != nil { - return nil, nil, err - } - // Check of the returned status is an error. - if resp.GetStatus() != nil { - if got, want := resp.GetStatus().Code, uint32(codes.OK); got != want { - return nil, nil, fmt.Errorf("%v", resp.GetStatus().Details) - } - } - - var extra []byte - if req.GetServerStart() != nil { - extra = req.GetServerStart().GetInBytes()[resp.GetBytesConsumed():] - } - result, extra, err := h.processUntilDone(resp, extra) - if err != nil { - return nil, nil, err - } - // The handshaker returns a 128 bytes key. It should be truncated based - // on the returned record protocol. - keyLen, ok := keyLength[result.RecordProtocol] - if !ok { - return nil, nil, fmt.Errorf("unknown resulted record protocol %v", result.RecordProtocol) - } - sc, err := conn.NewConn(h.conn, h.side, result.GetRecordProtocol(), result.KeyData[:keyLen], extra) - if err != nil { - return nil, nil, err - } - return sc, result, nil -} - -func (h *altsHandshaker) accessHandshakerService(req *altspb.HandshakerReq) (*altspb.HandshakerResp, error) { - if err := h.stream.Send(req); err != nil { - return nil, err - } - resp, err := h.stream.Recv() - if err != nil { - return nil, err - } - return resp, nil -} - -// processUntilDone processes the handshake until the handshaker service returns -// the results. Handshaker service takes care of frame parsing, so we read -// whatever received from the network and send it to the handshaker service. -func (h *altsHandshaker) processUntilDone(resp *altspb.HandshakerResp, extra []byte) (*altspb.HandshakerResult, []byte, error) { - for { - if len(resp.OutFrames) > 0 { - if _, err := h.conn.Write(resp.OutFrames); err != nil { - return nil, nil, err - } - } - if resp.Result != nil { - return resp.Result, extra, nil - } - buf := make([]byte, frameLimit) - n, err := h.conn.Read(buf) - if err != nil && err != io.EOF { - return nil, nil, err - } - // If there is nothing to send to the handshaker service, and - // nothing is received from the peer, then we are stuck. - // This covers the case when the peer is not responding. Note - // that handshaker service connection issues are caught in - // accessHandshakerService before we even get here. - if len(resp.OutFrames) == 0 && n == 0 { - return nil, nil, core.PeerNotRespondingError - } - // Append extra bytes from the previous interaction with the - // handshaker service with the current buffer read from conn. - p := append(extra, buf[:n]...) - resp, err = h.accessHandshakerService(&altspb.HandshakerReq{ - ReqOneof: &altspb.HandshakerReq_Next{ - Next: &altspb.NextHandshakeMessageReq{ - InBytes: p, - }, - }, - }) - if err != nil { - return nil, nil, err - } - // Set extra based on handshaker service response. - if n == 0 { - extra = nil - } else { - extra = buf[resp.GetBytesConsumed():n] - } - } -} - -// Close terminates the Handshaker. It should be called when the caller obtains -// the secure connection. -func (h *altsHandshaker) Close() { - h.stream.CloseSend() -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker_test.go b/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker_test.go deleted file mode 100755 index 322fcb4..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/handshaker_test.go +++ /dev/null @@ -1,261 +0,0 @@ -/* - * - * 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. - * - */ - -package handshaker - -import ( - "bytes" - "testing" - "time" - - "golang.org/x/net/context" - grpc "google.golang.org/grpc" - "google.golang.org/grpc/credentials/alts/core" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - "google.golang.org/grpc/credentials/alts/core/testutil" -) - -var ( - testAppProtocols = []string{"grpc"} - testRecordProtocol = rekeyRecordProtocolName - testKey = []byte{ - // 44 arbitrary bytes. - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xd2, 0x4c, 0xce, 0x4f, 0x49, - 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xd2, 0x4c, 0xce, 0x4f, 0x49, 0x1f, 0x8b, - 0xd2, 0x4c, 0xce, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, - } - testServiceAccount = "test_service_account" - testTargetServiceAccounts = []string{testServiceAccount} - testClientIdentity = &altspb.Identity{ - IdentityOneof: &altspb.Identity_Hostname{ - Hostname: "i_am_a_client", - }, - } -) - -// testRPCStream mimics a altspb.HandshakerService_DoHandshakeClient object. -type testRPCStream struct { - grpc.ClientStream - t *testing.T - isClient bool - // The resp expected to be returned by Recv(). Make sure this is set to - // the content the test requires before Recv() is invoked. - recvBuf *altspb.HandshakerResp - // false if it is the first access to Handshaker service on Envelope. - first bool - // useful for testing concurrent calls. - delay time.Duration -} - -func (t *testRPCStream) Recv() (*altspb.HandshakerResp, error) { - resp := t.recvBuf - t.recvBuf = nil - return resp, nil -} - -func (t *testRPCStream) Send(req *altspb.HandshakerReq) error { - var resp *altspb.HandshakerResp - if !t.first { - // Generate the bytes to be returned by Recv() for the initial - // handshaking. - t.first = true - if t.isClient { - resp = &altspb.HandshakerResp{ - OutFrames: testutil.MakeFrame("ClientInit"), - // Simulate consuming ServerInit. - BytesConsumed: 14, - } - } else { - resp = &altspb.HandshakerResp{ - OutFrames: testutil.MakeFrame("ServerInit"), - // Simulate consuming ClientInit. - BytesConsumed: 14, - } - } - } else { - // Add delay to test concurrent calls. - close := stat.Update() - defer close() - time.Sleep(t.delay) - - // Generate the response to be returned by Recv() for the - // follow-up handshaking. - result := &altspb.HandshakerResult{ - RecordProtocol: testRecordProtocol, - KeyData: testKey, - } - resp = &altspb.HandshakerResp{ - Result: result, - // Simulate consuming ClientFinished or ServerFinished. - BytesConsumed: 18, - } - } - t.recvBuf = resp - return nil -} - -func (t *testRPCStream) CloseSend() error { - return nil -} - -var stat testutil.Stats - -func TestClientHandshake(t *testing.T) { - for _, testCase := range []struct { - delay time.Duration - numberOfHandshakes int - }{ - {0 * time.Millisecond, 1}, - {100 * time.Millisecond, 10 * maxPendingHandshakes}, - } { - errc := make(chan error) - stat.Reset() - for i := 0; i < testCase.numberOfHandshakes; i++ { - stream := &testRPCStream{ - t: t, - isClient: true, - } - // Preload the inbound frames. - f1 := testutil.MakeFrame("ServerInit") - f2 := testutil.MakeFrame("ServerFinished") - in := bytes.NewBuffer(f1) - in.Write(f2) - out := new(bytes.Buffer) - tc := testutil.NewTestConn(in, out) - chs := &altsHandshaker{ - stream: stream, - conn: tc, - clientOpts: &ClientHandshakerOptions{ - TargetServiceAccounts: testTargetServiceAccounts, - ClientIdentity: testClientIdentity, - }, - side: core.ClientSide, - } - go func() { - _, context, err := chs.ClientHandshake(context.Background()) - if err == nil && context == nil { - panic("expected non-nil ALTS context") - } - errc <- err - chs.Close() - }() - } - - // Ensure all errors are expected. - for i := 0; i < testCase.numberOfHandshakes; i++ { - if err := <-errc; err != nil && err != errDropped { - t.Errorf("ClientHandshake() = _, %v, want _, or %v", err, errDropped) - } - } - - // Ensure that there are no concurrent calls more than the limit. - if stat.MaxConcurrentCalls > maxPendingHandshakes { - t.Errorf("Observed %d concurrent handshakes; want <= %d", stat.MaxConcurrentCalls, maxPendingHandshakes) - } - } -} - -func TestServerHandshake(t *testing.T) { - for _, testCase := range []struct { - delay time.Duration - numberOfHandshakes int - }{ - {0 * time.Millisecond, 1}, - {100 * time.Millisecond, 10 * maxPendingHandshakes}, - } { - errc := make(chan error) - stat.Reset() - for i := 0; i < testCase.numberOfHandshakes; i++ { - stream := &testRPCStream{ - t: t, - isClient: false, - } - // Preload the inbound frames. - f1 := testutil.MakeFrame("ClientInit") - f2 := testutil.MakeFrame("ClientFinished") - in := bytes.NewBuffer(f1) - in.Write(f2) - out := new(bytes.Buffer) - tc := testutil.NewTestConn(in, out) - shs := &altsHandshaker{ - stream: stream, - conn: tc, - serverOpts: DefaultServerHandshakerOptions(), - side: core.ServerSide, - } - go func() { - _, context, err := shs.ServerHandshake(context.Background()) - if err == nil && context == nil { - panic("expected non-nil ALTS context") - } - errc <- err - shs.Close() - }() - } - - // Ensure all errors are expected. - for i := 0; i < testCase.numberOfHandshakes; i++ { - if err := <-errc; err != nil && err != errDropped { - t.Errorf("ServerHandshake() = _, %v, want _, or %v", err, errDropped) - } - } - - // Ensure that there are no concurrent calls more than the limit. - if stat.MaxConcurrentCalls > maxPendingHandshakes { - t.Errorf("Observed %d concurrent handshakes; want <= %d", stat.MaxConcurrentCalls, maxPendingHandshakes) - } - } -} - -// testUnresponsiveRPCStream is used for testing the PeerNotResponding case. -type testUnresponsiveRPCStream struct { - grpc.ClientStream -} - -func (t *testUnresponsiveRPCStream) Recv() (*altspb.HandshakerResp, error) { - return &altspb.HandshakerResp{}, nil -} - -func (t *testUnresponsiveRPCStream) Send(req *altspb.HandshakerReq) error { - return nil -} - -func (t *testUnresponsiveRPCStream) CloseSend() error { - return nil -} - -func TestPeerNotResponding(t *testing.T) { - stream := &testUnresponsiveRPCStream{} - chs := &altsHandshaker{ - stream: stream, - conn: testutil.NewUnresponsiveTestConn(), - clientOpts: &ClientHandshakerOptions{ - TargetServiceAccounts: testTargetServiceAccounts, - ClientIdentity: testClientIdentity, - }, - side: core.ClientSide, - } - _, context, err := chs.ClientHandshake(context.Background()) - chs.Close() - if context != nil { - t.Error("expected non-nil ALTS context") - } - if got, want := err, core.PeerNotRespondingError; got != want { - t.Errorf("ClientHandshake() = %v, want %v", got, want) - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service.go b/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service.go deleted file mode 100755 index b09fdae..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * 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. - * - */ - -// Package service manages connections between the VM application and the ALTS -// handshaker service. -package service - -import ( - "sync" - - grpc "google.golang.org/grpc" -) - -var ( - // hsConn represents a connection to hypervisor handshaker service. - hsConn *grpc.ClientConn - mu sync.Mutex - // hsDialer will be reassigned in tests. - hsDialer = grpc.Dial -) - -type dialer func(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) - -// Dial dials the handshake service in the hypervisor. If a connection has -// already been established, this function returns it. Otherwise, a new -// connection is created. -func Dial(hsAddress string) (*grpc.ClientConn, error) { - mu.Lock() - defer mu.Unlock() - - if hsConn == nil { - // Create a new connection to the handshaker service. Note that - // this connection stays open until the application is closed. - var err error - hsConn, err = hsDialer(hsAddress, grpc.WithInsecure()) - if err != nil { - return nil, err - } - } - return hsConn, nil -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service_test.go b/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service_test.go deleted file mode 100755 index 98160bf..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/handshaker/service/service_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * 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. - * - */ - -package service - -import ( - "testing" - - grpc "google.golang.org/grpc" -) - -const ( - // The address is irrelevant in this test. - testAddress = "some_address" -) - -func TestDial(t *testing.T) { - defer func() func() { - temp := hsDialer - hsDialer = func(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { - return &grpc.ClientConn{}, nil - } - return func() { - hsDialer = temp - } - }() - - // Ensure that hsConn is nil at first. - hsConn = nil - - // First call to Dial, it should create set hsConn. - conn1, err := Dial(testAddress) - if err != nil { - t.Fatalf("first call to Dial failed: %v", err) - } - if conn1 == nil { - t.Fatal("first call to Dial(_)=(nil, _), want not nil") - } - if got, want := hsConn, conn1; got != want { - t.Fatalf("hsConn=%v, want %v", got, want) - } - - // Second call to Dial should return conn1 above. - conn2, err := Dial(testAddress) - if err != nil { - t.Fatalf("second call to Dial(_) failed: %v", err) - } - if got, want := conn2, conn1; got != want { - t.Fatalf("second call to Dial(_)=(%v, _), want (%v,. _)", got, want) - } - if got, want := hsConn, conn1; got != want { - t.Fatalf("hsConn=%v, want %v", got, want) - } -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/altscontext.pb.go b/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/altscontext.pb.go deleted file mode 100755 index cd4fe79..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/altscontext.pb.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/gcp/altscontext.proto - -package grpc_gcp // import "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type AltsContext struct { - // The application protocol negotiated for this connection. - ApplicationProtocol string `protobuf:"bytes,1,opt,name=application_protocol,json=applicationProtocol,proto3" json:"application_protocol,omitempty"` - // The record protocol negotiated for this connection. - RecordProtocol string `protobuf:"bytes,2,opt,name=record_protocol,json=recordProtocol,proto3" json:"record_protocol,omitempty"` - // The security level of the created secure channel. - SecurityLevel SecurityLevel `protobuf:"varint,3,opt,name=security_level,json=securityLevel,proto3,enum=grpc.gcp.SecurityLevel" json:"security_level,omitempty"` - // The peer service account. - PeerServiceAccount string `protobuf:"bytes,4,opt,name=peer_service_account,json=peerServiceAccount,proto3" json:"peer_service_account,omitempty"` - // The local service account. - LocalServiceAccount string `protobuf:"bytes,5,opt,name=local_service_account,json=localServiceAccount,proto3" json:"local_service_account,omitempty"` - // The RPC protocol versions supported by the peer. - PeerRpcVersions *RpcProtocolVersions `protobuf:"bytes,6,opt,name=peer_rpc_versions,json=peerRpcVersions,proto3" json:"peer_rpc_versions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AltsContext) Reset() { *m = AltsContext{} } -func (m *AltsContext) String() string { return proto.CompactTextString(m) } -func (*AltsContext) ProtoMessage() {} -func (*AltsContext) Descriptor() ([]byte, []int) { - return fileDescriptor_altscontext_2f63c0ac7e856743, []int{0} -} -func (m *AltsContext) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AltsContext.Unmarshal(m, b) -} -func (m *AltsContext) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AltsContext.Marshal(b, m, deterministic) -} -func (dst *AltsContext) XXX_Merge(src proto.Message) { - xxx_messageInfo_AltsContext.Merge(dst, src) -} -func (m *AltsContext) XXX_Size() int { - return xxx_messageInfo_AltsContext.Size(m) -} -func (m *AltsContext) XXX_DiscardUnknown() { - xxx_messageInfo_AltsContext.DiscardUnknown(m) -} - -var xxx_messageInfo_AltsContext proto.InternalMessageInfo - -func (m *AltsContext) GetApplicationProtocol() string { - if m != nil { - return m.ApplicationProtocol - } - return "" -} - -func (m *AltsContext) GetRecordProtocol() string { - if m != nil { - return m.RecordProtocol - } - return "" -} - -func (m *AltsContext) GetSecurityLevel() SecurityLevel { - if m != nil { - return m.SecurityLevel - } - return SecurityLevel_SECURITY_NONE -} - -func (m *AltsContext) GetPeerServiceAccount() string { - if m != nil { - return m.PeerServiceAccount - } - return "" -} - -func (m *AltsContext) GetLocalServiceAccount() string { - if m != nil { - return m.LocalServiceAccount - } - return "" -} - -func (m *AltsContext) GetPeerRpcVersions() *RpcProtocolVersions { - if m != nil { - return m.PeerRpcVersions - } - return nil -} - -func init() { - proto.RegisterType((*AltsContext)(nil), "grpc.gcp.AltsContext") -} - -func init() { - proto.RegisterFile("grpc/gcp/altscontext.proto", fileDescriptor_altscontext_2f63c0ac7e856743) -} - -var fileDescriptor_altscontext_2f63c0ac7e856743 = []byte{ - // 338 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x91, 0x4d, 0x4b, 0x23, 0x41, - 0x10, 0x86, 0x99, 0xec, 0x6e, 0xd8, 0xed, 0xb0, 0xc9, 0xee, 0x6c, 0xc2, 0x0e, 0x01, 0x21, 0x78, - 0x71, 0x4e, 0x33, 0x1a, 0x8f, 0x82, 0x90, 0x78, 0x12, 0x3c, 0x84, 0x09, 0x78, 0xf0, 0x32, 0xb4, - 0x95, 0xa2, 0x6d, 0xe8, 0x74, 0x35, 0xd5, 0x9d, 0xa0, 0x7f, 0xd5, 0x5f, 0x23, 0xd3, 0x93, 0x2f, - 0xf4, 0x58, 0xf5, 0xbc, 0x6f, 0x7d, 0x8a, 0xb1, 0x62, 0x07, 0xa5, 0x02, 0x57, 0x4a, 0x13, 0x3c, - 0x90, 0x0d, 0xf8, 0x1a, 0x0a, 0xc7, 0x14, 0x28, 0xfd, 0xd9, 0xb0, 0x42, 0x81, 0x1b, 0xe7, 0x07, - 0x55, 0x60, 0x69, 0xbd, 0x23, 0x0e, 0xb5, 0x47, 0xd8, 0xb0, 0x0e, 0x6f, 0x35, 0xd0, 0x7a, 0x4d, - 0xb6, 0xf5, 0x9c, 0xbf, 0x77, 0x44, 0x6f, 0x66, 0x82, 0xbf, 0x6b, 0x2b, 0xa5, 0x57, 0x62, 0x28, - 0x9d, 0x33, 0x1a, 0x64, 0xd0, 0x64, 0xeb, 0x28, 0x02, 0x32, 0x59, 0x32, 0x49, 0xf2, 0x5f, 0xd5, - 0xbf, 0x13, 0xb6, 0xd8, 0xa1, 0xf4, 0x42, 0x0c, 0x18, 0x81, 0x78, 0x75, 0x54, 0x77, 0xa2, 0xba, - 0xdf, 0xa6, 0x0f, 0xc2, 0x5b, 0xd1, 0x3f, 0x0c, 0x61, 0x70, 0x8b, 0x26, 0xfb, 0x36, 0x49, 0xf2, - 0xfe, 0xf4, 0x7f, 0xb1, 0x1f, 0xbc, 0x58, 0xee, 0xf8, 0x43, 0x83, 0xab, 0xdf, 0xfe, 0x34, 0x4c, - 0x2f, 0xc5, 0xd0, 0x21, 0x72, 0xed, 0x91, 0xb7, 0x1a, 0xb0, 0x96, 0x00, 0xb4, 0xb1, 0x21, 0xfb, - 0x1e, 0xbb, 0xa5, 0x0d, 0x5b, 0xb6, 0x68, 0xd6, 0x92, 0x74, 0x2a, 0x46, 0x86, 0x40, 0x9a, 0x2f, - 0x96, 0x1f, 0xed, 0x3a, 0x11, 0x7e, 0xf2, 0xdc, 0x8b, 0xbf, 0xb1, 0x0b, 0x3b, 0xa8, 0xb7, 0xc8, - 0x5e, 0x93, 0xf5, 0x59, 0x77, 0x92, 0xe4, 0xbd, 0xe9, 0xd9, 0x71, 0xd0, 0xca, 0xc1, 0x7e, 0xaf, - 0xc7, 0x9d, 0xa8, 0x1a, 0x34, 0xbe, 0xca, 0xc1, 0x3e, 0x31, 0x7f, 0x11, 0x23, 0x4d, 0xad, 0xa7, - 0xf9, 0x56, 0xa1, 0x6d, 0x40, 0xb6, 0xd2, 0xcc, 0xff, 0x9c, 0x9c, 0x3c, 0x96, 0x59, 0x24, 0x4f, - 0x37, 0x8a, 0x48, 0x19, 0x2c, 0x14, 0x19, 0x69, 0x55, 0x41, 0xac, 0xca, 0xf8, 0x45, 0x60, 0x5c, - 0xa1, 0x0d, 0x5a, 0x1a, 0x1f, 0x7f, 0x5e, 0x02, 0x31, 0x96, 0xf1, 0xd4, 0x51, 0x50, 0x2b, 0x70, - 0xcf, 0xdd, 0x18, 0x5f, 0x7f, 0x04, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x41, 0xe3, 0x52, 0x1f, 0x02, - 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/handshaker.pb.go b/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/handshaker.pb.go deleted file mode 100755 index 01e8719..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/handshaker.pb.go +++ /dev/null @@ -1,1178 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/gcp/handshaker.proto - -package grpc_gcp // import "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type HandshakeProtocol int32 - -const ( - // Default value. - HandshakeProtocol_HANDSHAKE_PROTOCOL_UNSPECIFIED HandshakeProtocol = 0 - // TLS handshake protocol. - HandshakeProtocol_TLS HandshakeProtocol = 1 - // Application Layer Transport Security handshake protocol. - HandshakeProtocol_ALTS HandshakeProtocol = 2 -) - -var HandshakeProtocol_name = map[int32]string{ - 0: "HANDSHAKE_PROTOCOL_UNSPECIFIED", - 1: "TLS", - 2: "ALTS", -} -var HandshakeProtocol_value = map[string]int32{ - "HANDSHAKE_PROTOCOL_UNSPECIFIED": 0, - "TLS": 1, - "ALTS": 2, -} - -func (x HandshakeProtocol) String() string { - return proto.EnumName(HandshakeProtocol_name, int32(x)) -} -func (HandshakeProtocol) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{0} -} - -type NetworkProtocol int32 - -const ( - NetworkProtocol_NETWORK_PROTOCOL_UNSPECIFIED NetworkProtocol = 0 - NetworkProtocol_TCP NetworkProtocol = 1 - NetworkProtocol_UDP NetworkProtocol = 2 -) - -var NetworkProtocol_name = map[int32]string{ - 0: "NETWORK_PROTOCOL_UNSPECIFIED", - 1: "TCP", - 2: "UDP", -} -var NetworkProtocol_value = map[string]int32{ - "NETWORK_PROTOCOL_UNSPECIFIED": 0, - "TCP": 1, - "UDP": 2, -} - -func (x NetworkProtocol) String() string { - return proto.EnumName(NetworkProtocol_name, int32(x)) -} -func (NetworkProtocol) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{1} -} - -type Endpoint struct { - // IP address. It should contain an IPv4 or IPv6 string literal, e.g. - // "192.168.0.1" or "2001:db8::1". - IpAddress string `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // Port number. - Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` - // Network protocol (e.g., TCP, UDP) associated with this endpoint. - Protocol NetworkProtocol `protobuf:"varint,3,opt,name=protocol,proto3,enum=grpc.gcp.NetworkProtocol" json:"protocol,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Endpoint) Reset() { *m = Endpoint{} } -func (m *Endpoint) String() string { return proto.CompactTextString(m) } -func (*Endpoint) ProtoMessage() {} -func (*Endpoint) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{0} -} -func (m *Endpoint) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Endpoint.Unmarshal(m, b) -} -func (m *Endpoint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Endpoint.Marshal(b, m, deterministic) -} -func (dst *Endpoint) XXX_Merge(src proto.Message) { - xxx_messageInfo_Endpoint.Merge(dst, src) -} -func (m *Endpoint) XXX_Size() int { - return xxx_messageInfo_Endpoint.Size(m) -} -func (m *Endpoint) XXX_DiscardUnknown() { - xxx_messageInfo_Endpoint.DiscardUnknown(m) -} - -var xxx_messageInfo_Endpoint proto.InternalMessageInfo - -func (m *Endpoint) GetIpAddress() string { - if m != nil { - return m.IpAddress - } - return "" -} - -func (m *Endpoint) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Endpoint) GetProtocol() NetworkProtocol { - if m != nil { - return m.Protocol - } - return NetworkProtocol_NETWORK_PROTOCOL_UNSPECIFIED -} - -type Identity struct { - // Types that are valid to be assigned to IdentityOneof: - // *Identity_ServiceAccount - // *Identity_Hostname - IdentityOneof isIdentity_IdentityOneof `protobuf_oneof:"identity_oneof"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Identity) Reset() { *m = Identity{} } -func (m *Identity) String() string { return proto.CompactTextString(m) } -func (*Identity) ProtoMessage() {} -func (*Identity) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{1} -} -func (m *Identity) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Identity.Unmarshal(m, b) -} -func (m *Identity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Identity.Marshal(b, m, deterministic) -} -func (dst *Identity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Identity.Merge(dst, src) -} -func (m *Identity) XXX_Size() int { - return xxx_messageInfo_Identity.Size(m) -} -func (m *Identity) XXX_DiscardUnknown() { - xxx_messageInfo_Identity.DiscardUnknown(m) -} - -var xxx_messageInfo_Identity proto.InternalMessageInfo - -type isIdentity_IdentityOneof interface { - isIdentity_IdentityOneof() -} - -type Identity_ServiceAccount struct { - ServiceAccount string `protobuf:"bytes,1,opt,name=service_account,json=serviceAccount,proto3,oneof"` -} -type Identity_Hostname struct { - Hostname string `protobuf:"bytes,2,opt,name=hostname,proto3,oneof"` -} - -func (*Identity_ServiceAccount) isIdentity_IdentityOneof() {} -func (*Identity_Hostname) isIdentity_IdentityOneof() {} - -func (m *Identity) GetIdentityOneof() isIdentity_IdentityOneof { - if m != nil { - return m.IdentityOneof - } - return nil -} - -func (m *Identity) GetServiceAccount() string { - if x, ok := m.GetIdentityOneof().(*Identity_ServiceAccount); ok { - return x.ServiceAccount - } - return "" -} - -func (m *Identity) GetHostname() string { - if x, ok := m.GetIdentityOneof().(*Identity_Hostname); ok { - return x.Hostname - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*Identity) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _Identity_OneofMarshaler, _Identity_OneofUnmarshaler, _Identity_OneofSizer, []interface{}{ - (*Identity_ServiceAccount)(nil), - (*Identity_Hostname)(nil), - } -} - -func _Identity_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*Identity) - // identity_oneof - switch x := m.IdentityOneof.(type) { - case *Identity_ServiceAccount: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ServiceAccount) - case *Identity_Hostname: - b.EncodeVarint(2<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Hostname) - case nil: - default: - return fmt.Errorf("Identity.IdentityOneof has unexpected type %T", x) - } - return nil -} - -func _Identity_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*Identity) - switch tag { - case 1: // identity_oneof.service_account - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.IdentityOneof = &Identity_ServiceAccount{x} - return true, err - case 2: // identity_oneof.hostname - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.IdentityOneof = &Identity_Hostname{x} - return true, err - default: - return false, nil - } -} - -func _Identity_OneofSizer(msg proto.Message) (n int) { - m := msg.(*Identity) - // identity_oneof - switch x := m.IdentityOneof.(type) { - case *Identity_ServiceAccount: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ServiceAccount))) - n += len(x.ServiceAccount) - case *Identity_Hostname: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.Hostname))) - n += len(x.Hostname) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type StartClientHandshakeReq struct { - // Handshake security protocol requested by the client. - HandshakeSecurityProtocol HandshakeProtocol `protobuf:"varint,1,opt,name=handshake_security_protocol,json=handshakeSecurityProtocol,proto3,enum=grpc.gcp.HandshakeProtocol" json:"handshake_security_protocol,omitempty"` - // The application protocols supported by the client, e.g., "h2" (for http2), - // "grpc". - ApplicationProtocols []string `protobuf:"bytes,2,rep,name=application_protocols,json=applicationProtocols,proto3" json:"application_protocols,omitempty"` - // The record protocols supported by the client, e.g., - // "ALTSRP_GCM_AES128". - RecordProtocols []string `protobuf:"bytes,3,rep,name=record_protocols,json=recordProtocols,proto3" json:"record_protocols,omitempty"` - // (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. - TargetIdentities []*Identity `protobuf:"bytes,4,rep,name=target_identities,json=targetIdentities,proto3" json:"target_identities,omitempty"` - // (Optional) Application may specify a local identity. Otherwise, the - // handshaker chooses a default local identity. - LocalIdentity *Identity `protobuf:"bytes,5,opt,name=local_identity,json=localIdentity,proto3" json:"local_identity,omitempty"` - // (Optional) Local endpoint information of the connection to the server, - // such as local IP address, port number, and network protocol. - LocalEndpoint *Endpoint `protobuf:"bytes,6,opt,name=local_endpoint,json=localEndpoint,proto3" json:"local_endpoint,omitempty"` - // (Optional) Endpoint information of the remote server, such as IP address, - // port number, and network protocol. - RemoteEndpoint *Endpoint `protobuf:"bytes,7,opt,name=remote_endpoint,json=remoteEndpoint,proto3" json:"remote_endpoint,omitempty"` - // (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. - TargetName string `protobuf:"bytes,8,opt,name=target_name,json=targetName,proto3" json:"target_name,omitempty"` - // (Optional) RPC protocol versions supported by the client. - RpcVersions *RpcProtocolVersions `protobuf:"bytes,9,opt,name=rpc_versions,json=rpcVersions,proto3" json:"rpc_versions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StartClientHandshakeReq) Reset() { *m = StartClientHandshakeReq{} } -func (m *StartClientHandshakeReq) String() string { return proto.CompactTextString(m) } -func (*StartClientHandshakeReq) ProtoMessage() {} -func (*StartClientHandshakeReq) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{2} -} -func (m *StartClientHandshakeReq) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StartClientHandshakeReq.Unmarshal(m, b) -} -func (m *StartClientHandshakeReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StartClientHandshakeReq.Marshal(b, m, deterministic) -} -func (dst *StartClientHandshakeReq) XXX_Merge(src proto.Message) { - xxx_messageInfo_StartClientHandshakeReq.Merge(dst, src) -} -func (m *StartClientHandshakeReq) XXX_Size() int { - return xxx_messageInfo_StartClientHandshakeReq.Size(m) -} -func (m *StartClientHandshakeReq) XXX_DiscardUnknown() { - xxx_messageInfo_StartClientHandshakeReq.DiscardUnknown(m) -} - -var xxx_messageInfo_StartClientHandshakeReq proto.InternalMessageInfo - -func (m *StartClientHandshakeReq) GetHandshakeSecurityProtocol() HandshakeProtocol { - if m != nil { - return m.HandshakeSecurityProtocol - } - return HandshakeProtocol_HANDSHAKE_PROTOCOL_UNSPECIFIED -} - -func (m *StartClientHandshakeReq) GetApplicationProtocols() []string { - if m != nil { - return m.ApplicationProtocols - } - return nil -} - -func (m *StartClientHandshakeReq) GetRecordProtocols() []string { - if m != nil { - return m.RecordProtocols - } - return nil -} - -func (m *StartClientHandshakeReq) GetTargetIdentities() []*Identity { - if m != nil { - return m.TargetIdentities - } - return nil -} - -func (m *StartClientHandshakeReq) GetLocalIdentity() *Identity { - if m != nil { - return m.LocalIdentity - } - return nil -} - -func (m *StartClientHandshakeReq) GetLocalEndpoint() *Endpoint { - if m != nil { - return m.LocalEndpoint - } - return nil -} - -func (m *StartClientHandshakeReq) GetRemoteEndpoint() *Endpoint { - if m != nil { - return m.RemoteEndpoint - } - return nil -} - -func (m *StartClientHandshakeReq) GetTargetName() string { - if m != nil { - return m.TargetName - } - return "" -} - -func (m *StartClientHandshakeReq) GetRpcVersions() *RpcProtocolVersions { - if m != nil { - return m.RpcVersions - } - return nil -} - -type ServerHandshakeParameters struct { - // The record protocols supported by the server, e.g., - // "ALTSRP_GCM_AES128". - RecordProtocols []string `protobuf:"bytes,1,rep,name=record_protocols,json=recordProtocols,proto3" json:"record_protocols,omitempty"` - // (Optional) A list of local identities supported by the server, if - // specified. Otherwise, the handshaker chooses a default local identity. - LocalIdentities []*Identity `protobuf:"bytes,2,rep,name=local_identities,json=localIdentities,proto3" json:"local_identities,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerHandshakeParameters) Reset() { *m = ServerHandshakeParameters{} } -func (m *ServerHandshakeParameters) String() string { return proto.CompactTextString(m) } -func (*ServerHandshakeParameters) ProtoMessage() {} -func (*ServerHandshakeParameters) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{3} -} -func (m *ServerHandshakeParameters) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerHandshakeParameters.Unmarshal(m, b) -} -func (m *ServerHandshakeParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerHandshakeParameters.Marshal(b, m, deterministic) -} -func (dst *ServerHandshakeParameters) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerHandshakeParameters.Merge(dst, src) -} -func (m *ServerHandshakeParameters) XXX_Size() int { - return xxx_messageInfo_ServerHandshakeParameters.Size(m) -} -func (m *ServerHandshakeParameters) XXX_DiscardUnknown() { - xxx_messageInfo_ServerHandshakeParameters.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerHandshakeParameters proto.InternalMessageInfo - -func (m *ServerHandshakeParameters) GetRecordProtocols() []string { - if m != nil { - return m.RecordProtocols - } - return nil -} - -func (m *ServerHandshakeParameters) GetLocalIdentities() []*Identity { - if m != nil { - return m.LocalIdentities - } - return nil -} - -type StartServerHandshakeReq struct { - // The application protocols supported by the server, e.g., "h2" (for http2), - // "grpc". - ApplicationProtocols []string `protobuf:"bytes,1,rep,name=application_protocols,json=applicationProtocols,proto3" json:"application_protocols,omitempty"` - // 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. - HandshakeParameters map[int32]*ServerHandshakeParameters `protobuf:"bytes,2,rep,name=handshake_parameters,json=handshakeParameters,proto3" json:"handshake_parameters,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - // 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. - InBytes []byte `protobuf:"bytes,3,opt,name=in_bytes,json=inBytes,proto3" json:"in_bytes,omitempty"` - // (Optional) Local endpoint information of the connection to the client, - // such as local IP address, port number, and network protocol. - LocalEndpoint *Endpoint `protobuf:"bytes,4,opt,name=local_endpoint,json=localEndpoint,proto3" json:"local_endpoint,omitempty"` - // (Optional) Endpoint information of the remote client, such as IP address, - // port number, and network protocol. - RemoteEndpoint *Endpoint `protobuf:"bytes,5,opt,name=remote_endpoint,json=remoteEndpoint,proto3" json:"remote_endpoint,omitempty"` - // (Optional) RPC protocol versions supported by the server. - RpcVersions *RpcProtocolVersions `protobuf:"bytes,6,opt,name=rpc_versions,json=rpcVersions,proto3" json:"rpc_versions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StartServerHandshakeReq) Reset() { *m = StartServerHandshakeReq{} } -func (m *StartServerHandshakeReq) String() string { return proto.CompactTextString(m) } -func (*StartServerHandshakeReq) ProtoMessage() {} -func (*StartServerHandshakeReq) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{4} -} -func (m *StartServerHandshakeReq) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StartServerHandshakeReq.Unmarshal(m, b) -} -func (m *StartServerHandshakeReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StartServerHandshakeReq.Marshal(b, m, deterministic) -} -func (dst *StartServerHandshakeReq) XXX_Merge(src proto.Message) { - xxx_messageInfo_StartServerHandshakeReq.Merge(dst, src) -} -func (m *StartServerHandshakeReq) XXX_Size() int { - return xxx_messageInfo_StartServerHandshakeReq.Size(m) -} -func (m *StartServerHandshakeReq) XXX_DiscardUnknown() { - xxx_messageInfo_StartServerHandshakeReq.DiscardUnknown(m) -} - -var xxx_messageInfo_StartServerHandshakeReq proto.InternalMessageInfo - -func (m *StartServerHandshakeReq) GetApplicationProtocols() []string { - if m != nil { - return m.ApplicationProtocols - } - return nil -} - -func (m *StartServerHandshakeReq) GetHandshakeParameters() map[int32]*ServerHandshakeParameters { - if m != nil { - return m.HandshakeParameters - } - return nil -} - -func (m *StartServerHandshakeReq) GetInBytes() []byte { - if m != nil { - return m.InBytes - } - return nil -} - -func (m *StartServerHandshakeReq) GetLocalEndpoint() *Endpoint { - if m != nil { - return m.LocalEndpoint - } - return nil -} - -func (m *StartServerHandshakeReq) GetRemoteEndpoint() *Endpoint { - if m != nil { - return m.RemoteEndpoint - } - return nil -} - -func (m *StartServerHandshakeReq) GetRpcVersions() *RpcProtocolVersions { - if m != nil { - return m.RpcVersions - } - return nil -} - -type NextHandshakeMessageReq struct { - // 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. - InBytes []byte `protobuf:"bytes,1,opt,name=in_bytes,json=inBytes,proto3" json:"in_bytes,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NextHandshakeMessageReq) Reset() { *m = NextHandshakeMessageReq{} } -func (m *NextHandshakeMessageReq) String() string { return proto.CompactTextString(m) } -func (*NextHandshakeMessageReq) ProtoMessage() {} -func (*NextHandshakeMessageReq) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{5} -} -func (m *NextHandshakeMessageReq) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_NextHandshakeMessageReq.Unmarshal(m, b) -} -func (m *NextHandshakeMessageReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_NextHandshakeMessageReq.Marshal(b, m, deterministic) -} -func (dst *NextHandshakeMessageReq) XXX_Merge(src proto.Message) { - xxx_messageInfo_NextHandshakeMessageReq.Merge(dst, src) -} -func (m *NextHandshakeMessageReq) XXX_Size() int { - return xxx_messageInfo_NextHandshakeMessageReq.Size(m) -} -func (m *NextHandshakeMessageReq) XXX_DiscardUnknown() { - xxx_messageInfo_NextHandshakeMessageReq.DiscardUnknown(m) -} - -var xxx_messageInfo_NextHandshakeMessageReq proto.InternalMessageInfo - -func (m *NextHandshakeMessageReq) GetInBytes() []byte { - if m != nil { - return m.InBytes - } - return nil -} - -type HandshakerReq struct { - // Types that are valid to be assigned to ReqOneof: - // *HandshakerReq_ClientStart - // *HandshakerReq_ServerStart - // *HandshakerReq_Next - ReqOneof isHandshakerReq_ReqOneof `protobuf_oneof:"req_oneof"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandshakerReq) Reset() { *m = HandshakerReq{} } -func (m *HandshakerReq) String() string { return proto.CompactTextString(m) } -func (*HandshakerReq) ProtoMessage() {} -func (*HandshakerReq) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{6} -} -func (m *HandshakerReq) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandshakerReq.Unmarshal(m, b) -} -func (m *HandshakerReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandshakerReq.Marshal(b, m, deterministic) -} -func (dst *HandshakerReq) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandshakerReq.Merge(dst, src) -} -func (m *HandshakerReq) XXX_Size() int { - return xxx_messageInfo_HandshakerReq.Size(m) -} -func (m *HandshakerReq) XXX_DiscardUnknown() { - xxx_messageInfo_HandshakerReq.DiscardUnknown(m) -} - -var xxx_messageInfo_HandshakerReq proto.InternalMessageInfo - -type isHandshakerReq_ReqOneof interface { - isHandshakerReq_ReqOneof() -} - -type HandshakerReq_ClientStart struct { - ClientStart *StartClientHandshakeReq `protobuf:"bytes,1,opt,name=client_start,json=clientStart,proto3,oneof"` -} -type HandshakerReq_ServerStart struct { - ServerStart *StartServerHandshakeReq `protobuf:"bytes,2,opt,name=server_start,json=serverStart,proto3,oneof"` -} -type HandshakerReq_Next struct { - Next *NextHandshakeMessageReq `protobuf:"bytes,3,opt,name=next,proto3,oneof"` -} - -func (*HandshakerReq_ClientStart) isHandshakerReq_ReqOneof() {} -func (*HandshakerReq_ServerStart) isHandshakerReq_ReqOneof() {} -func (*HandshakerReq_Next) isHandshakerReq_ReqOneof() {} - -func (m *HandshakerReq) GetReqOneof() isHandshakerReq_ReqOneof { - if m != nil { - return m.ReqOneof - } - return nil -} - -func (m *HandshakerReq) GetClientStart() *StartClientHandshakeReq { - if x, ok := m.GetReqOneof().(*HandshakerReq_ClientStart); ok { - return x.ClientStart - } - return nil -} - -func (m *HandshakerReq) GetServerStart() *StartServerHandshakeReq { - if x, ok := m.GetReqOneof().(*HandshakerReq_ServerStart); ok { - return x.ServerStart - } - return nil -} - -func (m *HandshakerReq) GetNext() *NextHandshakeMessageReq { - if x, ok := m.GetReqOneof().(*HandshakerReq_Next); ok { - return x.Next - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*HandshakerReq) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _HandshakerReq_OneofMarshaler, _HandshakerReq_OneofUnmarshaler, _HandshakerReq_OneofSizer, []interface{}{ - (*HandshakerReq_ClientStart)(nil), - (*HandshakerReq_ServerStart)(nil), - (*HandshakerReq_Next)(nil), - } -} - -func _HandshakerReq_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*HandshakerReq) - // req_oneof - switch x := m.ReqOneof.(type) { - case *HandshakerReq_ClientStart: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientStart); err != nil { - return err - } - case *HandshakerReq_ServerStart: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerStart); err != nil { - return err - } - case *HandshakerReq_Next: - b.EncodeVarint(3<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Next); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("HandshakerReq.ReqOneof has unexpected type %T", x) - } - return nil -} - -func _HandshakerReq_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*HandshakerReq) - switch tag { - case 1: // req_oneof.client_start - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(StartClientHandshakeReq) - err := b.DecodeMessage(msg) - m.ReqOneof = &HandshakerReq_ClientStart{msg} - return true, err - case 2: // req_oneof.server_start - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(StartServerHandshakeReq) - err := b.DecodeMessage(msg) - m.ReqOneof = &HandshakerReq_ServerStart{msg} - return true, err - case 3: // req_oneof.next - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(NextHandshakeMessageReq) - err := b.DecodeMessage(msg) - m.ReqOneof = &HandshakerReq_Next{msg} - return true, err - default: - return false, nil - } -} - -func _HandshakerReq_OneofSizer(msg proto.Message) (n int) { - m := msg.(*HandshakerReq) - // req_oneof - switch x := m.ReqOneof.(type) { - case *HandshakerReq_ClientStart: - s := proto.Size(x.ClientStart) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *HandshakerReq_ServerStart: - s := proto.Size(x.ServerStart) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *HandshakerReq_Next: - s := proto.Size(x.Next) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type HandshakerResult struct { - // The application protocol negotiated for this connection. - ApplicationProtocol string `protobuf:"bytes,1,opt,name=application_protocol,json=applicationProtocol,proto3" json:"application_protocol,omitempty"` - // The record protocol negotiated for this connection. - RecordProtocol string `protobuf:"bytes,2,opt,name=record_protocol,json=recordProtocol,proto3" json:"record_protocol,omitempty"` - // 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. - KeyData []byte `protobuf:"bytes,3,opt,name=key_data,json=keyData,proto3" json:"key_data,omitempty"` - // The authenticated identity of the peer. - PeerIdentity *Identity `protobuf:"bytes,4,opt,name=peer_identity,json=peerIdentity,proto3" json:"peer_identity,omitempty"` - // The local identity used in the handshake. - LocalIdentity *Identity `protobuf:"bytes,5,opt,name=local_identity,json=localIdentity,proto3" json:"local_identity,omitempty"` - // 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. - KeepChannelOpen bool `protobuf:"varint,6,opt,name=keep_channel_open,json=keepChannelOpen,proto3" json:"keep_channel_open,omitempty"` - // The RPC protocol versions supported by the peer. - PeerRpcVersions *RpcProtocolVersions `protobuf:"bytes,7,opt,name=peer_rpc_versions,json=peerRpcVersions,proto3" json:"peer_rpc_versions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandshakerResult) Reset() { *m = HandshakerResult{} } -func (m *HandshakerResult) String() string { return proto.CompactTextString(m) } -func (*HandshakerResult) ProtoMessage() {} -func (*HandshakerResult) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{7} -} -func (m *HandshakerResult) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandshakerResult.Unmarshal(m, b) -} -func (m *HandshakerResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandshakerResult.Marshal(b, m, deterministic) -} -func (dst *HandshakerResult) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandshakerResult.Merge(dst, src) -} -func (m *HandshakerResult) XXX_Size() int { - return xxx_messageInfo_HandshakerResult.Size(m) -} -func (m *HandshakerResult) XXX_DiscardUnknown() { - xxx_messageInfo_HandshakerResult.DiscardUnknown(m) -} - -var xxx_messageInfo_HandshakerResult proto.InternalMessageInfo - -func (m *HandshakerResult) GetApplicationProtocol() string { - if m != nil { - return m.ApplicationProtocol - } - return "" -} - -func (m *HandshakerResult) GetRecordProtocol() string { - if m != nil { - return m.RecordProtocol - } - return "" -} - -func (m *HandshakerResult) GetKeyData() []byte { - if m != nil { - return m.KeyData - } - return nil -} - -func (m *HandshakerResult) GetPeerIdentity() *Identity { - if m != nil { - return m.PeerIdentity - } - return nil -} - -func (m *HandshakerResult) GetLocalIdentity() *Identity { - if m != nil { - return m.LocalIdentity - } - return nil -} - -func (m *HandshakerResult) GetKeepChannelOpen() bool { - if m != nil { - return m.KeepChannelOpen - } - return false -} - -func (m *HandshakerResult) GetPeerRpcVersions() *RpcProtocolVersions { - if m != nil { - return m.PeerRpcVersions - } - return nil -} - -type HandshakerStatus struct { - // The status code. This could be the gRPC status code. - Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` - // The status details. - Details string `protobuf:"bytes,2,opt,name=details,proto3" json:"details,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandshakerStatus) Reset() { *m = HandshakerStatus{} } -func (m *HandshakerStatus) String() string { return proto.CompactTextString(m) } -func (*HandshakerStatus) ProtoMessage() {} -func (*HandshakerStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{8} -} -func (m *HandshakerStatus) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandshakerStatus.Unmarshal(m, b) -} -func (m *HandshakerStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandshakerStatus.Marshal(b, m, deterministic) -} -func (dst *HandshakerStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandshakerStatus.Merge(dst, src) -} -func (m *HandshakerStatus) XXX_Size() int { - return xxx_messageInfo_HandshakerStatus.Size(m) -} -func (m *HandshakerStatus) XXX_DiscardUnknown() { - xxx_messageInfo_HandshakerStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_HandshakerStatus proto.InternalMessageInfo - -func (m *HandshakerStatus) GetCode() uint32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *HandshakerStatus) GetDetails() string { - if m != nil { - return m.Details - } - return "" -} - -type HandshakerResp struct { - // 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. - OutFrames []byte `protobuf:"bytes,1,opt,name=out_frames,json=outFrames,proto3" json:"out_frames,omitempty"` - // 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. - BytesConsumed uint32 `protobuf:"varint,2,opt,name=bytes_consumed,json=bytesConsumed,proto3" json:"bytes_consumed,omitempty"` - // This is set iff the handshake was successful. out_frames may still be set - // to frames that needs to be forwarded to the peer. - Result *HandshakerResult `protobuf:"bytes,3,opt,name=result,proto3" json:"result,omitempty"` - // Status of the handshaker. - Status *HandshakerStatus `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HandshakerResp) Reset() { *m = HandshakerResp{} } -func (m *HandshakerResp) String() string { return proto.CompactTextString(m) } -func (*HandshakerResp) ProtoMessage() {} -func (*HandshakerResp) Descriptor() ([]byte, []int) { - return fileDescriptor_handshaker_b28e45bdd1661054, []int{9} -} -func (m *HandshakerResp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HandshakerResp.Unmarshal(m, b) -} -func (m *HandshakerResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HandshakerResp.Marshal(b, m, deterministic) -} -func (dst *HandshakerResp) XXX_Merge(src proto.Message) { - xxx_messageInfo_HandshakerResp.Merge(dst, src) -} -func (m *HandshakerResp) XXX_Size() int { - return xxx_messageInfo_HandshakerResp.Size(m) -} -func (m *HandshakerResp) XXX_DiscardUnknown() { - xxx_messageInfo_HandshakerResp.DiscardUnknown(m) -} - -var xxx_messageInfo_HandshakerResp proto.InternalMessageInfo - -func (m *HandshakerResp) GetOutFrames() []byte { - if m != nil { - return m.OutFrames - } - return nil -} - -func (m *HandshakerResp) GetBytesConsumed() uint32 { - if m != nil { - return m.BytesConsumed - } - return 0 -} - -func (m *HandshakerResp) GetResult() *HandshakerResult { - if m != nil { - return m.Result - } - return nil -} - -func (m *HandshakerResp) GetStatus() *HandshakerStatus { - if m != nil { - return m.Status - } - return nil -} - -func init() { - proto.RegisterType((*Endpoint)(nil), "grpc.gcp.Endpoint") - proto.RegisterType((*Identity)(nil), "grpc.gcp.Identity") - proto.RegisterType((*StartClientHandshakeReq)(nil), "grpc.gcp.StartClientHandshakeReq") - proto.RegisterType((*ServerHandshakeParameters)(nil), "grpc.gcp.ServerHandshakeParameters") - proto.RegisterType((*StartServerHandshakeReq)(nil), "grpc.gcp.StartServerHandshakeReq") - proto.RegisterMapType((map[int32]*ServerHandshakeParameters)(nil), "grpc.gcp.StartServerHandshakeReq.HandshakeParametersEntry") - proto.RegisterType((*NextHandshakeMessageReq)(nil), "grpc.gcp.NextHandshakeMessageReq") - proto.RegisterType((*HandshakerReq)(nil), "grpc.gcp.HandshakerReq") - proto.RegisterType((*HandshakerResult)(nil), "grpc.gcp.HandshakerResult") - proto.RegisterType((*HandshakerStatus)(nil), "grpc.gcp.HandshakerStatus") - proto.RegisterType((*HandshakerResp)(nil), "grpc.gcp.HandshakerResp") - proto.RegisterEnum("grpc.gcp.HandshakeProtocol", HandshakeProtocol_name, HandshakeProtocol_value) - proto.RegisterEnum("grpc.gcp.NetworkProtocol", NetworkProtocol_name, NetworkProtocol_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// HandshakerServiceClient is the client API for HandshakerService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type HandshakerServiceClient interface { - // 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. - DoHandshake(ctx context.Context, opts ...grpc.CallOption) (HandshakerService_DoHandshakeClient, error) -} - -type handshakerServiceClient struct { - cc *grpc.ClientConn -} - -func NewHandshakerServiceClient(cc *grpc.ClientConn) HandshakerServiceClient { - return &handshakerServiceClient{cc} -} - -func (c *handshakerServiceClient) DoHandshake(ctx context.Context, opts ...grpc.CallOption) (HandshakerService_DoHandshakeClient, error) { - stream, err := c.cc.NewStream(ctx, &_HandshakerService_serviceDesc.Streams[0], "/grpc.gcp.HandshakerService/DoHandshake", opts...) - if err != nil { - return nil, err - } - x := &handshakerServiceDoHandshakeClient{stream} - return x, nil -} - -type HandshakerService_DoHandshakeClient interface { - Send(*HandshakerReq) error - Recv() (*HandshakerResp, error) - grpc.ClientStream -} - -type handshakerServiceDoHandshakeClient struct { - grpc.ClientStream -} - -func (x *handshakerServiceDoHandshakeClient) Send(m *HandshakerReq) error { - return x.ClientStream.SendMsg(m) -} - -func (x *handshakerServiceDoHandshakeClient) Recv() (*HandshakerResp, error) { - m := new(HandshakerResp) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// HandshakerServiceServer is the server API for HandshakerService service. -type HandshakerServiceServer interface { - // 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. - DoHandshake(HandshakerService_DoHandshakeServer) error -} - -func RegisterHandshakerServiceServer(s *grpc.Server, srv HandshakerServiceServer) { - s.RegisterService(&_HandshakerService_serviceDesc, srv) -} - -func _HandshakerService_DoHandshake_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(HandshakerServiceServer).DoHandshake(&handshakerServiceDoHandshakeServer{stream}) -} - -type HandshakerService_DoHandshakeServer interface { - Send(*HandshakerResp) error - Recv() (*HandshakerReq, error) - grpc.ServerStream -} - -type handshakerServiceDoHandshakeServer struct { - grpc.ServerStream -} - -func (x *handshakerServiceDoHandshakeServer) Send(m *HandshakerResp) error { - return x.ServerStream.SendMsg(m) -} - -func (x *handshakerServiceDoHandshakeServer) Recv() (*HandshakerReq, error) { - m := new(HandshakerReq) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _HandshakerService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.gcp.HandshakerService", - HandlerType: (*HandshakerServiceServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "DoHandshake", - Handler: _HandshakerService_DoHandshake_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc/gcp/handshaker.proto", -} - -func init() { - proto.RegisterFile("grpc/gcp/handshaker.proto", fileDescriptor_handshaker_b28e45bdd1661054) -} - -var fileDescriptor_handshaker_b28e45bdd1661054 = []byte{ - // 1128 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0xdf, 0x6e, 0x1a, 0xc7, - 0x17, 0xf6, 0x02, 0xb6, 0xe1, 0x60, 0xfe, 0x78, 0x92, 0x28, 0xd8, 0x49, 0x7e, 0x3f, 0x4a, 0x55, - 0x95, 0xf8, 0x02, 0x5a, 0xd2, 0x2a, 0x4d, 0xa2, 0xaa, 0xb1, 0x31, 0x16, 0x6e, 0x5c, 0x8c, 0x16, - 0xa7, 0x95, 0x9a, 0x8b, 0xd5, 0x64, 0x39, 0x59, 0xaf, 0x58, 0x66, 0xd6, 0x33, 0x83, 0x1b, 0x1e, - 0xa0, 0x8f, 0xd3, 0x57, 0xe8, 0xdb, 0xf4, 0x0d, 0x7a, 0xdf, 0x6a, 0x67, 0xff, 0x61, 0x0c, 0x51, - 0xa2, 0xde, 0xed, 0xce, 0x7c, 0xdf, 0xd9, 0x73, 0xbe, 0xf3, 0xcd, 0xd9, 0x81, 0x3d, 0x47, 0xf8, - 0x76, 0xdb, 0xb1, 0xfd, 0xf6, 0x25, 0x65, 0x63, 0x79, 0x49, 0x27, 0x28, 0x5a, 0xbe, 0xe0, 0x8a, - 0x93, 0x7c, 0xb0, 0xd5, 0x72, 0x6c, 0x7f, 0xbf, 0x99, 0x80, 0x94, 0xa0, 0x4c, 0xfa, 0x5c, 0x28, - 0x4b, 0xa2, 0x3d, 0x13, 0xae, 0x9a, 0x5b, 0x36, 0x9f, 0x4e, 0x39, 0x0b, 0x39, 0x0d, 0x05, 0xf9, - 0x1e, 0x1b, 0xfb, 0xdc, 0x65, 0x8a, 0x3c, 0x02, 0x70, 0x7d, 0x8b, 0x8e, 0xc7, 0x02, 0xa5, 0xac, - 0x19, 0x75, 0xa3, 0x59, 0x30, 0x0b, 0xae, 0x7f, 0x18, 0x2e, 0x10, 0x02, 0xb9, 0x20, 0x50, 0x2d, - 0x53, 0x37, 0x9a, 0x9b, 0xa6, 0x7e, 0x26, 0xdf, 0x42, 0x5e, 0xc7, 0xb1, 0xb9, 0x57, 0xcb, 0xd6, - 0x8d, 0x66, 0xb9, 0xb3, 0xd7, 0x8a, 0xb3, 0x68, 0x0d, 0x50, 0xfd, 0xc6, 0xc5, 0x64, 0x18, 0x01, - 0xcc, 0x04, 0xda, 0x40, 0xc8, 0x9f, 0x8e, 0x91, 0x29, 0x57, 0xcd, 0xc9, 0x63, 0xa8, 0x48, 0x14, - 0xd7, 0xae, 0x8d, 0x16, 0xb5, 0x6d, 0x3e, 0x63, 0x2a, 0xfc, 0x74, 0x7f, 0xc3, 0x2c, 0x47, 0x1b, - 0x87, 0xe1, 0x3a, 0x79, 0x08, 0xf9, 0x4b, 0x2e, 0x15, 0xa3, 0x53, 0xd4, 0x59, 0x04, 0x98, 0x64, - 0xe5, 0xa8, 0x0a, 0x65, 0x37, 0x0a, 0x6a, 0x71, 0x86, 0xfc, 0x5d, 0xe3, 0x8f, 0x1c, 0xdc, 0x1f, - 0x29, 0x2a, 0x54, 0xd7, 0x73, 0x91, 0xa9, 0x7e, 0x2c, 0x98, 0x89, 0x57, 0xe4, 0x0d, 0x3c, 0x48, - 0x04, 0x4c, 0xb5, 0x49, 0x8a, 0x31, 0x74, 0x31, 0x0f, 0xd2, 0x62, 0x12, 0x72, 0x52, 0xce, 0x5e, - 0xc2, 0x1f, 0x45, 0xf4, 0x78, 0x8b, 0x3c, 0x81, 0x7b, 0xd4, 0xf7, 0x3d, 0xd7, 0xa6, 0xca, 0xe5, - 0x2c, 0x89, 0x2a, 0x6b, 0x99, 0x7a, 0xb6, 0x59, 0x30, 0xef, 0x2e, 0x6c, 0xc6, 0x1c, 0x49, 0x1e, - 0x43, 0x55, 0xa0, 0xcd, 0xc5, 0x78, 0x01, 0x9f, 0xd5, 0xf8, 0x4a, 0xb8, 0x9e, 0x42, 0x7f, 0x80, - 0x5d, 0x45, 0x85, 0x83, 0xca, 0x8a, 0x2a, 0x76, 0x51, 0xd6, 0x72, 0xf5, 0x6c, 0xb3, 0xd8, 0x21, - 0x69, 0xca, 0xb1, 0xc4, 0x66, 0x35, 0x04, 0x9f, 0x26, 0x58, 0xf2, 0x0c, 0xca, 0x1e, 0xb7, 0xa9, - 0x17, 0xf3, 0xe7, 0xb5, 0xcd, 0xba, 0xb1, 0x86, 0x5d, 0xd2, 0xc8, 0xa4, 0x5f, 0x09, 0x15, 0x23, - 0xdf, 0xd4, 0xb6, 0x96, 0xa9, 0xb1, 0xa3, 0x22, 0x6a, 0x62, 0xb0, 0x17, 0x50, 0x11, 0x38, 0xe5, - 0x0a, 0x53, 0xee, 0xf6, 0x5a, 0x6e, 0x39, 0x84, 0x26, 0xe4, 0xff, 0x43, 0x31, 0xaa, 0x59, 0xf7, - 0x3f, 0xaf, 0xed, 0x09, 0xe1, 0xd2, 0x80, 0x4e, 0x91, 0xbc, 0x84, 0x1d, 0xe1, 0xdb, 0xd6, 0x35, - 0x0a, 0xe9, 0x72, 0x26, 0x6b, 0x05, 0x1d, 0xfa, 0x51, 0x1a, 0xda, 0xf4, 0xed, 0x58, 0xc2, 0x9f, - 0x23, 0x90, 0x59, 0x14, 0xbe, 0x1d, 0xbf, 0x34, 0x7e, 0x37, 0x60, 0x6f, 0x84, 0xe2, 0x1a, 0x45, - 0xda, 0x6d, 0x2a, 0xe8, 0x14, 0x15, 0x8a, 0xd5, 0xfd, 0x31, 0x56, 0xf7, 0xe7, 0x7b, 0xa8, 0xde, - 0x90, 0x37, 0x68, 0x4f, 0x66, 0x6d, 0x7b, 0x2a, 0x8b, 0x02, 0xbb, 0x28, 0x1b, 0xff, 0x64, 0x23, - 0xdf, 0x2e, 0x25, 0x13, 0xf8, 0x76, 0xad, 0xb5, 0x8c, 0x0f, 0x58, 0x6b, 0x0a, 0x77, 0x53, 0xb3, - 0xfb, 0x49, 0x49, 0x51, 0x4e, 0xcf, 0xd3, 0x9c, 0xd6, 0x7c, 0xb5, 0xb5, 0x42, 0x8f, 0x1e, 0x53, - 0x62, 0x6e, 0xde, 0xb9, 0x5c, 0xa1, 0xd4, 0x1e, 0xe4, 0x5d, 0x66, 0xbd, 0x9d, 0x2b, 0x94, 0x7a, - 0x2a, 0xec, 0x98, 0xdb, 0x2e, 0x3b, 0x0a, 0x5e, 0x57, 0xb8, 0x27, 0xf7, 0x1f, 0xdc, 0xb3, 0xf9, - 0xd1, 0xee, 0x59, 0x36, 0xc7, 0xd6, 0xa7, 0x9a, 0x63, 0x7f, 0x02, 0xb5, 0x75, 0x2a, 0x90, 0x2a, - 0x64, 0x27, 0x38, 0xd7, 0x43, 0x63, 0xd3, 0x0c, 0x1e, 0xc9, 0x33, 0xd8, 0xbc, 0xa6, 0xde, 0x2c, - 0x9c, 0x53, 0xc5, 0xce, 0xe7, 0x0b, 0x12, 0xaf, 0x33, 0x98, 0x19, 0x32, 0x9e, 0x67, 0xbe, 0x33, - 0x1a, 0xdf, 0xc0, 0xfd, 0x01, 0xbe, 0x4f, 0x27, 0xd6, 0x4f, 0x28, 0x25, 0x75, 0xb4, 0x01, 0x16, - 0xc5, 0x35, 0x6e, 0x88, 0xdb, 0xf8, 0xcb, 0x80, 0x52, 0x42, 0x11, 0x01, 0xf8, 0x04, 0x76, 0x6c, - 0x3d, 0xfb, 0x2c, 0x19, 0x74, 0x56, 0x13, 0x8a, 0x9d, 0xcf, 0x96, 0x1a, 0x7e, 0x7b, 0x3c, 0xf6, - 0x37, 0xcc, 0x62, 0x48, 0xd4, 0x80, 0x20, 0x8e, 0xd4, 0x79, 0x47, 0x71, 0x32, 0x2b, 0xe3, 0xdc, - 0x36, 0x4e, 0x10, 0x27, 0x24, 0x86, 0x71, 0x9e, 0x42, 0x8e, 0xe1, 0x7b, 0xa5, 0x5d, 0x71, 0x83, - 0xbf, 0xa6, 0xda, 0xfe, 0x86, 0xa9, 0x09, 0x47, 0x45, 0x28, 0x08, 0xbc, 0x8a, 0xe6, 0xfa, 0xdf, - 0x19, 0xa8, 0x2e, 0xd6, 0x29, 0x67, 0x9e, 0x22, 0x5f, 0xc3, 0xdd, 0x55, 0x07, 0x23, 0xfa, 0x8f, - 0xdd, 0x59, 0x71, 0x2e, 0xc8, 0x97, 0x50, 0x59, 0x3a, 0xd1, 0xe1, 0x6f, 0x25, 0x70, 0xcf, 0xe2, - 0x81, 0x0e, 0x34, 0x9f, 0xe0, 0xdc, 0x1a, 0x53, 0x45, 0x63, 0x43, 0x4f, 0x70, 0x7e, 0x4c, 0x15, - 0x25, 0x4f, 0xa1, 0xe4, 0x23, 0x8a, 0x74, 0x90, 0xe6, 0xd6, 0x0e, 0xd2, 0x9d, 0x00, 0x78, 0x7b, - 0x8e, 0x7e, 0xfa, 0x08, 0x3e, 0x80, 0xdd, 0x09, 0xa2, 0x6f, 0xd9, 0x97, 0x94, 0x31, 0xf4, 0x2c, - 0xee, 0x23, 0xd3, 0x8e, 0xce, 0x9b, 0x95, 0x60, 0xa3, 0x1b, 0xae, 0x9f, 0xfb, 0xc8, 0xc8, 0x29, - 0xec, 0xea, 0xfc, 0x6e, 0xb8, 0x7f, 0xfb, 0x63, 0xdc, 0x5f, 0x09, 0x78, 0xe6, 0xc2, 0x78, 0x7c, - 0xb9, 0xa8, 0xfa, 0x48, 0x51, 0x35, 0xd3, 0x97, 0x02, 0x9b, 0x8f, 0x51, 0xab, 0x5c, 0x32, 0xf5, - 0x33, 0xa9, 0xc1, 0xf6, 0x18, 0x15, 0x75, 0xf5, 0xff, 0x2e, 0x90, 0x33, 0x7e, 0x6d, 0xfc, 0x69, - 0x40, 0xf9, 0x46, 0xe3, 0xfc, 0xe0, 0xd2, 0xc1, 0x67, 0xca, 0x7a, 0x17, 0x9c, 0x82, 0xd8, 0xd0, - 0x05, 0x3e, 0x53, 0x27, 0x7a, 0x81, 0x7c, 0x01, 0x65, 0x6d, 0x75, 0xcb, 0xe6, 0x4c, 0xce, 0xa6, - 0x38, 0xd6, 0x21, 0x4b, 0x66, 0x49, 0xaf, 0x76, 0xa3, 0x45, 0xd2, 0x81, 0x2d, 0xa1, 0x6d, 0x10, - 0x39, 0x6b, 0x7f, 0xc5, 0x8f, 0x3b, 0x32, 0x8a, 0x19, 0x21, 0x03, 0x8e, 0xd4, 0x45, 0x44, 0x2d, - 0x5b, 0xc9, 0x09, 0xcb, 0x34, 0x23, 0xe4, 0xc1, 0x8f, 0xb0, 0x7b, 0xeb, 0x22, 0x40, 0x1a, 0xf0, - 0xbf, 0xfe, 0xe1, 0xe0, 0x78, 0xd4, 0x3f, 0x7c, 0xd5, 0xb3, 0x86, 0xe6, 0xf9, 0xc5, 0x79, 0xf7, - 0xfc, 0xcc, 0x7a, 0x3d, 0x18, 0x0d, 0x7b, 0xdd, 0xd3, 0x93, 0xd3, 0xde, 0x71, 0x75, 0x83, 0x6c, - 0x43, 0xf6, 0xe2, 0x6c, 0x54, 0x35, 0x48, 0x1e, 0x72, 0x87, 0x67, 0x17, 0xa3, 0x6a, 0xe6, 0xa0, - 0x07, 0x95, 0xa5, 0x1b, 0x12, 0xa9, 0xc3, 0xc3, 0x41, 0xef, 0xe2, 0x97, 0x73, 0xf3, 0xd5, 0x87, - 0xe2, 0x74, 0x87, 0x55, 0x23, 0x78, 0x78, 0x7d, 0x3c, 0xac, 0x66, 0x3a, 0x6f, 0x16, 0x52, 0x12, - 0xa3, 0xf0, 0xc2, 0x44, 0x4e, 0xa0, 0x78, 0xcc, 0x93, 0x65, 0x72, 0x7f, 0xb5, 0x1c, 0x57, 0xfb, - 0xb5, 0x35, 0x3a, 0xf9, 0x8d, 0x8d, 0xa6, 0xf1, 0x95, 0x71, 0xe4, 0xc0, 0x3d, 0x97, 0x87, 0x18, - 0xea, 0x29, 0xd9, 0x72, 0x99, 0x42, 0xc1, 0xa8, 0x77, 0x54, 0x49, 0xe1, 0x3a, 0xfb, 0xa1, 0xf1, - 0xeb, 0x0b, 0x87, 0x73, 0xc7, 0xc3, 0x96, 0xc3, 0x3d, 0xca, 0x9c, 0x16, 0x17, 0x4e, 0x5b, 0x5f, - 0x43, 0x6d, 0x81, 0xda, 0xb8, 0xd4, 0x93, 0xed, 0x20, 0x48, 0xdb, 0xe6, 0x02, 0xdb, 0xfa, 0xc4, - 0x69, 0x80, 0xe5, 0xd8, 0xfe, 0xdb, 0x2d, 0xfd, 0xfe, 0xe4, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xfa, 0xd2, 0x42, 0x7f, 0xdf, 0x0a, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/transport_security_common.pb.go b/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/transport_security_common.pb.go deleted file mode 100755 index 120700e..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp/transport_security_common.pb.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/gcp/transport_security_common.proto - -package grpc_gcp // import "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The security level of the created channel. The list is sorted in increasing -// level of security. This order must always be maintained. -type SecurityLevel int32 - -const ( - SecurityLevel_SECURITY_NONE SecurityLevel = 0 - SecurityLevel_INTEGRITY_ONLY SecurityLevel = 1 - SecurityLevel_INTEGRITY_AND_PRIVACY SecurityLevel = 2 -) - -var SecurityLevel_name = map[int32]string{ - 0: "SECURITY_NONE", - 1: "INTEGRITY_ONLY", - 2: "INTEGRITY_AND_PRIVACY", -} -var SecurityLevel_value = map[string]int32{ - "SECURITY_NONE": 0, - "INTEGRITY_ONLY": 1, - "INTEGRITY_AND_PRIVACY": 2, -} - -func (x SecurityLevel) String() string { - return proto.EnumName(SecurityLevel_name, int32(x)) -} -func (SecurityLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_transport_security_common_6489ab913bf26255, []int{0} -} - -// Max and min supported RPC protocol versions. -type RpcProtocolVersions struct { - // Maximum supported RPC version. - MaxRpcVersion *RpcProtocolVersions_Version `protobuf:"bytes,1,opt,name=max_rpc_version,json=maxRpcVersion,proto3" json:"max_rpc_version,omitempty"` - // Minimum supported RPC version. - MinRpcVersion *RpcProtocolVersions_Version `protobuf:"bytes,2,opt,name=min_rpc_version,json=minRpcVersion,proto3" json:"min_rpc_version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RpcProtocolVersions) Reset() { *m = RpcProtocolVersions{} } -func (m *RpcProtocolVersions) String() string { return proto.CompactTextString(m) } -func (*RpcProtocolVersions) ProtoMessage() {} -func (*RpcProtocolVersions) Descriptor() ([]byte, []int) { - return fileDescriptor_transport_security_common_6489ab913bf26255, []int{0} -} -func (m *RpcProtocolVersions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RpcProtocolVersions.Unmarshal(m, b) -} -func (m *RpcProtocolVersions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RpcProtocolVersions.Marshal(b, m, deterministic) -} -func (dst *RpcProtocolVersions) XXX_Merge(src proto.Message) { - xxx_messageInfo_RpcProtocolVersions.Merge(dst, src) -} -func (m *RpcProtocolVersions) XXX_Size() int { - return xxx_messageInfo_RpcProtocolVersions.Size(m) -} -func (m *RpcProtocolVersions) XXX_DiscardUnknown() { - xxx_messageInfo_RpcProtocolVersions.DiscardUnknown(m) -} - -var xxx_messageInfo_RpcProtocolVersions proto.InternalMessageInfo - -func (m *RpcProtocolVersions) GetMaxRpcVersion() *RpcProtocolVersions_Version { - if m != nil { - return m.MaxRpcVersion - } - return nil -} - -func (m *RpcProtocolVersions) GetMinRpcVersion() *RpcProtocolVersions_Version { - if m != nil { - return m.MinRpcVersion - } - return nil -} - -// RPC version contains a major version and a minor version. -type RpcProtocolVersions_Version struct { - Major uint32 `protobuf:"varint,1,opt,name=major,proto3" json:"major,omitempty"` - Minor uint32 `protobuf:"varint,2,opt,name=minor,proto3" json:"minor,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RpcProtocolVersions_Version) Reset() { *m = RpcProtocolVersions_Version{} } -func (m *RpcProtocolVersions_Version) String() string { return proto.CompactTextString(m) } -func (*RpcProtocolVersions_Version) ProtoMessage() {} -func (*RpcProtocolVersions_Version) Descriptor() ([]byte, []int) { - return fileDescriptor_transport_security_common_6489ab913bf26255, []int{0, 0} -} -func (m *RpcProtocolVersions_Version) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RpcProtocolVersions_Version.Unmarshal(m, b) -} -func (m *RpcProtocolVersions_Version) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RpcProtocolVersions_Version.Marshal(b, m, deterministic) -} -func (dst *RpcProtocolVersions_Version) XXX_Merge(src proto.Message) { - xxx_messageInfo_RpcProtocolVersions_Version.Merge(dst, src) -} -func (m *RpcProtocolVersions_Version) XXX_Size() int { - return xxx_messageInfo_RpcProtocolVersions_Version.Size(m) -} -func (m *RpcProtocolVersions_Version) XXX_DiscardUnknown() { - xxx_messageInfo_RpcProtocolVersions_Version.DiscardUnknown(m) -} - -var xxx_messageInfo_RpcProtocolVersions_Version proto.InternalMessageInfo - -func (m *RpcProtocolVersions_Version) GetMajor() uint32 { - if m != nil { - return m.Major - } - return 0 -} - -func (m *RpcProtocolVersions_Version) GetMinor() uint32 { - if m != nil { - return m.Minor - } - return 0 -} - -func init() { - proto.RegisterType((*RpcProtocolVersions)(nil), "grpc.gcp.RpcProtocolVersions") - proto.RegisterType((*RpcProtocolVersions_Version)(nil), "grpc.gcp.RpcProtocolVersions.Version") - proto.RegisterEnum("grpc.gcp.SecurityLevel", SecurityLevel_name, SecurityLevel_value) -} - -func init() { - proto.RegisterFile("grpc/gcp/transport_security_common.proto", fileDescriptor_transport_security_common_6489ab913bf26255) -} - -var fileDescriptor_transport_security_common_6489ab913bf26255 = []byte{ - // 324 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x91, 0x41, 0x4b, 0x3b, 0x31, - 0x10, 0xc5, 0xff, 0x5b, 0xf8, 0xab, 0x44, 0x56, 0xeb, 0x6a, 0x41, 0xc5, 0x83, 0x08, 0x42, 0xf1, - 0x90, 0x05, 0xc5, 0x93, 0xa7, 0xb6, 0x16, 0x29, 0xd4, 0x6d, 0xdd, 0xd6, 0x42, 0xbd, 0x84, 0x18, - 0x43, 0x88, 0x64, 0x33, 0x61, 0x36, 0x96, 0xfa, 0x95, 0xfd, 0x14, 0xb2, 0x69, 0x97, 0x22, 0x78, - 0xf1, 0x96, 0xf7, 0x98, 0xf9, 0x4d, 0x66, 0x1e, 0x69, 0x2b, 0x74, 0x22, 0x55, 0xc2, 0xa5, 0x1e, - 0xb9, 0x2d, 0x1d, 0xa0, 0x67, 0xa5, 0x14, 0x1f, 0xa8, 0xfd, 0x27, 0x13, 0x50, 0x14, 0x60, 0xa9, - 0x43, 0xf0, 0x90, 0xec, 0x54, 0x95, 0x54, 0x09, 0x77, 0xf1, 0x15, 0x91, 0xc3, 0xdc, 0x89, 0x71, - 0x65, 0x0b, 0x30, 0x33, 0x89, 0xa5, 0x06, 0x5b, 0x26, 0x8f, 0x64, 0xbf, 0xe0, 0x4b, 0x86, 0x4e, - 0xb0, 0xc5, 0xca, 0x3b, 0x8e, 0xce, 0xa3, 0xf6, 0xee, 0xf5, 0x25, 0xad, 0x7b, 0xe9, 0x2f, 0x7d, - 0x74, 0xfd, 0xc8, 0xe3, 0x82, 0x2f, 0x73, 0x27, 0xd6, 0x32, 0xe0, 0xb4, 0xfd, 0x81, 0x6b, 0xfc, - 0x0d, 0xa7, 0xed, 0x06, 0x77, 0x7a, 0x4b, 0xb6, 0x6b, 0xf2, 0x11, 0xf9, 0x5f, 0xf0, 0x77, 0xc0, - 0xf0, 0xbd, 0x38, 0x5f, 0x89, 0xe0, 0x6a, 0x0b, 0x18, 0xa6, 0x54, 0x6e, 0x25, 0xae, 0x9e, 0x48, - 0x3c, 0x59, 0xdf, 0x63, 0x28, 0x17, 0xd2, 0x24, 0x07, 0x24, 0x9e, 0xf4, 0x7b, 0xcf, 0xf9, 0x60, - 0x3a, 0x67, 0xd9, 0x28, 0xeb, 0x37, 0xff, 0x25, 0x09, 0xd9, 0x1b, 0x64, 0xd3, 0xfe, 0x43, 0xf0, - 0x46, 0xd9, 0x70, 0xde, 0x8c, 0x92, 0x13, 0xd2, 0xda, 0x78, 0x9d, 0xec, 0x9e, 0x8d, 0xf3, 0xc1, - 0xac, 0xd3, 0x9b, 0x37, 0x1b, 0x5d, 0x4f, 0x5a, 0x1a, 0x56, 0x3b, 0x70, 0xe3, 0x4b, 0xaa, 0xad, - 0x97, 0x68, 0xb9, 0xe9, 0x9e, 0x4d, 0xeb, 0x0c, 0xea, 0x91, 0xbd, 0x90, 0x40, 0x58, 0x71, 0x1c, - 0xbd, 0xdc, 0x29, 0x00, 0x65, 0x24, 0x55, 0x60, 0xb8, 0x55, 0x14, 0x50, 0xa5, 0x21, 0x3e, 0x81, - 0xf2, 0x4d, 0x5a, 0xaf, 0xb9, 0x29, 0xd3, 0x8a, 0x98, 0x0a, 0x40, 0x99, 0x86, 0xd8, 0x42, 0x01, - 0x53, 0xc2, 0xbd, 0x6e, 0x05, 0x7d, 0xf3, 0x1d, 0x00, 0x00, 0xff, 0xff, 0xa8, 0xc8, 0x38, 0x9d, - 0xf2, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/credentials/alts/core/regenerate.sh b/examples/google.golang.org/grpc/credentials/alts/core/regenerate.sh deleted file mode 100755 index a79c420..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/regenerate.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/gcp -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/gcp/altscontext.proto > grpc/gcp/altscontext.proto -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/gcp/handshaker.proto > grpc/gcp/handshaker.proto -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/gcp/transport_security_common.proto > grpc/gcp/transport_security_common.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/gcp/*.proto -popd -rm -f proto/grpc_gcp/*.pb.go -cp "$TMP"/grpc/gcp/*.pb.go proto/grpc_gcp/ - diff --git a/examples/google.golang.org/grpc/credentials/alts/core/testutil/testutil.go b/examples/google.golang.org/grpc/credentials/alts/core/testutil/testutil.go deleted file mode 100755 index 91cbd03..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/core/testutil/testutil.go +++ /dev/null @@ -1,125 +0,0 @@ -/* - * - * 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. - * - */ - -// Package testutil include useful test utilities for the handshaker. -package testutil - -import ( - "bytes" - "encoding/binary" - "io" - "net" - "sync" - - "google.golang.org/grpc/credentials/alts/core/conn" -) - -// Stats is used to collect statistics about concurrent handshake calls. -type Stats struct { - mu sync.Mutex - calls int - MaxConcurrentCalls int -} - -// Update updates the statistics by adding one call. -func (s *Stats) Update() func() { - s.mu.Lock() - s.calls++ - if s.calls > s.MaxConcurrentCalls { - s.MaxConcurrentCalls = s.calls - } - s.mu.Unlock() - - return func() { - s.mu.Lock() - s.calls-- - s.mu.Unlock() - } -} - -// Reset resets the statistics. -func (s *Stats) Reset() { - s.mu.Lock() - defer s.mu.Unlock() - s.calls = 0 - s.MaxConcurrentCalls = 0 -} - -// testConn mimics a net.Conn to the peer. -type testConn struct { - net.Conn - in *bytes.Buffer - out *bytes.Buffer -} - -// NewTestConn creates a new instance of testConn object. -func NewTestConn(in *bytes.Buffer, out *bytes.Buffer) net.Conn { - return &testConn{ - in: in, - out: out, - } -} - -// Read reads from the in buffer. -func (c *testConn) Read(b []byte) (n int, err error) { - return c.in.Read(b) -} - -// Write writes to the out buffer. -func (c *testConn) Write(b []byte) (n int, err error) { - return c.out.Write(b) -} - -// Close closes the testConn object. -func (c *testConn) Close() error { - return nil -} - -// unresponsiveTestConn mimics a net.Conn for an unresponsive peer. It is used -// for testing the PeerNotResponding case. -type unresponsiveTestConn struct { - net.Conn -} - -// NewUnresponsiveTestConn creates a new instance of unresponsiveTestConn object. -func NewUnresponsiveTestConn() net.Conn { - return &unresponsiveTestConn{} -} - -// Read reads from the in buffer. -func (c *unresponsiveTestConn) Read(b []byte) (n int, err error) { - return 0, io.EOF -} - -// Write writes to the out buffer. -func (c *unresponsiveTestConn) Write(b []byte) (n int, err error) { - return 0, nil -} - -// Close closes the TestConn object. -func (c *unresponsiveTestConn) Close() error { - return nil -} - -// MakeFrame creates a handshake frame. -func MakeFrame(pl string) []byte { - f := make([]byte, len(pl)+conn.MsgLenFieldSize) - binary.LittleEndian.PutUint32(f, uint32(len(pl))) - copy(f[conn.MsgLenFieldSize:], []byte(pl)) - return f -} diff --git a/examples/google.golang.org/grpc/credentials/alts/utils.go b/examples/google.golang.org/grpc/credentials/alts/utils.go deleted file mode 100755 index 9f92eb1..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/utils.go +++ /dev/null @@ -1,136 +0,0 @@ -/* - * - * 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. - * - */ - -package alts - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "os/exec" - "regexp" - "runtime" - "strings" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/peer" -) - -const ( - linuxProductNameFile = "/sys/class/dmi/id/product_name" - windowsCheckCommand = "powershell.exe" - windowsCheckCommandArgs = "Get-WmiObject -Class Win32_BIOS" - powershellOutputFilter = "Manufacturer" - windowsManufacturerRegex = ":(.*)" - windowsCheckTimeout = 30 * time.Second -) - -type platformError string - -func (k platformError) Error() string { - return fmt.Sprintf("%s is not supported", string(k)) -} - -var ( - // The following two variables will be reassigned in tests. - runningOS = runtime.GOOS - manufacturerReader = func() (io.Reader, error) { - switch runningOS { - case "linux": - return os.Open(linuxProductNameFile) - case "windows": - cmd := exec.Command(windowsCheckCommand, windowsCheckCommandArgs) - out, err := cmd.Output() - if err != nil { - return nil, err - } - - for _, line := range strings.Split(strings.TrimSuffix(string(out), "\n"), "\n") { - if strings.HasPrefix(line, powershellOutputFilter) { - re := regexp.MustCompile(windowsManufacturerRegex) - name := re.FindString(line) - name = strings.TrimLeft(name, ":") - return strings.NewReader(name), nil - } - } - - return nil, errors.New("cannot determine the machine's manufacturer") - default: - return nil, platformError(runningOS) - } - } - vmOnGCP bool -) - -// isRunningOnGCP checks whether the local system, without doing a network request is -// running on GCP. -func isRunningOnGCP() bool { - manufacturer, err := readManufacturer() - if err != nil { - log.Fatalf("failure to read manufacturer information: %v", err) - } - name := string(manufacturer) - switch runningOS { - case "linux": - name = strings.TrimSpace(name) - return name == "Google" || name == "Google Compute Engine" - case "windows": - name = strings.Replace(name, " ", "", -1) - name = strings.Replace(name, "\n", "", -1) - name = strings.Replace(name, "\r", "", -1) - return name == "Google" - default: - log.Fatal(platformError(runningOS)) - } - return false -} - -func readManufacturer() ([]byte, error) { - reader, err := manufacturerReader() - if err != nil { - return nil, err - } - if reader == nil { - return nil, errors.New("got nil reader") - } - manufacturer, err := ioutil.ReadAll(reader) - if err != nil { - return nil, fmt.Errorf("failed reading %v: %v", linuxProductNameFile, err) - } - return manufacturer, nil -} - -// AuthInfoFromContext extracts the alts.AuthInfo object from the given context, -// if it exists. This API should be used by gRPC server RPC handlers to get -// information about the communicating peer. For client-side, use grpc.Peer() -// CallOption. -func AuthInfoFromContext(ctx context.Context) (AuthInfo, error) { - peer, ok := peer.FromContext(ctx) - if !ok { - return nil, errors.New("no Peer found in Context") - } - altsAuthInfo, ok := peer.AuthInfo.(AuthInfo) - if !ok { - return nil, errors.New("no alts.AuthInfo found in Context") - } - return altsAuthInfo, nil -} diff --git a/examples/google.golang.org/grpc/credentials/alts/utils_test.go b/examples/google.golang.org/grpc/credentials/alts/utils_test.go deleted file mode 100755 index 4724103..0000000 --- a/examples/google.golang.org/grpc/credentials/alts/utils_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * 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. - * - */ - -package alts - -import ( - "io" - "strings" - "testing" - - "golang.org/x/net/context" - altspb "google.golang.org/grpc/credentials/alts/core/proto/grpc_gcp" - "google.golang.org/grpc/peer" -) - -func TestIsRunningOnGCP(t *testing.T) { - for _, tc := range []struct { - description string - testOS string - testReader io.Reader - out bool - }{ - // Linux tests. - {"linux: not a GCP platform", "linux", strings.NewReader("not GCP"), false}, - {"Linux: GCP platform (Google)", "linux", strings.NewReader("Google"), true}, - {"Linux: GCP platform (Google Compute Engine)", "linux", strings.NewReader("Google Compute Engine"), true}, - {"Linux: GCP platform (Google Compute Engine) with extra spaces", "linux", strings.NewReader(" Google Compute Engine "), true}, - // Windows tests. - {"windows: not a GCP platform", "windows", strings.NewReader("not GCP"), false}, - {"windows: GCP platform (Google)", "windows", strings.NewReader("Google"), true}, - {"windows: GCP platform (Google) with extra spaces", "windows", strings.NewReader(" Google "), true}, - } { - reverseFunc := setup(tc.testOS, tc.testReader) - if got, want := isRunningOnGCP(), tc.out; got != want { - t.Errorf("%v: isRunningOnGCP()=%v, want %v", tc.description, got, want) - } - reverseFunc() - } -} - -func setup(testOS string, testReader io.Reader) func() { - tmpOS := runningOS - tmpReader := manufacturerReader - - // Set test OS and reader function. - runningOS = testOS - manufacturerReader = func() (io.Reader, error) { - return testReader, nil - } - - return func() { - runningOS = tmpOS - manufacturerReader = tmpReader - } -} - -func TestAuthInfoFromContext(t *testing.T) { - ctx := context.Background() - altsAuthInfo := &fakeALTSAuthInfo{} - p := &peer.Peer{ - AuthInfo: altsAuthInfo, - } - for _, tc := range []struct { - desc string - ctx context.Context - success bool - out AuthInfo - }{ - { - "working case", - peer.NewContext(ctx, p), - true, - altsAuthInfo, - }, - } { - authInfo, err := AuthInfoFromContext(tc.ctx) - if got, want := (err == nil), tc.success; got != want { - t.Errorf("%v: AuthInfoFromContext(_)=(err=nil)=%v, want %v", tc.desc, got, want) - } - if got, want := authInfo, tc.out; got != want { - t.Errorf("%v:, AuthInfoFromContext(_)=(%v, _), want (%v, _)", tc.desc, got, want) - } - } -} - -type fakeALTSAuthInfo struct{} - -func (*fakeALTSAuthInfo) AuthType() string { return "" } -func (*fakeALTSAuthInfo) ApplicationProtocol() string { return "" } -func (*fakeALTSAuthInfo) RecordProtocol() string { return "" } -func (*fakeALTSAuthInfo) SecurityLevel() altspb.SecurityLevel { - return altspb.SecurityLevel_SECURITY_NONE -} -func (*fakeALTSAuthInfo) PeerServiceAccount() string { return "" } -func (*fakeALTSAuthInfo) LocalServiceAccount() string { return "" } -func (*fakeALTSAuthInfo) PeerRPCVersions() *altspb.RpcProtocolVersions { return nil } diff --git a/examples/google.golang.org/grpc/credentials/credentials.go b/examples/google.golang.org/grpc/credentials/credentials.go deleted file mode 100755 index 3351bf0..0000000 --- a/examples/google.golang.org/grpc/credentials/credentials.go +++ /dev/null @@ -1,220 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package credentials implements various credentials supported by gRPC library, -// which encapsulate all the state needed by a client to authenticate with a -// server and make various assertions, e.g., about the client's identity, role, -// or whether it is authorized to make a particular call. -package credentials // import "google.golang.org/grpc/credentials" - -import ( - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "io/ioutil" - "net" - "strings" - - "golang.org/x/net/context" -) - -// alpnProtoStr are the specified application level protocols for gRPC. -var alpnProtoStr = []string{"h2"} - -// PerRPCCredentials defines the common interface for the credentials which need to -// attach security information to every RPC (e.g., oauth2). -type PerRPCCredentials interface { - // GetRequestMetadata gets the current request metadata, refreshing - // tokens if required. This should be called by the transport layer on - // each request, and the data should be populated in headers or other - // context. If a status code is returned, it will be used as the status - // for the RPC. uri is the URI of the entry point for the request. - // When supported by the underlying implementation, ctx can be used for - // timeout and cancellation. - // TODO(zhaoq): Define the set of the qualified keys instead of leaving - // it as an arbitrary string. - GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) - // RequireTransportSecurity indicates whether the credentials requires - // transport security. - RequireTransportSecurity() bool -} - -// ProtocolInfo provides information regarding the gRPC wire protocol version, -// security protocol, security protocol version in use, server name, etc. -type ProtocolInfo struct { - // ProtocolVersion is the gRPC wire protocol version. - ProtocolVersion string - // SecurityProtocol is the security protocol in use. - SecurityProtocol string - // SecurityVersion is the security protocol version. - SecurityVersion string - // ServerName is the user-configured server name. - ServerName string -} - -// AuthInfo defines the common interface for the auth information the users are interested in. -type AuthInfo interface { - AuthType() string -} - -// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC -// and the caller should not close rawConn. -var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") - -// TransportCredentials defines the common interface for all the live gRPC wire -// protocols and supported transport security protocols (e.g., TLS, SSL). -type TransportCredentials interface { - // ClientHandshake does the authentication handshake specified by the corresponding - // authentication protocol on rawConn for clients. It returns the authenticated - // connection and the corresponding auth information about the connection. - // Implementations must use the provided context to implement timely cancellation. - // gRPC will try to reconnect if the error returned is a temporary error - // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). - // If the returned error is a wrapper error, implementations should make sure that - // the error implements Temporary() to have the correct retry behaviors. - // - // If the returned net.Conn is closed, it MUST close the net.Conn provided. - ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) - // ServerHandshake does the authentication handshake for servers. It returns - // the authenticated connection and the corresponding auth information about - // the connection. - // - // If the returned net.Conn is closed, it MUST close the net.Conn provided. - ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) - // Info provides the ProtocolInfo of this TransportCredentials. - Info() ProtocolInfo - // Clone makes a copy of this TransportCredentials. - Clone() TransportCredentials - // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server. - // gRPC internals also use it to override the virtual hosting name if it is set. - // It must be called before dialing. Currently, this is only used by grpclb. - OverrideServerName(string) error -} - -// TLSInfo contains the auth information for a TLS authenticated connection. -// It implements the AuthInfo interface. -type TLSInfo struct { - State tls.ConnectionState -} - -// AuthType returns the type of TLSInfo as a string. -func (t TLSInfo) AuthType() string { - return "tls" -} - -// tlsCreds is the credentials required for authenticating a connection using TLS. -type tlsCreds struct { - // TLS configuration - config *tls.Config -} - -func (c tlsCreds) Info() ProtocolInfo { - return ProtocolInfo{ - SecurityProtocol: "tls", - SecurityVersion: "1.2", - ServerName: c.config.ServerName, - } -} - -func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { - // use local cfg to avoid clobbering ServerName if using multiple endpoints - cfg := cloneTLSConfig(c.config) - if cfg.ServerName == "" { - colonPos := strings.LastIndex(authority, ":") - if colonPos == -1 { - colonPos = len(authority) - } - cfg.ServerName = authority[:colonPos] - } - conn := tls.Client(rawConn, cfg) - errChannel := make(chan error, 1) - go func() { - errChannel <- conn.Handshake() - }() - select { - case err := <-errChannel: - if err != nil { - return nil, nil, err - } - case <-ctx.Done(): - return nil, nil, ctx.Err() - } - return conn, TLSInfo{conn.ConnectionState()}, nil -} - -func (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) { - conn := tls.Server(rawConn, c.config) - if err := conn.Handshake(); err != nil { - return nil, nil, err - } - return conn, TLSInfo{conn.ConnectionState()}, nil -} - -func (c *tlsCreds) Clone() TransportCredentials { - return NewTLS(c.config) -} - -func (c *tlsCreds) OverrideServerName(serverNameOverride string) error { - c.config.ServerName = serverNameOverride - return nil -} - -// NewTLS uses c to construct a TransportCredentials based on TLS. -func NewTLS(c *tls.Config) TransportCredentials { - tc := &tlsCreds{cloneTLSConfig(c)} - tc.config.NextProtos = alpnProtoStr - return tc -} - -// NewClientTLSFromCert constructs TLS credentials from the input certificate for client. -// serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. -func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { - return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) -} - -// NewClientTLSFromFile constructs TLS credentials from the input certificate file for client. -// serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. -func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { - b, err := ioutil.ReadFile(certFile) - if err != nil { - return nil, err - } - cp := x509.NewCertPool() - if !cp.AppendCertsFromPEM(b) { - return nil, fmt.Errorf("credentials: failed to append certificates") - } - return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil -} - -// NewServerTLSFromCert constructs TLS credentials from the input certificate for server. -func NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials { - return NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}}) -} - -// NewServerTLSFromFile constructs TLS credentials from the input certificate file and key -// file for server. -func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) { - cert, err := tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return nil, err - } - return NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil -} diff --git a/examples/google.golang.org/grpc/credentials/credentials_test.go b/examples/google.golang.org/grpc/credentials/credentials_test.go deleted file mode 100755 index 9b13db5..0000000 --- a/examples/google.golang.org/grpc/credentials/credentials_test.go +++ /dev/null @@ -1,206 +0,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. - * - */ - -package credentials - -import ( - "crypto/tls" - "net" - "testing" - - "golang.org/x/net/context" - "google.golang.org/grpc/testdata" -) - -func TestTLSOverrideServerName(t *testing.T) { - expectedServerName := "server.name" - c := NewTLS(nil) - c.OverrideServerName(expectedServerName) - if c.Info().ServerName != expectedServerName { - t.Fatalf("c.Info().ServerName = %v, want %v", c.Info().ServerName, expectedServerName) - } -} - -func TestTLSClone(t *testing.T) { - expectedServerName := "server.name" - c := NewTLS(nil) - c.OverrideServerName(expectedServerName) - cc := c.Clone() - if cc.Info().ServerName != expectedServerName { - t.Fatalf("cc.Info().ServerName = %v, want %v", cc.Info().ServerName, expectedServerName) - } - cc.OverrideServerName("") - if c.Info().ServerName != expectedServerName { - t.Fatalf("Change in clone should not affect the original, c.Info().ServerName = %v, want %v", c.Info().ServerName, expectedServerName) - } - -} - -type serverHandshake func(net.Conn) (AuthInfo, error) - -func TestClientHandshakeReturnsAuthInfo(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, tlsServerHandshake, done) - defer lis.Close() - lisAddr := lis.Addr().String() - clientAuthInfo := clientHandle(t, gRPCClientHandshake, lisAddr) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("c.ClientHandshake(_, %v, _) = %v, want %v.", lisAddr, clientAuthInfo, serverAuthInfo) - } -} - -func TestServerHandshakeReturnsAuthInfo(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, gRPCServerHandshake, done) - defer lis.Close() - clientAuthInfo := clientHandle(t, tlsClientHandshake, lis.Addr().String()) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("ServerHandshake(_) = %v, want %v.", serverAuthInfo, clientAuthInfo) - } -} - -func TestServerAndClientHandshake(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, gRPCServerHandshake, done) - defer lis.Close() - clientAuthInfo := clientHandle(t, gRPCClientHandshake, lis.Addr().String()) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("AuthInfo returned by server: %v and client: %v aren't same", serverAuthInfo, clientAuthInfo) - } -} - -func compare(a1, a2 AuthInfo) bool { - if a1.AuthType() != a2.AuthType() { - return false - } - switch a1.AuthType() { - case "tls": - state1 := a1.(TLSInfo).State - state2 := a2.(TLSInfo).State - if state1.Version == state2.Version && - state1.HandshakeComplete == state2.HandshakeComplete && - state1.CipherSuite == state2.CipherSuite && - state1.NegotiatedProtocol == state2.NegotiatedProtocol { - return true - } - return false - default: - return false - } -} - -func launchServer(t *testing.T, hs serverHandshake, done chan AuthInfo) net.Listener { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - go serverHandle(t, hs, done, lis) - return lis -} - -// Is run in a separate goroutine. -func serverHandle(t *testing.T, hs serverHandshake, done chan AuthInfo, lis net.Listener) { - serverRawConn, err := lis.Accept() - if err != nil { - t.Errorf("Server failed to accept connection: %v", err) - close(done) - return - } - serverAuthInfo, err := hs(serverRawConn) - if err != nil { - t.Errorf("Server failed while handshake. Error: %v", err) - serverRawConn.Close() - close(done) - return - } - done <- serverAuthInfo -} - -func clientHandle(t *testing.T, hs func(net.Conn, string) (AuthInfo, error), lisAddr string) AuthInfo { - conn, err := net.Dial("tcp", lisAddr) - if err != nil { - t.Fatalf("Client failed to connect to %s. Error: %v", lisAddr, err) - } - defer conn.Close() - clientAuthInfo, err := hs(conn, lisAddr) - if err != nil { - t.Fatalf("Error on client while handshake. Error: %v", err) - } - return clientAuthInfo -} - -// Server handshake implementation in gRPC. -func gRPCServerHandshake(conn net.Conn) (AuthInfo, error) { - serverTLS, err := NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - return nil, err - } - _, serverAuthInfo, err := serverTLS.ServerHandshake(conn) - if err != nil { - return nil, err - } - return serverAuthInfo, nil -} - -// Client handshake implementation in gRPC. -func gRPCClientHandshake(conn net.Conn, lisAddr string) (AuthInfo, error) { - clientTLS := NewTLS(&tls.Config{InsecureSkipVerify: true}) - _, authInfo, err := clientTLS.ClientHandshake(context.Background(), lisAddr, conn) - if err != nil { - return nil, err - } - return authInfo, nil -} - -func tlsServerHandshake(conn net.Conn) (AuthInfo, error) { - cert, err := tls.LoadX509KeyPair(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - return nil, err - } - serverTLSConfig := &tls.Config{Certificates: []tls.Certificate{cert}} - serverConn := tls.Server(conn, serverTLSConfig) - err = serverConn.Handshake() - if err != nil { - return nil, err - } - return TLSInfo{State: serverConn.ConnectionState()}, nil -} - -func tlsClientHandshake(conn net.Conn, _ string) (AuthInfo, error) { - clientTLSConfig := &tls.Config{InsecureSkipVerify: true} - clientConn := tls.Client(conn, clientTLSConfig) - if err := clientConn.Handshake(); err != nil { - return nil, err - } - return TLSInfo{State: clientConn.ConnectionState()}, nil -} diff --git a/examples/google.golang.org/grpc/credentials/credentials_util_go17.go b/examples/google.golang.org/grpc/credentials/credentials_util_go17.go deleted file mode 100755 index 60409aa..0000000 --- a/examples/google.golang.org/grpc/credentials/credentials_util_go17.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build go1.7 -// +build !go1.8 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - SessionTicketsDisabled: cfg.SessionTicketsDisabled, - SessionTicketKey: cfg.SessionTicketKey, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled, - Renegotiation: cfg.Renegotiation, - } -} diff --git a/examples/google.golang.org/grpc/credentials/credentials_util_go18.go b/examples/google.golang.org/grpc/credentials/credentials_util_go18.go deleted file mode 100755 index 93f0e1d..0000000 --- a/examples/google.golang.org/grpc/credentials/credentials_util_go18.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - - return cfg.Clone() -} diff --git a/examples/google.golang.org/grpc/credentials/credentials_util_pre_go17.go b/examples/google.golang.org/grpc/credentials/credentials_util_pre_go17.go deleted file mode 100755 index d6bbcc9..0000000 --- a/examples/google.golang.org/grpc/credentials/credentials_util_pre_go17.go +++ /dev/null @@ -1,57 +0,0 @@ -// +build !go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package credentials - -import ( - "crypto/tls" -) - -// cloneTLSConfig returns a shallow clone of the exported -// fields of cfg, ignoring the unexported sync.Once, which -// contains a mutex and must not be copied. -// -// If cfg is nil, a new zero tls.Config is returned. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - SessionTicketsDisabled: cfg.SessionTicketsDisabled, - SessionTicketKey: cfg.SessionTicketKey, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - } -} diff --git a/examples/google.golang.org/grpc/credentials/oauth/oauth.go b/examples/google.golang.org/grpc/credentials/oauth/oauth.go deleted file mode 100755 index f6d597a..0000000 --- a/examples/google.golang.org/grpc/credentials/oauth/oauth.go +++ /dev/null @@ -1,173 +0,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. - * - */ - -// Package oauth implements gRPC credentials using OAuth. -package oauth - -import ( - "fmt" - "io/ioutil" - "sync" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/grpc/credentials" -) - -// TokenSource supplies PerRPCCredentials from an oauth2.TokenSource. -type TokenSource struct { - oauth2.TokenSource -} - -// GetRequestMetadata gets the request metadata as a map from a TokenSource. -func (ts TokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -// RequireTransportSecurity indicates whether the credentials requires transport security. -func (ts TokenSource) RequireTransportSecurity() bool { - return true -} - -type jwtAccess struct { - jsonKey []byte -} - -// NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile. -func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewJWTAccessFromKey(jsonKey) -} - -// NewJWTAccessFromKey creates PerRPCCredentials from the given jsonKey. -func NewJWTAccessFromKey(jsonKey []byte) (credentials.PerRPCCredentials, error) { - return jwtAccess{jsonKey}, nil -} - -func (j jwtAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - ts, err := google.JWTAccessTokenSourceFromJSON(j.jsonKey, uri[0]) - if err != nil { - return nil, err - } - token, err := ts.Token() - if err != nil { - return nil, err - } - return map[string]string{ - "authorization": token.Type() + " " + token.AccessToken, - }, nil -} - -func (j jwtAccess) RequireTransportSecurity() bool { - return true -} - -// oauthAccess supplies PerRPCCredentials from a given token. -type oauthAccess struct { - token oauth2.Token -} - -// NewOauthAccess constructs the PerRPCCredentials using a given token. -func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials { - return oauthAccess{token: *token} -} - -func (oa oauthAccess) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return map[string]string{ - "authorization": oa.token.Type() + " " + oa.token.AccessToken, - }, nil -} - -func (oa oauthAccess) RequireTransportSecurity() bool { - return true -} - -// NewComputeEngine constructs the PerRPCCredentials that fetches access tokens from -// Google Compute Engine (GCE)'s metadata server. It is only valid to use this -// if your program is running on a GCE instance. -// TODO(dsymonds): Deprecate and remove this. -func NewComputeEngine() credentials.PerRPCCredentials { - return TokenSource{google.ComputeTokenSource("")} -} - -// serviceAccount represents PerRPCCredentials via JWT signing key. -type serviceAccount struct { - mu sync.Mutex - config *jwt.Config - t *oauth2.Token -} - -func (s *serviceAccount) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - s.mu.Lock() - defer s.mu.Unlock() - if !s.t.Valid() { - var err error - s.t, err = s.config.TokenSource(ctx).Token() - if err != nil { - return nil, err - } - } - return map[string]string{ - "authorization": s.t.Type() + " " + s.t.AccessToken, - }, nil -} - -func (s *serviceAccount) RequireTransportSecurity() bool { - return true -} - -// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice -// from a Google Developers service account. -func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) { - config, err := google.JWTConfigFromJSON(jsonKey, scope...) - if err != nil { - return nil, err - } - return &serviceAccount{config: config}, nil -} - -// NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file -// of a Google Developers service account. -func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) - } - return NewServiceAccountFromKey(jsonKey, scope...) -} - -// NewApplicationDefault returns "Application Default Credentials". For more -// detail, see https://developers.google.com/accounts/docs/application-default-credentials. -func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) { - t, err := google.DefaultTokenSource(ctx, scope...) - if err != nil { - return nil, err - } - return TokenSource{t}, nil -} diff --git a/examples/google.golang.org/grpc/doc.go b/examples/google.golang.org/grpc/doc.go deleted file mode 100755 index 187adbb..0000000 --- a/examples/google.golang.org/grpc/doc.go +++ /dev/null @@ -1,24 +0,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. - * - */ - -/* -Package grpc implements an RPC system called gRPC. - -See grpc.io for more information about gRPC. -*/ -package grpc // import "google.golang.org/grpc" diff --git a/examples/google.golang.org/grpc/encoding/encoding.go b/examples/google.golang.org/grpc/encoding/encoding.go deleted file mode 100755 index ade8b7c..0000000 --- a/examples/google.golang.org/grpc/encoding/encoding.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package encoding defines the interface for the compressor and codec, and -// functions to register and retrieve compressors and codecs. -// -// This package is EXPERIMENTAL. -package encoding - -import ( - "io" - "strings" -) - -// Identity specifies the optional encoding for uncompressed streams. -// It is intended for grpc internal use only. -const Identity = "identity" - -// Compressor is used for compressing and decompressing when sending or -// receiving messages. -type Compressor interface { - // Compress writes the data written to wc to w after compressing it. If an - // error occurs while initializing the compressor, that error is returned - // instead. - Compress(w io.Writer) (io.WriteCloser, error) - // Decompress reads data from r, decompresses it, and provides the - // uncompressed data via the returned io.Reader. If an error occurs while - // initializing the decompressor, that error is returned instead. - Decompress(r io.Reader) (io.Reader, error) - // Name is the name of the compression codec and is used to set the content - // coding header. The result must be static; the result cannot change - // between calls. - Name() string -} - -var registeredCompressor = make(map[string]Compressor) - -// RegisterCompressor registers the compressor with gRPC by its name. It can -// be activated when sending an RPC via grpc.UseCompressor(). It will be -// automatically accessed when receiving a message based on the content coding -// header. Servers also use it to send a response with the same encoding as -// the request. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Compressors are -// registered with the same name, the one registered last will take effect. -func RegisterCompressor(c Compressor) { - registeredCompressor[c.Name()] = c -} - -// GetCompressor returns Compressor for the given compressor name. -func GetCompressor(name string) Compressor { - return registeredCompressor[name] -} - -// Codec defines the interface gRPC uses to encode and decode messages. Note -// that implementations of this interface must be thread safe; a Codec's -// methods can be called from concurrent goroutines. -type Codec interface { - // Marshal returns the wire format of v. - Marshal(v interface{}) ([]byte, error) - // Unmarshal parses the wire format into v. - Unmarshal(data []byte, v interface{}) error - // Name returns the name of the Codec implementation. The returned string - // will be used as part of content type in transmission. The result must be - // static; the result cannot change between calls. - Name() string -} - -var registeredCodecs = make(map[string]Codec) - -// RegisterCodec registers the provided Codec for use with all gRPC clients and -// servers. -// -// The Codec will be stored and looked up by result of its Name() method, which -// should match the content-subtype of the encoding handled by the Codec. This -// is case-insensitive, and is stored and looked up as lowercase. If the -// result of calling Name() is an empty string, RegisterCodec will panic. See -// Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Compressors are -// registered with the same name, the one registered last will take effect. -func RegisterCodec(codec Codec) { - if codec == nil { - panic("cannot register a nil Codec") - } - contentSubtype := strings.ToLower(codec.Name()) - if contentSubtype == "" { - panic("cannot register Codec with empty string result for String()") - } - registeredCodecs[contentSubtype] = codec -} - -// GetCodec gets a registered Codec by content-subtype, or nil if no Codec is -// registered for the content-subtype. -// -// The content-subtype is expected to be lowercase. -func GetCodec(contentSubtype string) Codec { - return registeredCodecs[contentSubtype] -} diff --git a/examples/google.golang.org/grpc/encoding/gzip/gzip.go b/examples/google.golang.org/grpc/encoding/gzip/gzip.go deleted file mode 100755 index 09564db..0000000 --- a/examples/google.golang.org/grpc/encoding/gzip/gzip.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package gzip implements and registers the gzip compressor -// during the initialization. -// This package is EXPERIMENTAL. -package gzip - -import ( - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "sync" - - "google.golang.org/grpc/encoding" -) - -// Name is the name registered for the gzip compressor. -const Name = "gzip" - -func init() { - c := &compressor{} - c.poolCompressor.New = func() interface{} { - return &writer{Writer: gzip.NewWriter(ioutil.Discard), pool: &c.poolCompressor} - } - encoding.RegisterCompressor(c) -} - -type writer struct { - *gzip.Writer - pool *sync.Pool -} - -// SetLevel updates the registered gzip compressor to use the compression level specified (gzip.HuffmanOnly is not supported). -// NOTE: this function must only be called during initialization time (i.e. in an init() function), -// and is not thread-safe. -// -// The error returned will be nil if the specified level is valid. -func SetLevel(level int) error { - if level < gzip.DefaultCompression || level > gzip.BestCompression { - return fmt.Errorf("grpc: invalid gzip compression level: %d", level) - } - c := encoding.GetCompressor(Name).(*compressor) - c.poolCompressor.New = func() interface{} { - w, err := gzip.NewWriterLevel(ioutil.Discard, level) - if err != nil { - panic(err) - } - return &writer{Writer: w, pool: &c.poolCompressor} - } - return nil -} - -func (c *compressor) Compress(w io.Writer) (io.WriteCloser, error) { - z := c.poolCompressor.Get().(*writer) - z.Writer.Reset(w) - return z, nil -} - -func (z *writer) Close() error { - defer z.pool.Put(z) - return z.Writer.Close() -} - -type reader struct { - *gzip.Reader - pool *sync.Pool -} - -func (c *compressor) Decompress(r io.Reader) (io.Reader, error) { - z, inPool := c.poolDecompressor.Get().(*reader) - if !inPool { - newZ, err := gzip.NewReader(r) - if err != nil { - return nil, err - } - return &reader{Reader: newZ, pool: &c.poolDecompressor}, nil - } - if err := z.Reset(r); err != nil { - c.poolDecompressor.Put(z) - return nil, err - } - return z, nil -} - -func (z *reader) Read(p []byte) (n int, err error) { - n, err = z.Reader.Read(p) - if err == io.EOF { - z.pool.Put(z) - } - return n, err -} - -func (c *compressor) Name() string { - return Name -} - -type compressor struct { - poolCompressor sync.Pool - poolDecompressor sync.Pool -} diff --git a/examples/google.golang.org/grpc/encoding/proto/proto.go b/examples/google.golang.org/grpc/encoding/proto/proto.go deleted file mode 100755 index 66b97a6..0000000 --- a/examples/google.golang.org/grpc/encoding/proto/proto.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * - * 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. - * - */ - -// Package proto defines the protobuf codec. Importing this package will -// register the codec. -package proto - -import ( - "math" - "sync" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/encoding" -) - -// Name is the name registered for the proto compressor. -const Name = "proto" - -func init() { - encoding.RegisterCodec(codec{}) -} - -// codec is a Codec implementation with protobuf. It is the default codec for gRPC. -type codec struct{} - -type cachedProtoBuffer struct { - lastMarshaledSize uint32 - proto.Buffer -} - -func capToMaxInt32(val int) uint32 { - if val > math.MaxInt32 { - return uint32(math.MaxInt32) - } - return uint32(val) -} - -func marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) { - protoMsg := v.(proto.Message) - newSlice := make([]byte, 0, cb.lastMarshaledSize) - - cb.SetBuf(newSlice) - cb.Reset() - if err := cb.Marshal(protoMsg); err != nil { - return nil, err - } - out := cb.Bytes() - cb.lastMarshaledSize = capToMaxInt32(len(out)) - return out, nil -} - -func (codec) Marshal(v interface{}) ([]byte, error) { - if pm, ok := v.(proto.Marshaler); ok { - // object can marshal itself, no need for buffer - return pm.Marshal() - } - - cb := protoBufferPool.Get().(*cachedProtoBuffer) - out, err := marshal(v, cb) - - // put back buffer and lose the ref to the slice - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return out, err -} - -func (codec) Unmarshal(data []byte, v interface{}) error { - protoMsg := v.(proto.Message) - protoMsg.Reset() - - if pu, ok := protoMsg.(proto.Unmarshaler); ok { - // object can unmarshal itself, no need for buffer - return pu.Unmarshal(data) - } - - cb := protoBufferPool.Get().(*cachedProtoBuffer) - cb.SetBuf(data) - err := cb.Unmarshal(protoMsg) - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return err -} - -func (codec) Name() string { - return Name -} - -var protoBufferPool = &sync.Pool{ - New: func() interface{} { - return &cachedProtoBuffer{ - Buffer: proto.Buffer{}, - lastMarshaledSize: 16, - } - }, -} diff --git a/examples/google.golang.org/grpc/encoding/proto/proto_benchmark_test.go b/examples/google.golang.org/grpc/encoding/proto/proto_benchmark_test.go deleted file mode 100755 index 63ea57d..0000000 --- a/examples/google.golang.org/grpc/encoding/proto/proto_benchmark_test.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package proto - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/test/codec_perf" -) - -func setupBenchmarkProtoCodecInputs(payloadBaseSize uint32) []proto.Message { - payloadBase := make([]byte, payloadBaseSize) - // arbitrary byte slices - payloadSuffixes := [][]byte{ - []byte("one"), - []byte("two"), - []byte("three"), - []byte("four"), - []byte("five"), - } - protoStructs := make([]proto.Message, 0) - - for _, p := range payloadSuffixes { - ps := &codec_perf.Buffer{} - ps.Body = append(payloadBase, p...) - protoStructs = append(protoStructs, ps) - } - - return protoStructs -} - -// The possible use of certain protobuf APIs like the proto.Buffer API potentially involves caching -// on our side. This can add checks around memory allocations and possible contention. -// Example run: go test -v -run=^$ -bench=BenchmarkProtoCodec -benchmem -func BenchmarkProtoCodec(b *testing.B) { - // range of message sizes - payloadBaseSizes := make([]uint32, 0) - for i := uint32(0); i <= 12; i += 4 { - payloadBaseSizes = append(payloadBaseSizes, 1< -## Creating the server - -First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client) (though you might find it interesting anyway!). - -There are two parts to making our `RouteGuide` service do its job: -- Implementing the service interface generated from our service definition: doing the actual "work" of our service. -- Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation. - -You can find our example `RouteGuide` server in [grpc-go/examples/route_guide/server/server.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/server/server.go). Let's take a closer look at how it works. - -### Implementing RouteGuide - -As you can see, our server has a `routeGuideServer` struct type that implements the generated `RouteGuideServer` interface: - -```go -type routeGuideServer struct { - ... -} -... - -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - ... -} -... - -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - ... -} -... - -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - ... -} -... - -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - ... -} -... -``` - -#### Simple RPC -`routeGuideServer` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`. - -```go -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - return feature, nil - } - } - // No feature was found, return an unnamed feature - return &pb.Feature{"", point}, nil -} -``` - -The method is passed a context object for the RPC and the client's `Point` protocol buffer request. It returns a `Feature` protocol buffer object with the response information and an `error`. In the method we populate the `Feature` with the appropriate information, and then `return` it along with an `nil` error to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client. - -#### Server-side streaming RPC -Now let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client. - -```go -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - for _, feature := range s.savedFeatures { - if inRange(feature.Location, rect) { - if err := stream.Send(feature); err != nil { - return err - } - } - } - return nil -} -``` - -As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `RouteGuide_ListFeaturesServer` object to write our responses. - -In the method, we populate as many `Feature` objects as we need to return, writing them to the `RouteGuide_ListFeaturesServer` using its `Send()` method. Finally, as in our simple RPC, we return a `nil` error to tell gRPC that we've finished writing responses. Should any error happen in this call, we return a non-`nil` error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire. - -#### Client-side streaming RPC -Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. As you can see, this time the method doesn't have a request parameter at all. Instead, it gets a `RouteGuide_RecordRouteServer` stream, which the server can use to both read *and* write messages - it can receive client messages using its `Recv()` method and return its single response using its `SendAndClose()` method. - -```go -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - var pointCount, featureCount, distance int32 - var lastPoint *pb.Point - startTime := time.Now() - for { - point, err := stream.Recv() - if err == io.EOF { - endTime := time.Now() - return stream.SendAndClose(&pb.RouteSummary{ - PointCount: pointCount, - FeatureCount: featureCount, - Distance: distance, - ElapsedTime: int32(endTime.Sub(startTime).Seconds()), - }) - } - if err != nil { - return err - } - pointCount++ - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - featureCount++ - } - } - if lastPoint != nil { - distance += calcDistance(lastPoint, point) - } - lastPoint = point - } -} -``` - -In the method body we use the `RouteGuide_RecordRouteServer`s `Recv()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the the error returned from `Recv()` after each call. If this is `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended and the server can return its `RouteSummary`. If it has any other value, we return the error "as is" so that it'll be translated to an RPC status by the gRPC layer. - -#### Bidirectional streaming RPC -Finally, let's look at our bidirectional streaming RPC `RouteChat()`. - -```go -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - key := serialize(in.Location) - ... // look for notes to be sent to client - for _, note := range s.routeNotes[key] { - if err := stream.Send(note); err != nil { - return err - } - } - } -} -``` - -This time we get a `RouteGuide_RouteChatServer` stream that, as in our client-side streaming example, can be used to read and write messages. However, this time we return values via our method's stream while the client is still writing messages to *their* message stream. - -The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream's `Send()` method rather than `SendAndClose()` because it's writing multiple responses. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. - -### Starting the server - -Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service: - -```go -flag.Parse() -lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port)) -if err != nil { - log.Fatalf("failed to listen: %v", err) -} -grpcServer := grpc.NewServer() -pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{}) -... // determine whether to use TLS -grpcServer.Serve(lis) -``` -To build and start a server, we: - -1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))`. -2. Create an instance of the gRPC server using `grpc.NewServer()`. -3. Register our service implementation with the gRPC server. -4. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called. - - -## Creating the client - -In this section, we'll look at creating a Go client for our `RouteGuide` service. You can see our complete example client code in [grpc-go/examples/route_guide/client/client.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/client/client.go). - -### Creating a stub - -To call service methods, we first need to create a gRPC *channel* to communicate with the server. We create this by passing the server address and port number to `grpc.Dial()` as follows: - -```go -conn, err := grpc.Dial(*serverAddr) -if err != nil { - ... -} -defer conn.Close() -``` - -You can use `DialOptions` to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in `grpc.Dial` if the service you request requires that - however, we don't need to do this for our `RouteGuide` service. - -Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs. We get this using the `NewRouteGuideClient` method provided in the `pb` package we generated from our `.proto` file. - -```go -client := pb.NewRouteGuideClient(conn) -``` - -### Calling service methods - -Now let's look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error. - -#### Simple RPC - -Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method. - -```go -feature, err := client.GetFeature(ctx, &pb.Point{409146138, -746188906}) -if err != nil { - ... -} -``` - -As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which lets us change our RPC's behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn't return an error, then we can read the response information from the server from the first return value. - -```go -log.Println(feature) -``` - -#### Server-side streaming RPC - -Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides. - -```go -rect := &pb.Rectangle{ ... } // initialize a pb.Rectangle -stream, err := client.ListFeatures(ctx, rect) -if err != nil { - ... -} -for { - feature, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(feature) -} -``` - -As in the simple RPC, we pass the method a context and a request. However, instead of getting a response object back, we get back an instance of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses. - -We use the `RouteGuide_ListFeaturesClient`'s `Recv()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the error `err` returned from `Recv()` after each call. If `nil`, the stream is still good and it can continue reading; if it's `io.EOF` then the message stream has ended; otherwise there must be an RPC error, which is passed over through `err`. - -#### Client-side streaming RPC - -The client-side streaming method `RecordRoute` is similar to the server-side method, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` stream back, which we can use to both write *and* read messages. - -```go -// Create a random number of random points -r := rand.New(rand.NewSource(time.Now().UnixNano())) -pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points -var points []*pb.Point -for i := 0; i < pointCount; i++ { - points = append(points, randomPoint(r)) -} -log.Printf("Traversing %d points.", len(points)) -stream, err := client.RecordRoute(ctx) -if err != nil { - log.Fatalf("%v.RecordRoute(_) = _, %v", client, err) -} -for _, point := range points { - if err := stream.Send(point); err != nil { - log.Fatalf("%v.Send(%v) = %v", stream, point, err) - } -} -reply, err := stream.CloseAndRecv() -if err != nil { - log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) -} -log.Printf("Route summary: %v", reply) -``` - -The `RouteGuide_RecordRouteClient` has a `Send()` method that we can use to send requests to the server. Once we've finished writing our client's requests to the stream using `Send()`, we need to call `CloseAndRecv()` on the stream to let gRPC know that we've finished writing and are expecting to receive a response. We get our RPC status from the `err` returned from `CloseAndRecv()`. If the status is `nil`, then the first return value from `CloseAndRecv()` will be a valid server response. - -#### Bidirectional streaming RPC - -Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method's stream while the server is still writing messages to *their* message stream. - -```go -stream, err := client.RouteChat(ctx) -waitc := make(chan struct{}) -go func() { - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - close(waitc) - return - } - if err != nil { - log.Fatalf("Failed to receive a note : %v", err) - } - log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude) - } -}() -for _, note := range notes { - if err := stream.Send(note); err != nil { - log.Fatalf("Failed to send a note: %v", err) - } -} -stream.CloseSend() -<-waitc -``` - -The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream's `CloseSend()` method once we've finished our call. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently. - -## Try it out! - -To compile and run the server, assuming you are in the folder -`$GOPATH/src/google.golang.org/grpc/examples/route_guide`, simply: - -```sh -$ go run server/server.go -``` - -Likewise, to run the client: - -```sh -$ go run client/client.go -``` - diff --git a/examples/google.golang.org/grpc/examples/helloworld/greeter_client/main.go b/examples/google.golang.org/grpc/examples/helloworld/greeter_client/main.go deleted file mode 100755 index 4b99ff5..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/greeter_client/main.go +++ /dev/null @@ -1,57 +0,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. - * - */ - -package main - -import ( - "log" - "os" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" -) - -const ( - address = "localhost:50051" - defaultName = "world" -) - -func main() { - // Set up a connection to the server. - conn, err := grpc.Dial(address, grpc.WithInsecure()) - if err != nil { - log.Fatalf("did not connect: %v", err) - } - defer conn.Close() - c := pb.NewGreeterClient(conn) - - // Contact the server and print out its response. - name := defaultName - if len(os.Args) > 1 { - name = os.Args[1] - } - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) - if err != nil { - log.Fatalf("could not greet: %v", err) - } - log.Printf("Greeting: %s", r.Message) -} diff --git a/examples/google.golang.org/grpc/examples/helloworld/greeter_server/main.go b/examples/google.golang.org/grpc/examples/helloworld/greeter_server/main.go deleted file mode 100755 index 702a3b6..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/greeter_server/main.go +++ /dev/null @@ -1,57 +0,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. - * - */ - -//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto - -package main - -import ( - "log" - "net" - - "golang.org/x/net/context" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" - "google.golang.org/grpc/reflection" -) - -const ( - port = ":50051" -) - -// server is used to implement helloworld.GreeterServer. -type server struct{} - -// SayHello implements helloworld.GreeterServer -func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { - return &pb.HelloReply{Message: "Hello " + in.Name}, nil -} - -func main() { - lis, err := net.Listen("tcp", port) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - s := grpc.NewServer() - pb.RegisterGreeterServer(s, &server{}) - // Register reflection service on gRPC server. - reflection.Register(s) - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -} diff --git a/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go b/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go deleted file mode 100755 index 11383d7..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.pb.go +++ /dev/null @@ -1,198 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: helloworld.proto - -package helloworld - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The request message containing the user's name. -type HelloRequest struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HelloRequest) Reset() { *m = HelloRequest{} } -func (m *HelloRequest) String() string { return proto.CompactTextString(m) } -func (*HelloRequest) ProtoMessage() {} -func (*HelloRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_helloworld_71e208cbdc16936b, []int{0} -} -func (m *HelloRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HelloRequest.Unmarshal(m, b) -} -func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) -} -func (dst *HelloRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_HelloRequest.Merge(dst, src) -} -func (m *HelloRequest) XXX_Size() int { - return xxx_messageInfo_HelloRequest.Size(m) -} -func (m *HelloRequest) XXX_DiscardUnknown() { - xxx_messageInfo_HelloRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_HelloRequest proto.InternalMessageInfo - -func (m *HelloRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// The response message containing the greetings -type HelloReply struct { - Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HelloReply) Reset() { *m = HelloReply{} } -func (m *HelloReply) String() string { return proto.CompactTextString(m) } -func (*HelloReply) ProtoMessage() {} -func (*HelloReply) Descriptor() ([]byte, []int) { - return fileDescriptor_helloworld_71e208cbdc16936b, []int{1} -} -func (m *HelloReply) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HelloReply.Unmarshal(m, b) -} -func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) -} -func (dst *HelloReply) XXX_Merge(src proto.Message) { - xxx_messageInfo_HelloReply.Merge(dst, src) -} -func (m *HelloReply) XXX_Size() int { - return xxx_messageInfo_HelloReply.Size(m) -} -func (m *HelloReply) XXX_DiscardUnknown() { - xxx_messageInfo_HelloReply.DiscardUnknown(m) -} - -var xxx_messageInfo_HelloReply proto.InternalMessageInfo - -func (m *HelloReply) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -func init() { - proto.RegisterType((*HelloRequest)(nil), "helloworld.HelloRequest") - proto.RegisterType((*HelloReply)(nil), "helloworld.HelloReply") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// GreeterClient is the client API for Greeter service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type GreeterClient interface { - // Sends a greeting - SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) -} - -type greeterClient struct { - cc *grpc.ClientConn -} - -func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { - return &greeterClient{cc} -} - -func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { - out := new(HelloReply) - err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// GreeterServer is the server API for Greeter service. -type GreeterServer interface { - // Sends a greeting - SayHello(context.Context, *HelloRequest) (*HelloReply, error) -} - -func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { - s.RegisterService(&_Greeter_serviceDesc, srv) -} - -func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HelloRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(GreeterServer).SayHello(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/helloworld.Greeter/SayHello", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Greeter_serviceDesc = grpc.ServiceDesc{ - ServiceName: "helloworld.Greeter", - HandlerType: (*GreeterServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "SayHello", - Handler: _Greeter_SayHello_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "helloworld.proto", -} - -func init() { proto.RegisterFile("helloworld.proto", fileDescriptor_helloworld_71e208cbdc16936b) } - -var fileDescriptor_helloworld_71e208cbdc16936b = []byte{ - // 175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xc8, 0x48, 0xcd, 0xc9, - 0xc9, 0x2f, 0xcf, 0x2f, 0xca, 0x49, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, - 0x28, 0x29, 0x71, 0xf1, 0x78, 0x80, 0x78, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0x42, - 0x5c, 0x2c, 0x79, 0x89, 0xb9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x92, - 0x1a, 0x17, 0x17, 0x54, 0x4d, 0x41, 0x4e, 0xa5, 0x90, 0x04, 0x17, 0x7b, 0x6e, 0x6a, 0x71, 0x71, - 0x62, 0x3a, 0x4c, 0x11, 0x8c, 0x6b, 0xe4, 0xc9, 0xc5, 0xee, 0x5e, 0x94, 0x9a, 0x5a, 0x92, 0x5a, - 0x24, 0x64, 0xc7, 0xc5, 0x11, 0x9c, 0x58, 0x09, 0xd6, 0x25, 0x24, 0xa1, 0x87, 0xe4, 0x02, 0x64, - 0xcb, 0xa4, 0xc4, 0xb0, 0xc8, 0x14, 0xe4, 0x54, 0x2a, 0x31, 0x38, 0x19, 0x70, 0x49, 0x67, 0xe6, - 0xeb, 0xa5, 0x17, 0x15, 0x24, 0xeb, 0xa5, 0x56, 0x24, 0xe6, 0x16, 0xe4, 0xa4, 0x16, 0x23, 0xa9, - 0x75, 0xe2, 0x07, 0x2b, 0x0e, 0x07, 0xb1, 0x03, 0x40, 0x5e, 0x0a, 0x60, 0x4c, 0x62, 0x03, 0xfb, - 0xcd, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x0f, 0xb7, 0xcd, 0xf2, 0xef, 0x00, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto b/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto deleted file mode 100755 index d79a6a0..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/helloworld/helloworld.proto +++ /dev/null @@ -1,37 +0,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. - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "io.grpc.examples.helloworld"; -option java_outer_classname = "HelloWorldProto"; - -package helloworld; - -// The greeting service definition. -service Greeter { - // Sends a greeting - rpc SayHello (HelloRequest) returns (HelloReply) {} -} - -// The request message containing the user's name. -message HelloRequest { - string name = 1; -} - -// The response message containing the greetings -message HelloReply { - string message = 1; -} diff --git a/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go b/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go deleted file mode 100755 index 14957ed..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock.go +++ /dev/null @@ -1,48 +0,0 @@ -// Automatically generated by MockGen. DO NOT EDIT! -// Source: google.golang.org/grpc/examples/helloworld/helloworld (interfaces: GreeterClient) - -package mock_helloworld - -import ( - gomock "github.com/golang/mock/gomock" - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" - helloworld "google.golang.org/grpc/examples/helloworld/helloworld" -) - -// Mock of GreeterClient interface -type MockGreeterClient struct { - ctrl *gomock.Controller - recorder *_MockGreeterClientRecorder -} - -// Recorder for MockGreeterClient (not exported) -type _MockGreeterClientRecorder struct { - mock *MockGreeterClient -} - -func NewMockGreeterClient(ctrl *gomock.Controller) *MockGreeterClient { - mock := &MockGreeterClient{ctrl: ctrl} - mock.recorder = &_MockGreeterClientRecorder{mock} - return mock -} - -func (_m *MockGreeterClient) EXPECT() *_MockGreeterClientRecorder { - return _m.recorder -} - -func (_m *MockGreeterClient) SayHello(_param0 context.Context, _param1 *helloworld.HelloRequest, _param2 ...grpc.CallOption) (*helloworld.HelloReply, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "SayHello", _s...) - ret0, _ := ret[0].(*helloworld.HelloReply) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockGreeterClientRecorder) SayHello(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "SayHello", _s...) -} diff --git a/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go b/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go deleted file mode 100755 index 3966763..0000000 --- a/examples/google.golang.org/grpc/examples/helloworld/mock_helloworld/hw_mock_test.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package mock_helloworld_test - -import ( - "fmt" - "testing" - "time" - - "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - helloworld "google.golang.org/grpc/examples/helloworld/helloworld" - hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld" -) - -// rpcMsg implements the gomock.Matcher interface -type rpcMsg struct { - msg proto.Message -} - -func (r *rpcMsg) Matches(msg interface{}) bool { - m, ok := msg.(proto.Message) - if !ok { - return false - } - return proto.Equal(m, r.msg) -} - -func (r *rpcMsg) String() string { - return fmt.Sprintf("is %s", r.msg) -} - -func TestSayHello(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mockGreeterClient := hwmock.NewMockGreeterClient(ctrl) - req := &helloworld.HelloRequest{Name: "unit_test"} - mockGreeterClient.EXPECT().SayHello( - gomock.Any(), - &rpcMsg{msg: req}, - ).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil) - testSayHello(t, mockGreeterClient) -} - -func testSayHello(t *testing.T, client helloworld.GreeterClient) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - r, err := client.SayHello(ctx, &helloworld.HelloRequest{Name: "unit_test"}) - if err != nil || r.Message != "Mocked Interface" { - t.Errorf("mocking failed") - } - t.Log("Reply : ", r.Message) -} diff --git a/examples/google.golang.org/grpc/examples/oauth/client/main.go b/examples/google.golang.org/grpc/examples/oauth/client/main.go deleted file mode 100755 index d167c43..0000000 --- a/examples/google.golang.org/grpc/examples/oauth/client/main.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// The client demonstrates how to supply an OAuth2 token for every RPC. -package main - -import ( - "crypto/tls" - "log" - "time" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/oauth" - pb "google.golang.org/grpc/examples/helloworld/helloworld" -) - -func main() { - perRPC := oauth.NewOauthAccess(fetchToken()) - opts := []grpc.DialOption{ - // In addition to the following grpc.DialOption, callers may also use - // the grpc.CallOption grpc.PerRPCCredentials with the RPC invocation - // itself. - // See: https://godoc.org/google.golang.org/grpc#PerRPCCredentials - grpc.WithPerRPCCredentials(perRPC), - // oauth.NewOauthAccess requires the configuration of transport - // credentials. - grpc.WithTransportCredentials( - credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}), - ), - } - conn, err := grpc.Dial(":8080", opts...) - if err != nil { - log.Fatalf("did not connect: %v", err) - } - defer conn.Close() - c := pb.NewGreeterClient(conn) - - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "authenticated-client"}) - if err != nil { - log.Fatalf("could not greet: %v", err) - } - log.Printf("Greeting: %s", r.Message) -} - -// fetchToken simulates a token lookup and omits the details of proper token -// acquisition. For examples of how to acquire an OAuth2 token, see: -// https://godoc.org/golang.org/x/oauth2 -func fetchToken() *oauth2.Token { - return &oauth2.Token{ - AccessToken: "some-secret-token", - } -} diff --git a/examples/google.golang.org/grpc/examples/oauth/server/main.go b/examples/google.golang.org/grpc/examples/oauth/server/main.go deleted file mode 100755 index 5135e9d..0000000 --- a/examples/google.golang.org/grpc/examples/oauth/server/main.go +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// The server demonstrates how to consume and validate OAuth2 tokens provided by -// clients for each RPC. -package main - -import ( - "crypto/tls" - "log" - "net" - "strings" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - pb "google.golang.org/grpc/examples/helloworld/helloworld" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" - "google.golang.org/grpc/testdata" -) - -var ( - errMissingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata") - errInvalidToken = status.Errorf(codes.Unauthenticated, "invalid token") -) - -func main() { - log.Println("server starting on port 8080...") - cert, err := tls.LoadX509KeyPair(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - log.Fatalf("failed to load key pair: %s", err) - } - opts := []grpc.ServerOption{ - // The following grpc.ServerOption adds an interceptor for all unary - // RPCs. To configure an interceptor for streaming RPCs, see: - // https://godoc.org/google.golang.org/grpc#StreamInterceptor - grpc.UnaryInterceptor(ensureValidToken), - // Enable TLS for all incoming connections. - grpc.Creds(credentials.NewServerTLSFromCert(&cert)), - } - s := grpc.NewServer(opts...) - pb.RegisterGreeterServer(s, &server{}) - lis, err := net.Listen("tcp", ":8080") - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -} - -// server is used to implement helloworld.GreeterServer. -type server struct{} - -// SayHello implements helloworld.GreeterServer -func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { - return &pb.HelloReply{Message: "Hello " + in.Name}, nil -} - -// valid validates the authorization. -func valid(authorization []string) bool { - if len(authorization) < 1 { - return false - } - token := strings.TrimPrefix(authorization[0], "Bearer ") - // Perform the token validation here. For the sake of this example, the code - // here forgoes any of the usual OAuth2 token validation and instead checks - // for a token matching an arbitrary string. - if token != "some-secret-token" { - return false - } - return true -} - -// ensureValidToken ensures a valid token exists within a request's metadata. If -// the token is missing or invalid, the interceptor blocks execution of the -// handler and returns an error. Otherwise, the interceptor invokes the unary -// handler. -func ensureValidToken(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errMissingMetadata - } - // The keys within metadata.MD are normalized to lowercase. - // See: https://godoc.org/google.golang.org/grpc/metadata#New - if !valid(md["authorization"]) { - return nil, errInvalidToken - } - // Continue execution of handler after ensuring a valid token. - return handler(ctx, req) -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/README.md b/examples/google.golang.org/grpc/examples/route_guide/README.md deleted file mode 100755 index ddec3a0..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Description -The route guide server and client demonstrate how to use grpc go libraries to -perform unary, client streaming, server streaming and full duplex RPCs. - -Please refer to [gRPC Basics: Go](https://grpc.io/docs/tutorials/basic/go.html) for more information. - -See the definition of the route guide service in routeguide/route_guide.proto. - -# Run the sample code -To compile and run the server, assuming you are in the root of the route_guide -folder, i.e., .../examples/route_guide/, simply: - -```sh -$ go run server/server.go -``` - -Likewise, to run the client: - -```sh -$ go run client/client.go -``` - -# Optional command line flags -The server and client both take optional command line flags. For example, the -client and server run without TLS by default. To enable TLS: - -```sh -$ go run server/server.go -tls=true -``` - -and - -```sh -$ go run client/client.go -tls=true -``` diff --git a/examples/google.golang.org/grpc/examples/route_guide/client/client.go b/examples/google.golang.org/grpc/examples/route_guide/client/client.go deleted file mode 100755 index 1ad1c17..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/client/client.go +++ /dev/null @@ -1,192 +0,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. - * - */ - -// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "flag" - "io" - "log" - "math/rand" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - pb "google.golang.org/grpc/examples/route_guide/routeguide" - "google.golang.org/grpc/testdata" -) - -var ( - tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP") - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") - serverAddr = flag.String("server_addr", "127.0.0.1:10000", "The server address in the format of host:port") - serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake") -) - -// printFeature gets the feature for the given point. -func printFeature(client pb.RouteGuideClient, point *pb.Point) { - log.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - feature, err := client.GetFeature(ctx, point) - if err != nil { - log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err) - } - log.Println(feature) -} - -// printFeatures lists all the features within the given bounding Rectangle. -func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) { - log.Printf("Looking for features within %v", rect) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := client.ListFeatures(ctx, rect) - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - for { - feature, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(feature) - } -} - -// runRecordRoute sends a sequence of points to server and expects to get a RouteSummary from server. -func runRecordRoute(client pb.RouteGuideClient) { - // Create a random number of random points - r := rand.New(rand.NewSource(time.Now().UnixNano())) - pointCount := int(r.Int31n(100)) + 2 // Traverse at least two points - var points []*pb.Point - for i := 0; i < pointCount; i++ { - points = append(points, randomPoint(r)) - } - log.Printf("Traversing %d points.", len(points)) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := client.RecordRoute(ctx) - if err != nil { - log.Fatalf("%v.RecordRoute(_) = _, %v", client, err) - } - for _, point := range points { - if err := stream.Send(point); err != nil { - log.Fatalf("%v.Send(%v) = %v", stream, point, err) - } - } - reply, err := stream.CloseAndRecv() - if err != nil { - log.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - log.Printf("Route summary: %v", reply) -} - -// runRouteChat receives a sequence of route notes, while sending notes for various locations. -func runRouteChat(client pb.RouteGuideClient) { - notes := []*pb.RouteNote{ - {Location: &pb.Point{Latitude: 0, Longitude: 1}, Message: "First message"}, - {Location: &pb.Point{Latitude: 0, Longitude: 2}, Message: "Second message"}, - {Location: &pb.Point{Latitude: 0, Longitude: 3}, Message: "Third message"}, - {Location: &pb.Point{Latitude: 0, Longitude: 1}, Message: "Fourth message"}, - {Location: &pb.Point{Latitude: 0, Longitude: 2}, Message: "Fifth message"}, - {Location: &pb.Point{Latitude: 0, Longitude: 3}, Message: "Sixth message"}, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := client.RouteChat(ctx) - if err != nil { - log.Fatalf("%v.RouteChat(_) = _, %v", client, err) - } - waitc := make(chan struct{}) - go func() { - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - close(waitc) - return - } - if err != nil { - log.Fatalf("Failed to receive a note : %v", err) - } - log.Printf("Got message %s at point(%d, %d)", in.Message, in.Location.Latitude, in.Location.Longitude) - } - }() - for _, note := range notes { - if err := stream.Send(note); err != nil { - log.Fatalf("Failed to send a note: %v", err) - } - } - stream.CloseSend() - <-waitc -} - -func randomPoint(r *rand.Rand) *pb.Point { - lat := (r.Int31n(180) - 90) * 1e7 - long := (r.Int31n(360) - 180) * 1e7 - return &pb.Point{Latitude: lat, Longitude: long} -} - -func main() { - flag.Parse() - var opts []grpc.DialOption - if *tls { - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err := credentials.NewClientTLSFromFile(*caFile, *serverHostOverride) - if err != nil { - log.Fatalf("Failed to create TLS credentials %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - conn, err := grpc.Dial(*serverAddr, opts...) - if err != nil { - log.Fatalf("fail to dial: %v", err) - } - defer conn.Close() - client := pb.NewRouteGuideClient(conn) - - // Looking for a valid feature - printFeature(client, &pb.Point{Latitude: 409146138, Longitude: -746188906}) - - // Feature missing. - printFeature(client, &pb.Point{Latitude: 0, Longitude: 0}) - - // Looking for features between 40, -75 and 42, -73. - printFeatures(client, &pb.Rectangle{ - Lo: &pb.Point{Latitude: 400000000, Longitude: -750000000}, - Hi: &pb.Point{Latitude: 420000000, Longitude: -730000000}, - }) - - // RecordRoute - runRecordRoute(client) - - // RouteChat - runRouteChat(client) -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go b/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go deleted file mode 100755 index 328c929..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock.go +++ /dev/null @@ -1,200 +0,0 @@ -// Automatically generated by MockGen. DO NOT EDIT! -// Source: google.golang.org/grpc/examples/route_guide/routeguide (interfaces: RouteGuideClient,RouteGuide_RouteChatClient) - -package mock_routeguide - -import ( - gomock "github.com/golang/mock/gomock" - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" - routeguide "google.golang.org/grpc/examples/route_guide/routeguide" - metadata "google.golang.org/grpc/metadata" -) - -// Mock of RouteGuideClient interface -type MockRouteGuideClient struct { - ctrl *gomock.Controller - recorder *_MockRouteGuideClientRecorder -} - -// Recorder for MockRouteGuideClient (not exported) -type _MockRouteGuideClientRecorder struct { - mock *MockRouteGuideClient -} - -func NewMockRouteGuideClient(ctrl *gomock.Controller) *MockRouteGuideClient { - mock := &MockRouteGuideClient{ctrl: ctrl} - mock.recorder = &_MockRouteGuideClientRecorder{mock} - return mock -} - -func (_m *MockRouteGuideClient) EXPECT() *_MockRouteGuideClientRecorder { - return _m.recorder -} - -func (_m *MockRouteGuideClient) GetFeature(_param0 context.Context, _param1 *routeguide.Point, _param2 ...grpc.CallOption) (*routeguide.Feature, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "GetFeature", _s...) - ret0, _ := ret[0].(*routeguide.Feature) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) GetFeature(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "GetFeature", _s...) -} - -func (_m *MockRouteGuideClient) ListFeatures(_param0 context.Context, _param1 *routeguide.Rectangle, _param2 ...grpc.CallOption) (routeguide.RouteGuide_ListFeaturesClient, error) { - _s := []interface{}{_param0, _param1} - for _, _x := range _param2 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "ListFeatures", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_ListFeaturesClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) ListFeatures(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1}, arg2...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "ListFeatures", _s...) -} - -func (_m *MockRouteGuideClient) RecordRoute(_param0 context.Context, _param1 ...grpc.CallOption) (routeguide.RouteGuide_RecordRouteClient, error) { - _s := []interface{}{_param0} - for _, _x := range _param1 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "RecordRoute", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_RecordRouteClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) RecordRoute(arg0 interface{}, arg1 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0}, arg1...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "RecordRoute", _s...) -} - -func (_m *MockRouteGuideClient) RouteChat(_param0 context.Context, _param1 ...grpc.CallOption) (routeguide.RouteGuide_RouteChatClient, error) { - _s := []interface{}{_param0} - for _, _x := range _param1 { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "RouteChat", _s...) - ret0, _ := ret[0].(routeguide.RouteGuide_RouteChatClient) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuideClientRecorder) RouteChat(arg0 interface{}, arg1 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0}, arg1...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "RouteChat", _s...) -} - -// Mock of RouteGuide_RouteChatClient interface -type MockRouteGuide_RouteChatClient struct { - ctrl *gomock.Controller - recorder *_MockRouteGuide_RouteChatClientRecorder -} - -// Recorder for MockRouteGuide_RouteChatClient (not exported) -type _MockRouteGuide_RouteChatClientRecorder struct { - mock *MockRouteGuide_RouteChatClient -} - -func NewMockRouteGuide_RouteChatClient(ctrl *gomock.Controller) *MockRouteGuide_RouteChatClient { - mock := &MockRouteGuide_RouteChatClient{ctrl: ctrl} - mock.recorder = &_MockRouteGuide_RouteChatClientRecorder{mock} - return mock -} - -func (_m *MockRouteGuide_RouteChatClient) EXPECT() *_MockRouteGuide_RouteChatClientRecorder { - return _m.recorder -} - -func (_m *MockRouteGuide_RouteChatClient) CloseSend() error { - ret := _m.ctrl.Call(_m, "CloseSend") - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) CloseSend() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "CloseSend") -} - -func (_m *MockRouteGuide_RouteChatClient) Context() context.Context { - ret := _m.ctrl.Call(_m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Context() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Context") -} - -func (_m *MockRouteGuide_RouteChatClient) Header() (metadata.MD, error) { - ret := _m.ctrl.Call(_m, "Header") - ret0, _ := ret[0].(metadata.MD) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Header() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Header") -} - -func (_m *MockRouteGuide_RouteChatClient) Recv() (*routeguide.RouteNote, error) { - ret := _m.ctrl.Call(_m, "Recv") - ret0, _ := ret[0].(*routeguide.RouteNote) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Recv() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Recv") -} - -func (_m *MockRouteGuide_RouteChatClient) RecvMsg(_param0 interface{}) error { - ret := _m.ctrl.Call(_m, "RecvMsg", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) RecvMsg(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RecvMsg", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) Send(_param0 *routeguide.RouteNote) error { - ret := _m.ctrl.Call(_m, "Send", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Send(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Send", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) SendMsg(_param0 interface{}) error { - ret := _m.ctrl.Call(_m, "SendMsg", _param0) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) SendMsg(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SendMsg", arg0) -} - -func (_m *MockRouteGuide_RouteChatClient) Trailer() metadata.MD { - ret := _m.ctrl.Call(_m, "Trailer") - ret0, _ := ret[0].(metadata.MD) - return ret0 -} - -func (_mr *_MockRouteGuide_RouteChatClientRecorder) Trailer() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Trailer") -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go b/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go deleted file mode 100755 index 8525cd5..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/mock_routeguide/rg_mock_test.go +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package mock_routeguide_test - -import ( - "fmt" - "testing" - "time" - - "github.com/golang/mock/gomock" - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - rgmock "google.golang.org/grpc/examples/route_guide/mock_routeguide" - rgpb "google.golang.org/grpc/examples/route_guide/routeguide" -) - -var msg = &rgpb.RouteNote{ - Location: &rgpb.Point{Latitude: 17, Longitude: 29}, - Message: "Taxi-cab", -} - -func TestRouteChat(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - // Create mock for the stream returned by RouteChat - stream := rgmock.NewMockRouteGuide_RouteChatClient(ctrl) - // set expectation on sending. - stream.EXPECT().Send( - gomock.Any(), - ).Return(nil) - // Set expectation on receiving. - stream.EXPECT().Recv().Return(msg, nil) - stream.EXPECT().CloseSend().Return(nil) - // Create mock for the client interface. - rgclient := rgmock.NewMockRouteGuideClient(ctrl) - // Set expectation on RouteChat - rgclient.EXPECT().RouteChat( - gomock.Any(), - ).Return(stream, nil) - if err := testRouteChat(rgclient); err != nil { - t.Fatalf("Test failed: %v", err) - } -} - -func testRouteChat(client rgpb.RouteGuideClient) error { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := client.RouteChat(ctx) - if err != nil { - return err - } - if err := stream.Send(msg); err != nil { - return err - } - if err := stream.CloseSend(); err != nil { - return err - } - got, err := stream.Recv() - if err != nil { - return err - } - if !proto.Equal(got, msg) { - return fmt.Errorf("stream.Recv() = %v, want %v", got, msg) - } - return nil -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go b/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go deleted file mode 100755 index 199a2ee..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.pb.go +++ /dev/null @@ -1,640 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: route_guide.proto - -package routeguide - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Points are represented as latitude-longitude pairs in the E7 representation -// (degrees multiplied by 10**7 and rounded to the nearest integer). -// Latitudes should be in the range +/- 90 degrees and longitude should be in -// the range +/- 180 degrees (inclusive). -type Point struct { - Latitude int32 `protobuf:"varint,1,opt,name=latitude,proto3" json:"latitude,omitempty"` - Longitude int32 `protobuf:"varint,2,opt,name=longitude,proto3" json:"longitude,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Point) Reset() { *m = Point{} } -func (m *Point) String() string { return proto.CompactTextString(m) } -func (*Point) ProtoMessage() {} -func (*Point) Descriptor() ([]byte, []int) { - return fileDescriptor_route_guide_dc79de2de4c66c19, []int{0} -} -func (m *Point) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Point.Unmarshal(m, b) -} -func (m *Point) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Point.Marshal(b, m, deterministic) -} -func (dst *Point) XXX_Merge(src proto.Message) { - xxx_messageInfo_Point.Merge(dst, src) -} -func (m *Point) XXX_Size() int { - return xxx_messageInfo_Point.Size(m) -} -func (m *Point) XXX_DiscardUnknown() { - xxx_messageInfo_Point.DiscardUnknown(m) -} - -var xxx_messageInfo_Point proto.InternalMessageInfo - -func (m *Point) GetLatitude() int32 { - if m != nil { - return m.Latitude - } - return 0 -} - -func (m *Point) GetLongitude() int32 { - if m != nil { - return m.Longitude - } - return 0 -} - -// A latitude-longitude rectangle, represented as two diagonally opposite -// points "lo" and "hi". -type Rectangle struct { - // One corner of the rectangle. - Lo *Point `protobuf:"bytes,1,opt,name=lo,proto3" json:"lo,omitempty"` - // The other corner of the rectangle. - Hi *Point `protobuf:"bytes,2,opt,name=hi,proto3" json:"hi,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Rectangle) Reset() { *m = Rectangle{} } -func (m *Rectangle) String() string { return proto.CompactTextString(m) } -func (*Rectangle) ProtoMessage() {} -func (*Rectangle) Descriptor() ([]byte, []int) { - return fileDescriptor_route_guide_dc79de2de4c66c19, []int{1} -} -func (m *Rectangle) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Rectangle.Unmarshal(m, b) -} -func (m *Rectangle) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Rectangle.Marshal(b, m, deterministic) -} -func (dst *Rectangle) XXX_Merge(src proto.Message) { - xxx_messageInfo_Rectangle.Merge(dst, src) -} -func (m *Rectangle) XXX_Size() int { - return xxx_messageInfo_Rectangle.Size(m) -} -func (m *Rectangle) XXX_DiscardUnknown() { - xxx_messageInfo_Rectangle.DiscardUnknown(m) -} - -var xxx_messageInfo_Rectangle proto.InternalMessageInfo - -func (m *Rectangle) GetLo() *Point { - if m != nil { - return m.Lo - } - return nil -} - -func (m *Rectangle) GetHi() *Point { - if m != nil { - return m.Hi - } - return nil -} - -// A feature names something at a given point. -// -// If a feature could not be named, the name is empty. -type Feature struct { - // The name of the feature. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // The point where the feature is detected. - Location *Point `protobuf:"bytes,2,opt,name=location,proto3" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Feature) Reset() { *m = Feature{} } -func (m *Feature) String() string { return proto.CompactTextString(m) } -func (*Feature) ProtoMessage() {} -func (*Feature) Descriptor() ([]byte, []int) { - return fileDescriptor_route_guide_dc79de2de4c66c19, []int{2} -} -func (m *Feature) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Feature.Unmarshal(m, b) -} -func (m *Feature) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Feature.Marshal(b, m, deterministic) -} -func (dst *Feature) XXX_Merge(src proto.Message) { - xxx_messageInfo_Feature.Merge(dst, src) -} -func (m *Feature) XXX_Size() int { - return xxx_messageInfo_Feature.Size(m) -} -func (m *Feature) XXX_DiscardUnknown() { - xxx_messageInfo_Feature.DiscardUnknown(m) -} - -var xxx_messageInfo_Feature proto.InternalMessageInfo - -func (m *Feature) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *Feature) GetLocation() *Point { - if m != nil { - return m.Location - } - return nil -} - -// A RouteNote is a message sent while at a given point. -type RouteNote struct { - // The location from which the message is sent. - Location *Point `protobuf:"bytes,1,opt,name=location,proto3" json:"location,omitempty"` - // The message to be sent. - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RouteNote) Reset() { *m = RouteNote{} } -func (m *RouteNote) String() string { return proto.CompactTextString(m) } -func (*RouteNote) ProtoMessage() {} -func (*RouteNote) Descriptor() ([]byte, []int) { - return fileDescriptor_route_guide_dc79de2de4c66c19, []int{3} -} -func (m *RouteNote) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RouteNote.Unmarshal(m, b) -} -func (m *RouteNote) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RouteNote.Marshal(b, m, deterministic) -} -func (dst *RouteNote) XXX_Merge(src proto.Message) { - xxx_messageInfo_RouteNote.Merge(dst, src) -} -func (m *RouteNote) XXX_Size() int { - return xxx_messageInfo_RouteNote.Size(m) -} -func (m *RouteNote) XXX_DiscardUnknown() { - xxx_messageInfo_RouteNote.DiscardUnknown(m) -} - -var xxx_messageInfo_RouteNote proto.InternalMessageInfo - -func (m *RouteNote) GetLocation() *Point { - if m != nil { - return m.Location - } - return nil -} - -func (m *RouteNote) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -// A RouteSummary is received in response to a RecordRoute rpc. -// -// It contains the number of individual points received, the number of -// detected features, and the total distance covered as the cumulative sum of -// the distance between each point. -type RouteSummary struct { - // The number of points received. - PointCount int32 `protobuf:"varint,1,opt,name=point_count,json=pointCount,proto3" json:"point_count,omitempty"` - // The number of known features passed while traversing the route. - FeatureCount int32 `protobuf:"varint,2,opt,name=feature_count,json=featureCount,proto3" json:"feature_count,omitempty"` - // The distance covered in metres. - Distance int32 `protobuf:"varint,3,opt,name=distance,proto3" json:"distance,omitempty"` - // The duration of the traversal in seconds. - ElapsedTime int32 `protobuf:"varint,4,opt,name=elapsed_time,json=elapsedTime,proto3" json:"elapsed_time,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RouteSummary) Reset() { *m = RouteSummary{} } -func (m *RouteSummary) String() string { return proto.CompactTextString(m) } -func (*RouteSummary) ProtoMessage() {} -func (*RouteSummary) Descriptor() ([]byte, []int) { - return fileDescriptor_route_guide_dc79de2de4c66c19, []int{4} -} -func (m *RouteSummary) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_RouteSummary.Unmarshal(m, b) -} -func (m *RouteSummary) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_RouteSummary.Marshal(b, m, deterministic) -} -func (dst *RouteSummary) XXX_Merge(src proto.Message) { - xxx_messageInfo_RouteSummary.Merge(dst, src) -} -func (m *RouteSummary) XXX_Size() int { - return xxx_messageInfo_RouteSummary.Size(m) -} -func (m *RouteSummary) XXX_DiscardUnknown() { - xxx_messageInfo_RouteSummary.DiscardUnknown(m) -} - -var xxx_messageInfo_RouteSummary proto.InternalMessageInfo - -func (m *RouteSummary) GetPointCount() int32 { - if m != nil { - return m.PointCount - } - return 0 -} - -func (m *RouteSummary) GetFeatureCount() int32 { - if m != nil { - return m.FeatureCount - } - return 0 -} - -func (m *RouteSummary) GetDistance() int32 { - if m != nil { - return m.Distance - } - return 0 -} - -func (m *RouteSummary) GetElapsedTime() int32 { - if m != nil { - return m.ElapsedTime - } - return 0 -} - -func init() { - proto.RegisterType((*Point)(nil), "routeguide.Point") - proto.RegisterType((*Rectangle)(nil), "routeguide.Rectangle") - proto.RegisterType((*Feature)(nil), "routeguide.Feature") - proto.RegisterType((*RouteNote)(nil), "routeguide.RouteNote") - proto.RegisterType((*RouteSummary)(nil), "routeguide.RouteSummary") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// RouteGuideClient is the client API for RouteGuide service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type RouteGuideClient interface { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) -} - -type routeGuideClient struct { - cc *grpc.ClientConn -} - -func NewRouteGuideClient(cc *grpc.ClientConn) RouteGuideClient { - return &routeGuideClient{cc} -} - -func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) { - out := new(Feature) - err := c.cc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *routeGuideClient) ListFeatures(ctx context.Context, in *Rectangle, opts ...grpc.CallOption) (RouteGuide_ListFeaturesClient, error) { - stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[0], "/routeguide.RouteGuide/ListFeatures", opts...) - if err != nil { - return nil, err - } - x := &routeGuideListFeaturesClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type RouteGuide_ListFeaturesClient interface { - Recv() (*Feature, error) - grpc.ClientStream -} - -type routeGuideListFeaturesClient struct { - grpc.ClientStream -} - -func (x *routeGuideListFeaturesClient) Recv() (*Feature, error) { - m := new(Feature) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routeGuideClient) RecordRoute(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RecordRouteClient, error) { - stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[1], "/routeguide.RouteGuide/RecordRoute", opts...) - if err != nil { - return nil, err - } - x := &routeGuideRecordRouteClient{stream} - return x, nil -} - -type RouteGuide_RecordRouteClient interface { - Send(*Point) error - CloseAndRecv() (*RouteSummary, error) - grpc.ClientStream -} - -type routeGuideRecordRouteClient struct { - grpc.ClientStream -} - -func (x *routeGuideRecordRouteClient) Send(m *Point) error { - return x.ClientStream.SendMsg(m) -} - -func (x *routeGuideRecordRouteClient) CloseAndRecv() (*RouteSummary, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(RouteSummary) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *routeGuideClient) RouteChat(ctx context.Context, opts ...grpc.CallOption) (RouteGuide_RouteChatClient, error) { - stream, err := c.cc.NewStream(ctx, &_RouteGuide_serviceDesc.Streams[2], "/routeguide.RouteGuide/RouteChat", opts...) - if err != nil { - return nil, err - } - x := &routeGuideRouteChatClient{stream} - return x, nil -} - -type RouteGuide_RouteChatClient interface { - Send(*RouteNote) error - Recv() (*RouteNote, error) - grpc.ClientStream -} - -type routeGuideRouteChatClient struct { - grpc.ClientStream -} - -func (x *routeGuideRouteChatClient) Send(m *RouteNote) error { - return x.ClientStream.SendMsg(m) -} - -func (x *routeGuideRouteChatClient) Recv() (*RouteNote, error) { - m := new(RouteNote) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// RouteGuideServer is the server API for RouteGuide service. -type RouteGuideServer interface { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - GetFeature(context.Context, *Point) (*Feature, error) - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - ListFeatures(*Rectangle, RouteGuide_ListFeaturesServer) error - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - RecordRoute(RouteGuide_RecordRouteServer) error - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - RouteChat(RouteGuide_RouteChatServer) error -} - -func RegisterRouteGuideServer(s *grpc.Server, srv RouteGuideServer) { - s.RegisterService(&_RouteGuide_serviceDesc, srv) -} - -func _RouteGuide_GetFeature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Point) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(RouteGuideServer).GetFeature(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/routeguide.RouteGuide/GetFeature", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(RouteGuideServer).GetFeature(ctx, req.(*Point)) - } - return interceptor(ctx, in, info, handler) -} - -func _RouteGuide_ListFeatures_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(Rectangle) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(RouteGuideServer).ListFeatures(m, &routeGuideListFeaturesServer{stream}) -} - -type RouteGuide_ListFeaturesServer interface { - Send(*Feature) error - grpc.ServerStream -} - -type routeGuideListFeaturesServer struct { - grpc.ServerStream -} - -func (x *routeGuideListFeaturesServer) Send(m *Feature) error { - return x.ServerStream.SendMsg(m) -} - -func _RouteGuide_RecordRoute_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(RouteGuideServer).RecordRoute(&routeGuideRecordRouteServer{stream}) -} - -type RouteGuide_RecordRouteServer interface { - SendAndClose(*RouteSummary) error - Recv() (*Point, error) - grpc.ServerStream -} - -type routeGuideRecordRouteServer struct { - grpc.ServerStream -} - -func (x *routeGuideRecordRouteServer) SendAndClose(m *RouteSummary) error { - return x.ServerStream.SendMsg(m) -} - -func (x *routeGuideRecordRouteServer) Recv() (*Point, error) { - m := new(Point) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _RouteGuide_RouteChat_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(RouteGuideServer).RouteChat(&routeGuideRouteChatServer{stream}) -} - -type RouteGuide_RouteChatServer interface { - Send(*RouteNote) error - Recv() (*RouteNote, error) - grpc.ServerStream -} - -type routeGuideRouteChatServer struct { - grpc.ServerStream -} - -func (x *routeGuideRouteChatServer) Send(m *RouteNote) error { - return x.ServerStream.SendMsg(m) -} - -func (x *routeGuideRouteChatServer) Recv() (*RouteNote, error) { - m := new(RouteNote) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _RouteGuide_serviceDesc = grpc.ServiceDesc{ - ServiceName: "routeguide.RouteGuide", - HandlerType: (*RouteGuideServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetFeature", - Handler: _RouteGuide_GetFeature_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "ListFeatures", - Handler: _RouteGuide_ListFeatures_Handler, - ServerStreams: true, - }, - { - StreamName: "RecordRoute", - Handler: _RouteGuide_RecordRoute_Handler, - ClientStreams: true, - }, - { - StreamName: "RouteChat", - Handler: _RouteGuide_RouteChat_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "route_guide.proto", -} - -func init() { proto.RegisterFile("route_guide.proto", fileDescriptor_route_guide_dc79de2de4c66c19) } - -var fileDescriptor_route_guide_dc79de2de4c66c19 = []byte{ - // 404 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x53, 0xdd, 0xca, 0xd3, 0x40, - 0x10, 0xfd, 0x36, 0x7e, 0x9f, 0x6d, 0x26, 0x11, 0xe9, 0x88, 0x10, 0xa2, 0xa0, 0x8d, 0x37, 0xbd, - 0x31, 0x94, 0x0a, 0x5e, 0x56, 0x6c, 0xc1, 0xde, 0x14, 0xa9, 0xb1, 0xf7, 0x65, 0x4d, 0xc6, 0x74, - 0x61, 0x93, 0x0d, 0xc9, 0x06, 0xf4, 0x01, 0x7c, 0x02, 0x5f, 0x58, 0xb2, 0x49, 0xda, 0x54, 0x5b, - 0xbc, 0xdb, 0x39, 0x73, 0xce, 0xfc, 0x9c, 0x61, 0x61, 0x52, 0xaa, 0x5a, 0xd3, 0x21, 0xad, 0x45, - 0x42, 0x61, 0x51, 0x2a, 0xad, 0x10, 0x0c, 0x64, 0x90, 0xe0, 0x23, 0x3c, 0xec, 0x94, 0xc8, 0x35, - 0xfa, 0x30, 0x96, 0x5c, 0x0b, 0x5d, 0x27, 0xe4, 0xb1, 0xd7, 0x6c, 0xf6, 0x10, 0x9d, 0x62, 0x7c, - 0x09, 0xb6, 0x54, 0x79, 0xda, 0x26, 0x2d, 0x93, 0x3c, 0x03, 0xc1, 0x17, 0xb0, 0x23, 0x8a, 0x35, - 0xcf, 0x53, 0x49, 0x38, 0x05, 0x4b, 0x2a, 0x53, 0xc0, 0x59, 0x4c, 0xc2, 0x73, 0xa3, 0xd0, 0x74, - 0x89, 0x2c, 0xa9, 0x1a, 0xca, 0x51, 0x98, 0x32, 0xd7, 0x29, 0x47, 0x11, 0x6c, 0x61, 0xf4, 0x89, - 0xb8, 0xae, 0x4b, 0x42, 0x84, 0xfb, 0x9c, 0x67, 0xed, 0x4c, 0x76, 0x64, 0xde, 0xf8, 0x16, 0xc6, - 0x52, 0xc5, 0x5c, 0x0b, 0x95, 0xdf, 0xae, 0x73, 0xa2, 0x04, 0x7b, 0xb0, 0xa3, 0x26, 0xfb, 0x59, - 0xe9, 0x4b, 0x2d, 0xfb, 0xaf, 0x16, 0x3d, 0x18, 0x65, 0x54, 0x55, 0x3c, 0x6d, 0x17, 0xb7, 0xa3, - 0x3e, 0x0c, 0x7e, 0x33, 0x70, 0x4d, 0xd9, 0xaf, 0x75, 0x96, 0xf1, 0xf2, 0x27, 0xbe, 0x02, 0xa7, - 0x68, 0xd4, 0x87, 0x58, 0xd5, 0xb9, 0xee, 0x4c, 0x04, 0x03, 0xad, 0x1b, 0x04, 0xdf, 0xc0, 0x93, - 0xef, 0xed, 0x56, 0x1d, 0xa5, 0xb5, 0xd2, 0xed, 0xc0, 0x96, 0xe4, 0xc3, 0x38, 0x11, 0x95, 0xe6, - 0x79, 0x4c, 0xde, 0xa3, 0xf6, 0x0e, 0x7d, 0x8c, 0x53, 0x70, 0x49, 0xf2, 0xa2, 0xa2, 0xe4, 0xa0, - 0x45, 0x46, 0xde, 0xbd, 0xc9, 0x3b, 0x1d, 0xb6, 0x17, 0x19, 0x2d, 0x7e, 0x59, 0x00, 0x66, 0xaa, - 0x4d, 0xb3, 0x0e, 0xbe, 0x07, 0xd8, 0x90, 0xee, 0xbd, 0xfc, 0x77, 0x53, 0xff, 0xd9, 0x10, 0xea, - 0x78, 0xc1, 0x1d, 0x2e, 0xc1, 0xdd, 0x8a, 0xaa, 0x17, 0x56, 0xf8, 0x7c, 0x48, 0x3b, 0x5d, 0xfb, - 0x86, 0x7a, 0xce, 0x70, 0x09, 0x4e, 0x44, 0xb1, 0x2a, 0x13, 0x33, 0xcb, 0xb5, 0xc6, 0xde, 0x45, - 0xc5, 0x81, 0x8f, 0xc1, 0xdd, 0x8c, 0xe1, 0x87, 0xee, 0x64, 0xeb, 0x23, 0xd7, 0x7f, 0x35, 0xef, - 0x2f, 0xe9, 0x5f, 0x87, 0x1b, 0xf9, 0x9c, 0xad, 0xe6, 0xf0, 0x42, 0xa8, 0x30, 0x2d, 0x8b, 0x38, - 0xa4, 0x1f, 0x3c, 0x2b, 0x24, 0x55, 0x03, 0xfa, 0xea, 0xe9, 0xd9, 0xa3, 0x5d, 0xf3, 0x27, 0x76, - 0xec, 0xdb, 0x63, 0xf3, 0x39, 0xde, 0xfd, 0x09, 0x00, 0x00, 0xff, 0xff, 0xc8, 0xe4, 0xef, 0xe6, - 0x31, 0x03, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto b/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto deleted file mode 100755 index fe21e43..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/routeguide/route_guide.proto +++ /dev/null @@ -1,110 +0,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. - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "io.grpc.examples.routeguide"; -option java_outer_classname = "RouteGuideProto"; - -package routeguide; - -// Interface exported by the server. -service RouteGuide { - // A simple RPC. - // - // Obtains the feature at a given position. - // - // A feature with an empty name is returned if there's no feature at the given - // position. - rpc GetFeature(Point) returns (Feature) {} - - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - rpc ListFeatures(Rectangle) returns (stream Feature) {} - - // A client-to-server streaming RPC. - // - // Accepts a stream of Points on a route being traversed, returning a - // RouteSummary when traversal is completed. - rpc RecordRoute(stream Point) returns (RouteSummary) {} - - // A Bidirectional streaming RPC. - // - // Accepts a stream of RouteNotes sent while a route is being traversed, - // while receiving other RouteNotes (e.g. from other users). - rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} -} - -// Points are represented as latitude-longitude pairs in the E7 representation -// (degrees multiplied by 10**7 and rounded to the nearest integer). -// Latitudes should be in the range +/- 90 degrees and longitude should be in -// the range +/- 180 degrees (inclusive). -message Point { - int32 latitude = 1; - int32 longitude = 2; -} - -// A latitude-longitude rectangle, represented as two diagonally opposite -// points "lo" and "hi". -message Rectangle { - // One corner of the rectangle. - Point lo = 1; - - // The other corner of the rectangle. - Point hi = 2; -} - -// A feature names something at a given point. -// -// If a feature could not be named, the name is empty. -message Feature { - // The name of the feature. - string name = 1; - - // The point where the feature is detected. - Point location = 2; -} - -// A RouteNote is a message sent while at a given point. -message RouteNote { - // The location from which the message is sent. - Point location = 1; - - // The message to be sent. - string message = 2; -} - -// A RouteSummary is received in response to a RecordRoute rpc. -// -// It contains the number of individual points received, the number of -// detected features, and the total distance covered as the cumulative sum of -// the distance between each point. -message RouteSummary { - // The number of points received. - int32 point_count = 1; - - // The number of known features passed while traversing the route. - int32 feature_count = 2; - - // The distance covered in metres. - int32 distance = 3; - - // The duration of the traversal in seconds. - int32 elapsed_time = 4; -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/server/server.go b/examples/google.golang.org/grpc/examples/route_guide/server/server.go deleted file mode 100755 index ececfa7..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/server/server.go +++ /dev/null @@ -1,238 +0,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. - * - */ - -//go:generate protoc -I ../routeguide --go_out=plugins=grpc:../routeguide ../routeguide/route_guide.proto - -// Package main implements a simple gRPC server that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It implements the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "math" - "net" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/testdata" - - "github.com/golang/protobuf/proto" - - pb "google.golang.org/grpc/examples/route_guide/routeguide" -) - -var ( - tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP") - certFile = flag.String("cert_file", "", "The TLS cert file") - keyFile = flag.String("key_file", "", "The TLS key file") - jsonDBFile = flag.String("json_db_file", "testdata/route_guide_db.json", "A json file containing a list of features") - port = flag.Int("port", 10000, "The server port") -) - -type routeGuideServer struct { - savedFeatures []*pb.Feature // read-only after initialized - - mu sync.Mutex // protects routeNotes - routeNotes map[string][]*pb.RouteNote -} - -// GetFeature returns the feature at the given point. -func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) { - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - return feature, nil - } - } - // No feature was found, return an unnamed feature - return &pb.Feature{Location: point}, nil -} - -// ListFeatures lists all features contained within the given bounding Rectangle. -func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error { - for _, feature := range s.savedFeatures { - if inRange(feature.Location, rect) { - if err := stream.Send(feature); err != nil { - return err - } - } - } - return nil -} - -// RecordRoute records a route composited of a sequence of points. -// -// It gets a stream of points, and responds with statistics about the "trip": -// number of points, number of known features visited, total distance traveled, and -// total time spent. -func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error { - var pointCount, featureCount, distance int32 - var lastPoint *pb.Point - startTime := time.Now() - for { - point, err := stream.Recv() - if err == io.EOF { - endTime := time.Now() - return stream.SendAndClose(&pb.RouteSummary{ - PointCount: pointCount, - FeatureCount: featureCount, - Distance: distance, - ElapsedTime: int32(endTime.Sub(startTime).Seconds()), - }) - } - if err != nil { - return err - } - pointCount++ - for _, feature := range s.savedFeatures { - if proto.Equal(feature.Location, point) { - featureCount++ - } - } - if lastPoint != nil { - distance += calcDistance(lastPoint, point) - } - lastPoint = point - } -} - -// RouteChat receives a stream of message/location pairs, and responds with a stream of all -// previous messages at each of those locations. -func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - key := serialize(in.Location) - - s.mu.Lock() - s.routeNotes[key] = append(s.routeNotes[key], in) - // Note: this copy prevents blocking other clients while serving this one. - // We don't need to do a deep copy, because elements in the slice are - // insert-only and never modified. - rn := make([]*pb.RouteNote, len(s.routeNotes[key])) - copy(rn, s.routeNotes[key]) - s.mu.Unlock() - - for _, note := range rn { - if err := stream.Send(note); err != nil { - return err - } - } - } -} - -// loadFeatures loads features from a JSON file. -func (s *routeGuideServer) loadFeatures(filePath string) { - file, err := ioutil.ReadFile(filePath) - if err != nil { - log.Fatalf("Failed to load default features: %v", err) - } - if err := json.Unmarshal(file, &s.savedFeatures); err != nil { - log.Fatalf("Failed to load default features: %v", err) - } -} - -func toRadians(num float64) float64 { - return num * math.Pi / float64(180) -} - -// calcDistance calculates the distance between two points using the "haversine" formula. -// The formula is based on http://mathforum.org/library/drmath/view/51879.html. -func calcDistance(p1 *pb.Point, p2 *pb.Point) int32 { - const CordFactor float64 = 1e7 - const R float64 = float64(6371000) // earth radius in metres - lat1 := toRadians(float64(p1.Latitude) / CordFactor) - lat2 := toRadians(float64(p2.Latitude) / CordFactor) - lng1 := toRadians(float64(p1.Longitude) / CordFactor) - lng2 := toRadians(float64(p2.Longitude) / CordFactor) - dlat := lat2 - lat1 - dlng := lng2 - lng1 - - a := math.Sin(dlat/2)*math.Sin(dlat/2) + - math.Cos(lat1)*math.Cos(lat2)* - math.Sin(dlng/2)*math.Sin(dlng/2) - c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) - - distance := R * c - return int32(distance) -} - -func inRange(point *pb.Point, rect *pb.Rectangle) bool { - left := math.Min(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude)) - right := math.Max(float64(rect.Lo.Longitude), float64(rect.Hi.Longitude)) - top := math.Max(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude)) - bottom := math.Min(float64(rect.Lo.Latitude), float64(rect.Hi.Latitude)) - - if float64(point.Longitude) >= left && - float64(point.Longitude) <= right && - float64(point.Latitude) >= bottom && - float64(point.Latitude) <= top { - return true - } - return false -} - -func serialize(point *pb.Point) string { - return fmt.Sprintf("%d %d", point.Latitude, point.Longitude) -} - -func newServer() *routeGuideServer { - s := &routeGuideServer{routeNotes: make(map[string][]*pb.RouteNote)} - s.loadFeatures(*jsonDBFile) - return s -} - -func main() { - flag.Parse() - lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port)) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - var opts []grpc.ServerOption - if *tls { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - log.Fatalf("Failed to generate credentials %v", err) - } - opts = []grpc.ServerOption{grpc.Creds(creds)} - } - grpcServer := grpc.NewServer(opts...) - pb.RegisterRouteGuideServer(grpcServer, newServer()) - grpcServer.Serve(lis) -} diff --git a/examples/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json b/examples/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json deleted file mode 100755 index 9d6a980..0000000 --- a/examples/google.golang.org/grpc/examples/route_guide/testdata/route_guide_db.json +++ /dev/null @@ -1,601 +0,0 @@ -[{ - "location": { - "latitude": 407838351, - "longitude": -746143763 - }, - "name": "Patriots Path, Mendham, NJ 07945, USA" -}, { - "location": { - "latitude": 408122808, - "longitude": -743999179 - }, - "name": "101 New Jersey 10, Whippany, NJ 07981, USA" -}, { - "location": { - "latitude": 413628156, - "longitude": -749015468 - }, - "name": "U.S. 6, Shohola, PA 18458, USA" -}, { - "location": { - "latitude": 419999544, - "longitude": -740371136 - }, - "name": "5 Conners Road, Kingston, NY 12401, USA" -}, { - "location": { - "latitude": 414008389, - "longitude": -743951297 - }, - "name": "Mid Hudson Psychiatric Center, New Hampton, NY 10958, USA" -}, { - "location": { - "latitude": 419611318, - "longitude": -746524769 - }, - "name": "287 Flugertown Road, Livingston Manor, NY 12758, USA" -}, { - "location": { - "latitude": 406109563, - "longitude": -742186778 - }, - "name": "4001 Tremley Point Road, Linden, NJ 07036, USA" -}, { - "location": { - "latitude": 416802456, - "longitude": -742370183 - }, - "name": "352 South Mountain Road, Wallkill, NY 12589, USA" -}, { - "location": { - "latitude": 412950425, - "longitude": -741077389 - }, - "name": "Bailey Turn Road, Harriman, NY 10926, USA" -}, { - "location": { - "latitude": 412144655, - "longitude": -743949739 - }, - "name": "193-199 Wawayanda Road, Hewitt, NJ 07421, USA" -}, { - "location": { - "latitude": 415736605, - "longitude": -742847522 - }, - "name": "406-496 Ward Avenue, Pine Bush, NY 12566, USA" -}, { - "location": { - "latitude": 413843930, - "longitude": -740501726 - }, - "name": "162 Merrill Road, Highland Mills, NY 10930, USA" -}, { - "location": { - "latitude": 410873075, - "longitude": -744459023 - }, - "name": "Clinton Road, West Milford, NJ 07480, USA" -}, { - "location": { - "latitude": 412346009, - "longitude": -744026814 - }, - "name": "16 Old Brook Lane, Warwick, NY 10990, USA" -}, { - "location": { - "latitude": 402948455, - "longitude": -747903913 - }, - "name": "3 Drake Lane, Pennington, NJ 08534, USA" -}, { - "location": { - "latitude": 406337092, - "longitude": -740122226 - }, - "name": "6324 8th Avenue, Brooklyn, NY 11220, USA" -}, { - "location": { - "latitude": 406421967, - "longitude": -747727624 - }, - "name": "1 Merck Access Road, Whitehouse Station, NJ 08889, USA" -}, { - "location": { - "latitude": 416318082, - "longitude": -749677716 - }, - "name": "78-98 Schalck Road, Narrowsburg, NY 12764, USA" -}, { - "location": { - "latitude": 415301720, - "longitude": -748416257 - }, - "name": "282 Lakeview Drive Road, Highland Lake, NY 12743, USA" -}, { - "location": { - "latitude": 402647019, - "longitude": -747071791 - }, - "name": "330 Evelyn Avenue, Hamilton Township, NJ 08619, USA" -}, { - "location": { - "latitude": 412567807, - "longitude": -741058078 - }, - "name": "New York State Reference Route 987E, Southfields, NY 10975, USA" -}, { - "location": { - "latitude": 416855156, - "longitude": -744420597 - }, - "name": "103-271 Tempaloni Road, Ellenville, NY 12428, USA" -}, { - "location": { - "latitude": 404663628, - "longitude": -744820157 - }, - "name": "1300 Airport Road, North Brunswick Township, NJ 08902, USA" -}, { - "location": { - "latitude": 407113723, - "longitude": -749746483 - }, - "name": "" -}, { - "location": { - "latitude": 402133926, - "longitude": -743613249 - }, - "name": "" -}, { - "location": { - "latitude": 400273442, - "longitude": -741220915 - }, - "name": "" -}, { - "location": { - "latitude": 411236786, - "longitude": -744070769 - }, - "name": "" -}, { - "location": { - "latitude": 411633782, - "longitude": -746784970 - }, - "name": "211-225 Plains Road, Augusta, NJ 07822, USA" -}, { - "location": { - "latitude": 415830701, - "longitude": -742952812 - }, - "name": "" -}, { - "location": { - "latitude": 413447164, - "longitude": -748712898 - }, - "name": "165 Pedersen Ridge Road, Milford, PA 18337, USA" -}, { - "location": { - "latitude": 405047245, - "longitude": -749800722 - }, - "name": "100-122 Locktown Road, Frenchtown, NJ 08825, USA" -}, { - "location": { - "latitude": 418858923, - "longitude": -746156790 - }, - "name": "" -}, { - "location": { - "latitude": 417951888, - "longitude": -748484944 - }, - "name": "650-652 Willi Hill Road, Swan Lake, NY 12783, USA" -}, { - "location": { - "latitude": 407033786, - "longitude": -743977337 - }, - "name": "26 East 3rd Street, New Providence, NJ 07974, USA" -}, { - "location": { - "latitude": 417548014, - "longitude": -740075041 - }, - "name": "" -}, { - "location": { - "latitude": 410395868, - "longitude": -744972325 - }, - "name": "" -}, { - "location": { - "latitude": 404615353, - "longitude": -745129803 - }, - "name": "" -}, { - "location": { - "latitude": 406589790, - "longitude": -743560121 - }, - "name": "611 Lawrence Avenue, Westfield, NJ 07090, USA" -}, { - "location": { - "latitude": 414653148, - "longitude": -740477477 - }, - "name": "18 Lannis Avenue, New Windsor, NY 12553, USA" -}, { - "location": { - "latitude": 405957808, - "longitude": -743255336 - }, - "name": "82-104 Amherst Avenue, Colonia, NJ 07067, USA" -}, { - "location": { - "latitude": 411733589, - "longitude": -741648093 - }, - "name": "170 Seven Lakes Drive, Sloatsburg, NY 10974, USA" -}, { - "location": { - "latitude": 412676291, - "longitude": -742606606 - }, - "name": "1270 Lakes Road, Monroe, NY 10950, USA" -}, { - "location": { - "latitude": 409224445, - "longitude": -748286738 - }, - "name": "509-535 Alphano Road, Great Meadows, NJ 07838, USA" -}, { - "location": { - "latitude": 406523420, - "longitude": -742135517 - }, - "name": "652 Garden Street, Elizabeth, NJ 07202, USA" -}, { - "location": { - "latitude": 401827388, - "longitude": -740294537 - }, - "name": "349 Sea Spray Court, Neptune City, NJ 07753, USA" -}, { - "location": { - "latitude": 410564152, - "longitude": -743685054 - }, - "name": "13-17 Stanley Street, West Milford, NJ 07480, USA" -}, { - "location": { - "latitude": 408472324, - "longitude": -740726046 - }, - "name": "47 Industrial Avenue, Teterboro, NJ 07608, USA" -}, { - "location": { - "latitude": 412452168, - "longitude": -740214052 - }, - "name": "5 White Oak Lane, Stony Point, NY 10980, USA" -}, { - "location": { - "latitude": 409146138, - "longitude": -746188906 - }, - "name": "Berkshire Valley Management Area Trail, Jefferson, NJ, USA" -}, { - "location": { - "latitude": 404701380, - "longitude": -744781745 - }, - "name": "1007 Jersey Avenue, New Brunswick, NJ 08901, USA" -}, { - "location": { - "latitude": 409642566, - "longitude": -746017679 - }, - "name": "6 East Emerald Isle Drive, Lake Hopatcong, NJ 07849, USA" -}, { - "location": { - "latitude": 408031728, - "longitude": -748645385 - }, - "name": "1358-1474 New Jersey 57, Port Murray, NJ 07865, USA" -}, { - "location": { - "latitude": 413700272, - "longitude": -742135189 - }, - "name": "367 Prospect Road, Chester, NY 10918, USA" -}, { - "location": { - "latitude": 404310607, - "longitude": -740282632 - }, - "name": "10 Simon Lake Drive, Atlantic Highlands, NJ 07716, USA" -}, { - "location": { - "latitude": 409319800, - "longitude": -746201391 - }, - "name": "11 Ward Street, Mount Arlington, NJ 07856, USA" -}, { - "location": { - "latitude": 406685311, - "longitude": -742108603 - }, - "name": "300-398 Jefferson Avenue, Elizabeth, NJ 07201, USA" -}, { - "location": { - "latitude": 419018117, - "longitude": -749142781 - }, - "name": "43 Dreher Road, Roscoe, NY 12776, USA" -}, { - "location": { - "latitude": 412856162, - "longitude": -745148837 - }, - "name": "Swan Street, Pine Island, NY 10969, USA" -}, { - "location": { - "latitude": 416560744, - "longitude": -746721964 - }, - "name": "66 Pleasantview Avenue, Monticello, NY 12701, USA" -}, { - "location": { - "latitude": 405314270, - "longitude": -749836354 - }, - "name": "" -}, { - "location": { - "latitude": 414219548, - "longitude": -743327440 - }, - "name": "" -}, { - "location": { - "latitude": 415534177, - "longitude": -742900616 - }, - "name": "565 Winding Hills Road, Montgomery, NY 12549, USA" -}, { - "location": { - "latitude": 406898530, - "longitude": -749127080 - }, - "name": "231 Rocky Run Road, Glen Gardner, NJ 08826, USA" -}, { - "location": { - "latitude": 407586880, - "longitude": -741670168 - }, - "name": "100 Mount Pleasant Avenue, Newark, NJ 07104, USA" -}, { - "location": { - "latitude": 400106455, - "longitude": -742870190 - }, - "name": "517-521 Huntington Drive, Manchester Township, NJ 08759, USA" -}, { - "location": { - "latitude": 400066188, - "longitude": -746793294 - }, - "name": "" -}, { - "location": { - "latitude": 418803880, - "longitude": -744102673 - }, - "name": "40 Mountain Road, Napanoch, NY 12458, USA" -}, { - "location": { - "latitude": 414204288, - "longitude": -747895140 - }, - "name": "" -}, { - "location": { - "latitude": 414777405, - "longitude": -740615601 - }, - "name": "" -}, { - "location": { - "latitude": 415464475, - "longitude": -747175374 - }, - "name": "48 North Road, Forestburgh, NY 12777, USA" -}, { - "location": { - "latitude": 404062378, - "longitude": -746376177 - }, - "name": "" -}, { - "location": { - "latitude": 405688272, - "longitude": -749285130 - }, - "name": "" -}, { - "location": { - "latitude": 400342070, - "longitude": -748788996 - }, - "name": "" -}, { - "location": { - "latitude": 401809022, - "longitude": -744157964 - }, - "name": "" -}, { - "location": { - "latitude": 404226644, - "longitude": -740517141 - }, - "name": "9 Thompson Avenue, Leonardo, NJ 07737, USA" -}, { - "location": { - "latitude": 410322033, - "longitude": -747871659 - }, - "name": "" -}, { - "location": { - "latitude": 407100674, - "longitude": -747742727 - }, - "name": "" -}, { - "location": { - "latitude": 418811433, - "longitude": -741718005 - }, - "name": "213 Bush Road, Stone Ridge, NY 12484, USA" -}, { - "location": { - "latitude": 415034302, - "longitude": -743850945 - }, - "name": "" -}, { - "location": { - "latitude": 411349992, - "longitude": -743694161 - }, - "name": "" -}, { - "location": { - "latitude": 404839914, - "longitude": -744759616 - }, - "name": "1-17 Bergen Court, New Brunswick, NJ 08901, USA" -}, { - "location": { - "latitude": 414638017, - "longitude": -745957854 - }, - "name": "35 Oakland Valley Road, Cuddebackville, NY 12729, USA" -}, { - "location": { - "latitude": 412127800, - "longitude": -740173578 - }, - "name": "" -}, { - "location": { - "latitude": 401263460, - "longitude": -747964303 - }, - "name": "" -}, { - "location": { - "latitude": 412843391, - "longitude": -749086026 - }, - "name": "" -}, { - "location": { - "latitude": 418512773, - "longitude": -743067823 - }, - "name": "" -}, { - "location": { - "latitude": 404318328, - "longitude": -740835638 - }, - "name": "42-102 Main Street, Belford, NJ 07718, USA" -}, { - "location": { - "latitude": 419020746, - "longitude": -741172328 - }, - "name": "" -}, { - "location": { - "latitude": 404080723, - "longitude": -746119569 - }, - "name": "" -}, { - "location": { - "latitude": 401012643, - "longitude": -744035134 - }, - "name": "" -}, { - "location": { - "latitude": 404306372, - "longitude": -741079661 - }, - "name": "" -}, { - "location": { - "latitude": 403966326, - "longitude": -748519297 - }, - "name": "" -}, { - "location": { - "latitude": 405002031, - "longitude": -748407866 - }, - "name": "" -}, { - "location": { - "latitude": 409532885, - "longitude": -742200683 - }, - "name": "" -}, { - "location": { - "latitude": 416851321, - "longitude": -742674555 - }, - "name": "" -}, { - "location": { - "latitude": 406411633, - "longitude": -741722051 - }, - "name": "3387 Richmond Terrace, Staten Island, NY 10303, USA" -}, { - "location": { - "latitude": 413069058, - "longitude": -744597778 - }, - "name": "261 Van Sickle Road, Goshen, NY 10924, USA" -}, { - "location": { - "latitude": 418465462, - "longitude": -746859398 - }, - "name": "" -}, { - "location": { - "latitude": 411733222, - "longitude": -744228360 - }, - "name": "" -}, { - "location": { - "latitude": 410248224, - "longitude": -747127767 - }, - "name": "3 Hasta Way, Newton, NJ 07860, USA" -}] diff --git a/examples/google.golang.org/grpc/examples/rpc_errors/client/main.go b/examples/google.golang.org/grpc/examples/rpc_errors/client/main.go deleted file mode 100755 index b50fa8c..0000000 --- a/examples/google.golang.org/grpc/examples/rpc_errors/client/main.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * 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. - * - */ - -package main - -import ( - "log" - "os" - "time" - - "golang.org/x/net/context" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - "google.golang.org/grpc" - pb "google.golang.org/grpc/examples/helloworld/helloworld" - "google.golang.org/grpc/status" -) - -func main() { - // Set up a connection to the server. - conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) - if err != nil { - log.Fatalf("did not connect: %v", err) - } - defer func() { - if e := conn.Close(); e != nil { - log.Printf("failed to close connection: %s", e) - } - }() - c := pb.NewGreeterClient(conn) - - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "world"}) - if err != nil { - s := status.Convert(err) - for _, d := range s.Details() { - switch info := d.(type) { - case *epb.QuotaFailure: - log.Printf("Quota failure: %s", info) - default: - log.Printf("Unexpected type: %s", info) - } - } - os.Exit(1) - } - log.Printf("Greeting: %s", r.Message) -} diff --git a/examples/google.golang.org/grpc/examples/rpc_errors/server/main.go b/examples/google.golang.org/grpc/examples/rpc_errors/server/main.go deleted file mode 100755 index ced95d3..0000000 --- a/examples/google.golang.org/grpc/examples/rpc_errors/server/main.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * - * 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. - * - */ - -package main - -import ( - "fmt" - "log" - "net" - "sync" - - "golang.org/x/net/context" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - pb "google.golang.org/grpc/examples/helloworld/helloworld" - "google.golang.org/grpc/status" -) - -const ( - port = ":50051" -) - -// server is used to implement helloworld.GreeterServer. -type server struct { - mu sync.Mutex - count map[string]int -} - -// SayHello implements helloworld.GreeterServer -func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { - s.mu.Lock() - defer s.mu.Unlock() - // Track the number of times the user has been greeted. - s.count[in.Name]++ - if s.count[in.Name] > 1 { - st := status.New(codes.ResourceExhausted, "Request limit exceeded.") - ds, err := st.WithDetails( - &epb.QuotaFailure{ - Violations: []*epb.QuotaFailure_Violation{{ - Subject: fmt.Sprintf("name:%s", in.Name), - Description: "Limit one greeting per person", - }}, - }, - ) - if err != nil { - return nil, st.Err() - } - return nil, ds.Err() - } - return &pb.HelloReply{Message: "Hello " + in.Name}, nil -} - -func main() { - log.Printf("server starting on port %s...", port) - lis, err := net.Listen("tcp", port) - if err != nil { - log.Fatalf("failed to listen: %v", err) - } - s := grpc.NewServer() - pb.RegisterGreeterServer(s, &server{count: make(map[string]int)}) - if err := s.Serve(lis); err != nil { - log.Fatalf("failed to serve: %v", err) - } -} diff --git a/examples/google.golang.org/grpc/go16.go b/examples/google.golang.org/grpc/go16.go deleted file mode 100755 index 535ee93..0000000 --- a/examples/google.golang.org/grpc/go16.go +++ /dev/null @@ -1,70 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "io" - "net" - "net/http" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) -} - -func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { - req.Cancel = ctx.Done() - if err := req.Write(conn); err != nil { - return fmt.Errorf("failed to write the HTTP request: %v", err) - } - return nil -} - -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if err == nil || err == io.EOF { - return err - } - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled: - return status.Error(codes.Canceled, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} diff --git a/examples/google.golang.org/grpc/go17.go b/examples/google.golang.org/grpc/go17.go deleted file mode 100755 index ec676a9..0000000 --- a/examples/google.golang.org/grpc/go17.go +++ /dev/null @@ -1,71 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "context" - "fmt" - "io" - "net" - "net/http" - - netctx "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, network, address) -} - -func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { - req = req.WithContext(ctx) - if err := req.Write(conn); err != nil { - return fmt.Errorf("failed to write the HTTP request: %v", err) - } - return nil -} - -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if err == nil || err == io.EOF { - return err - } - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded, netctx.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled, netctx.Canceled: - return status.Error(codes.Canceled, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} diff --git a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go b/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go deleted file mode 100755 index 59b1ed4..0000000 --- a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go +++ /dev/null @@ -1,718 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_lb_v1/messages/messages.proto - -package messages // import "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type LoadBalanceRequest struct { - // Types that are valid to be assigned to LoadBalanceRequestType: - // *LoadBalanceRequest_InitialRequest - // *LoadBalanceRequest_ClientStats - LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } -func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceRequest) ProtoMessage() {} -func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{0} -} -func (m *LoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceRequest.Unmarshal(m, b) -} -func (m *LoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceRequest.Merge(dst, src) -} -func (m *LoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_LoadBalanceRequest.Size(m) -} -func (m *LoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceRequest proto.InternalMessageInfo - -type isLoadBalanceRequest_LoadBalanceRequestType interface { - isLoadBalanceRequest_LoadBalanceRequestType() -} - -type LoadBalanceRequest_InitialRequest struct { - InitialRequest *InitialLoadBalanceRequest `protobuf:"bytes,1,opt,name=initial_request,json=initialRequest,proto3,oneof"` -} -type LoadBalanceRequest_ClientStats struct { - ClientStats *ClientStats `protobuf:"bytes,2,opt,name=client_stats,json=clientStats,proto3,oneof"` -} - -func (*LoadBalanceRequest_InitialRequest) isLoadBalanceRequest_LoadBalanceRequestType() {} -func (*LoadBalanceRequest_ClientStats) isLoadBalanceRequest_LoadBalanceRequestType() {} - -func (m *LoadBalanceRequest) GetLoadBalanceRequestType() isLoadBalanceRequest_LoadBalanceRequestType { - if m != nil { - return m.LoadBalanceRequestType - } - return nil -} - -func (m *LoadBalanceRequest) GetInitialRequest() *InitialLoadBalanceRequest { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_InitialRequest); ok { - return x.InitialRequest - } - return nil -} - -func (m *LoadBalanceRequest) GetClientStats() *ClientStats { - if x, ok := m.GetLoadBalanceRequestType().(*LoadBalanceRequest_ClientStats); ok { - return x.ClientStats - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceRequest_OneofMarshaler, _LoadBalanceRequest_OneofUnmarshaler, _LoadBalanceRequest_OneofSizer, []interface{}{ - (*LoadBalanceRequest_InitialRequest)(nil), - (*LoadBalanceRequest_ClientStats)(nil), - } -} - -func _LoadBalanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialRequest); err != nil { - return err - } - case *LoadBalanceRequest_ClientStats: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientStats); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceRequest.LoadBalanceRequestType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceRequest) - switch tag { - case 1: // load_balance_request_type.initial_request - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceRequest) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_InitialRequest{msg} - return true, err - case 2: // load_balance_request_type.client_stats - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientStats) - err := b.DecodeMessage(msg) - m.LoadBalanceRequestType = &LoadBalanceRequest_ClientStats{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceRequest) - // load_balance_request_type - switch x := m.LoadBalanceRequestType.(type) { - case *LoadBalanceRequest_InitialRequest: - s := proto.Size(x.InitialRequest) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceRequest_ClientStats: - s := proto.Size(x.ClientStats) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceRequest struct { - // Name of load balanced service (IE, balancer.service.com). Its - // length should be less than 256 bytes. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } -func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceRequest) ProtoMessage() {} -func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{1} -} -func (m *InitialLoadBalanceRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceRequest.Unmarshal(m, b) -} -func (m *InitialLoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceRequest.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceRequest.Merge(dst, src) -} -func (m *InitialLoadBalanceRequest) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceRequest.Size(m) -} -func (m *InitialLoadBalanceRequest) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceRequest proto.InternalMessageInfo - -func (m *InitialLoadBalanceRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// Contains the number of calls finished for a particular load balance token. -type ClientStatsPerToken struct { - // See Server.load_balance_token. - LoadBalanceToken string `protobuf:"bytes,1,opt,name=load_balance_token,json=loadBalanceToken,proto3" json:"load_balance_token,omitempty"` - // The total number of RPCs that finished associated with the token. - NumCalls int64 `protobuf:"varint,2,opt,name=num_calls,json=numCalls,proto3" json:"num_calls,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStatsPerToken) Reset() { *m = ClientStatsPerToken{} } -func (m *ClientStatsPerToken) String() string { return proto.CompactTextString(m) } -func (*ClientStatsPerToken) ProtoMessage() {} -func (*ClientStatsPerToken) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{2} -} -func (m *ClientStatsPerToken) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStatsPerToken.Unmarshal(m, b) -} -func (m *ClientStatsPerToken) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStatsPerToken.Marshal(b, m, deterministic) -} -func (dst *ClientStatsPerToken) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStatsPerToken.Merge(dst, src) -} -func (m *ClientStatsPerToken) XXX_Size() int { - return xxx_messageInfo_ClientStatsPerToken.Size(m) -} -func (m *ClientStatsPerToken) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStatsPerToken.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStatsPerToken proto.InternalMessageInfo - -func (m *ClientStatsPerToken) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *ClientStatsPerToken) GetNumCalls() int64 { - if m != nil { - return m.NumCalls - } - return 0 -} - -// Contains client level statistics that are useful to load balancing. Each -// count except the timestamp should be reset to zero after reporting the stats. -type ClientStats struct { - // The timestamp of generating the report. - Timestamp *timestamp.Timestamp `protobuf:"bytes,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - // The total number of RPCs that started. - NumCallsStarted int64 `protobuf:"varint,2,opt,name=num_calls_started,json=numCallsStarted,proto3" json:"num_calls_started,omitempty"` - // The total number of RPCs that finished. - NumCallsFinished int64 `protobuf:"varint,3,opt,name=num_calls_finished,json=numCallsFinished,proto3" json:"num_calls_finished,omitempty"` - // The total number of RPCs that failed to reach a server except dropped RPCs. - NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend,proto3" json:"num_calls_finished_with_client_failed_to_send,omitempty"` - // The total number of RPCs that finished and are known to have been received - // by a server. - NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived,proto3" json:"num_calls_finished_known_received,omitempty"` - // The list of dropped calls. - CallsFinishedWithDrop []*ClientStatsPerToken `protobuf:"bytes,8,rep,name=calls_finished_with_drop,json=callsFinishedWithDrop,proto3" json:"calls_finished_with_drop,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{3} -} -func (m *ClientStats) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ClientStats.Unmarshal(m, b) -} -func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) -} -func (dst *ClientStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientStats.Merge(dst, src) -} -func (m *ClientStats) XXX_Size() int { - return xxx_messageInfo_ClientStats.Size(m) -} -func (m *ClientStats) XXX_DiscardUnknown() { - xxx_messageInfo_ClientStats.DiscardUnknown(m) -} - -var xxx_messageInfo_ClientStats proto.InternalMessageInfo - -func (m *ClientStats) GetTimestamp() *timestamp.Timestamp { - if m != nil { - return m.Timestamp - } - return nil -} - -func (m *ClientStats) GetNumCallsStarted() int64 { - if m != nil { - return m.NumCallsStarted - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinished() int64 { - if m != nil { - return m.NumCallsFinished - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedWithClientFailedToSend() int64 { - if m != nil { - return m.NumCallsFinishedWithClientFailedToSend - } - return 0 -} - -func (m *ClientStats) GetNumCallsFinishedKnownReceived() int64 { - if m != nil { - return m.NumCallsFinishedKnownReceived - } - return 0 -} - -func (m *ClientStats) GetCallsFinishedWithDrop() []*ClientStatsPerToken { - if m != nil { - return m.CallsFinishedWithDrop - } - return nil -} - -type LoadBalanceResponse struct { - // Types that are valid to be assigned to LoadBalanceResponseType: - // *LoadBalanceResponse_InitialResponse - // *LoadBalanceResponse_ServerList - LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } -func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceResponse) ProtoMessage() {} -func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{4} -} -func (m *LoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LoadBalanceResponse.Unmarshal(m, b) -} -func (m *LoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *LoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_LoadBalanceResponse.Merge(dst, src) -} -func (m *LoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_LoadBalanceResponse.Size(m) -} -func (m *LoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_LoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_LoadBalanceResponse proto.InternalMessageInfo - -type isLoadBalanceResponse_LoadBalanceResponseType interface { - isLoadBalanceResponse_LoadBalanceResponseType() -} - -type LoadBalanceResponse_InitialResponse struct { - InitialResponse *InitialLoadBalanceResponse `protobuf:"bytes,1,opt,name=initial_response,json=initialResponse,proto3,oneof"` -} -type LoadBalanceResponse_ServerList struct { - ServerList *ServerList `protobuf:"bytes,2,opt,name=server_list,json=serverList,proto3,oneof"` -} - -func (*LoadBalanceResponse_InitialResponse) isLoadBalanceResponse_LoadBalanceResponseType() {} -func (*LoadBalanceResponse_ServerList) isLoadBalanceResponse_LoadBalanceResponseType() {} - -func (m *LoadBalanceResponse) GetLoadBalanceResponseType() isLoadBalanceResponse_LoadBalanceResponseType { - if m != nil { - return m.LoadBalanceResponseType - } - return nil -} - -func (m *LoadBalanceResponse) GetInitialResponse() *InitialLoadBalanceResponse { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_InitialResponse); ok { - return x.InitialResponse - } - return nil -} - -func (m *LoadBalanceResponse) GetServerList() *ServerList { - if x, ok := m.GetLoadBalanceResponseType().(*LoadBalanceResponse_ServerList); ok { - return x.ServerList - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*LoadBalanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _LoadBalanceResponse_OneofMarshaler, _LoadBalanceResponse_OneofUnmarshaler, _LoadBalanceResponse_OneofSizer, []interface{}{ - (*LoadBalanceResponse_InitialResponse)(nil), - (*LoadBalanceResponse_ServerList)(nil), - } -} - -func _LoadBalanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - b.EncodeVarint(1<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.InitialResponse); err != nil { - return err - } - case *LoadBalanceResponse_ServerList: - b.EncodeVarint(2<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerList); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("LoadBalanceResponse.LoadBalanceResponseType has unexpected type %T", x) - } - return nil -} - -func _LoadBalanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*LoadBalanceResponse) - switch tag { - case 1: // load_balance_response_type.initial_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(InitialLoadBalanceResponse) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_InitialResponse{msg} - return true, err - case 2: // load_balance_response_type.server_list - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerList) - err := b.DecodeMessage(msg) - m.LoadBalanceResponseType = &LoadBalanceResponse_ServerList{msg} - return true, err - default: - return false, nil - } -} - -func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*LoadBalanceResponse) - // load_balance_response_type - switch x := m.LoadBalanceResponseType.(type) { - case *LoadBalanceResponse_InitialResponse: - s := proto.Size(x.InitialResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *LoadBalanceResponse_ServerList: - s := proto.Size(x.ServerList) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type InitialLoadBalanceResponse struct { - // This is an application layer redirect that indicates the client should use - // the specified server for load balancing. When this field is non-empty in - // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. Its length should - // be less than 64 bytes. - LoadBalancerDelegate string `protobuf:"bytes,1,opt,name=load_balancer_delegate,json=loadBalancerDelegate,proto3" json:"load_balancer_delegate,omitempty"` - // This interval defines how often the client should send the client stats - // to the load balancer. Stats should only be reported when the duration is - // positive. - ClientStatsReportInterval *duration.Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval,proto3" json:"client_stats_report_interval,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } -func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceResponse) ProtoMessage() {} -func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{5} -} -func (m *InitialLoadBalanceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_InitialLoadBalanceResponse.Unmarshal(m, b) -} -func (m *InitialLoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_InitialLoadBalanceResponse.Marshal(b, m, deterministic) -} -func (dst *InitialLoadBalanceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_InitialLoadBalanceResponse.Merge(dst, src) -} -func (m *InitialLoadBalanceResponse) XXX_Size() int { - return xxx_messageInfo_InitialLoadBalanceResponse.Size(m) -} -func (m *InitialLoadBalanceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_InitialLoadBalanceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_InitialLoadBalanceResponse proto.InternalMessageInfo - -func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string { - if m != nil { - return m.LoadBalancerDelegate - } - return "" -} - -func (m *InitialLoadBalanceResponse) GetClientStatsReportInterval() *duration.Duration { - if m != nil { - return m.ClientStatsReportInterval - } - return nil -} - -type ServerList struct { - // Contains a list of servers selected by the load balancer. The list will - // be updated when server resolutions change or as needed to balance load - // across more servers. The client should consume the server list in order - // unless instructed otherwise via the client_config. - Servers []*Server `protobuf:"bytes,1,rep,name=servers,proto3" json:"servers,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerList) Reset() { *m = ServerList{} } -func (m *ServerList) String() string { return proto.CompactTextString(m) } -func (*ServerList) ProtoMessage() {} -func (*ServerList) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{6} -} -func (m *ServerList) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerList.Unmarshal(m, b) -} -func (m *ServerList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerList.Marshal(b, m, deterministic) -} -func (dst *ServerList) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerList.Merge(dst, src) -} -func (m *ServerList) XXX_Size() int { - return xxx_messageInfo_ServerList.Size(m) -} -func (m *ServerList) XXX_DiscardUnknown() { - xxx_messageInfo_ServerList.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerList proto.InternalMessageInfo - -func (m *ServerList) GetServers() []*Server { - if m != nil { - return m.Servers - } - return nil -} - -// Contains server information. When the drop field is not true, use the other -// fields. -type Server struct { - // A resolved address for the server, serialized in network-byte-order. It may - // either be an IPv4 or IPv6 address. - IpAddress []byte `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - // A resolved port number for the server. - Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` - // An opaque but printable token given to the frontend for each pick. All - // frontend requests for that pick must include the token in its initial - // metadata. The token is used by the backend to verify the request and to - // allow the backend to report load to the gRPC LB system. The token is also - // used in client stats for reporting dropped calls. - LoadBalanceToken string `protobuf:"bytes,3,opt,name=load_balance_token,json=loadBalanceToken,proto3" json:"load_balance_token,omitempty"` - // 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. - Drop bool `protobuf:"varint,4,opt,name=drop,proto3" json:"drop,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { - return fileDescriptor_messages_b3d89fcb5aa158f8, []int{7} -} -func (m *Server) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Server.Unmarshal(m, b) -} -func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Server.Marshal(b, m, deterministic) -} -func (dst *Server) XXX_Merge(src proto.Message) { - xxx_messageInfo_Server.Merge(dst, src) -} -func (m *Server) XXX_Size() int { - return xxx_messageInfo_Server.Size(m) -} -func (m *Server) XXX_DiscardUnknown() { - xxx_messageInfo_Server.DiscardUnknown(m) -} - -var xxx_messageInfo_Server proto.InternalMessageInfo - -func (m *Server) GetIpAddress() []byte { - if m != nil { - return m.IpAddress - } - return nil -} - -func (m *Server) GetPort() int32 { - if m != nil { - return m.Port - } - return 0 -} - -func (m *Server) GetLoadBalanceToken() string { - if m != nil { - return m.LoadBalanceToken - } - return "" -} - -func (m *Server) GetDrop() bool { - if m != nil { - return m.Drop - } - return false -} - -func init() { - proto.RegisterType((*LoadBalanceRequest)(nil), "grpc.lb.v1.LoadBalanceRequest") - proto.RegisterType((*InitialLoadBalanceRequest)(nil), "grpc.lb.v1.InitialLoadBalanceRequest") - proto.RegisterType((*ClientStatsPerToken)(nil), "grpc.lb.v1.ClientStatsPerToken") - proto.RegisterType((*ClientStats)(nil), "grpc.lb.v1.ClientStats") - proto.RegisterType((*LoadBalanceResponse)(nil), "grpc.lb.v1.LoadBalanceResponse") - proto.RegisterType((*InitialLoadBalanceResponse)(nil), "grpc.lb.v1.InitialLoadBalanceResponse") - proto.RegisterType((*ServerList)(nil), "grpc.lb.v1.ServerList") - proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server") -} - -func init() { - proto.RegisterFile("grpc_lb_v1/messages/messages.proto", fileDescriptor_messages_b3d89fcb5aa158f8) -} - -var fileDescriptor_messages_b3d89fcb5aa158f8 = []byte{ - // 708 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0x61, 0x4f, 0xf3, 0x36, - 0x10, 0x26, 0x6b, 0xe8, 0xdb, 0x5e, 0x5f, 0x8d, 0xce, 0x6c, 0x2c, 0x2d, 0x30, 0x58, 0xa4, 0x21, - 0x34, 0xb1, 0x54, 0xc0, 0x3e, 0x6c, 0xd2, 0x3e, 0x6c, 0x05, 0xa1, 0xc2, 0xf8, 0x80, 0x52, 0xa4, - 0x4d, 0x48, 0x93, 0xe7, 0x36, 0x26, 0x58, 0xb8, 0x76, 0x66, 0xbb, 0x45, 0xfb, 0xbc, 0xff, 0x33, - 0xed, 0x2f, 0x4c, 0xfb, 0x63, 0x53, 0xec, 0xa4, 0x0d, 0x2d, 0xd5, 0xfb, 0x25, 0x72, 0xee, 0x9e, - 0x7b, 0xee, 0xce, 0x77, 0x8f, 0x21, 0x4c, 0x55, 0x36, 0xc6, 0x7c, 0x84, 0x67, 0xa7, 0xbd, 0x09, - 0xd5, 0x9a, 0xa4, 0x54, 0xcf, 0x0f, 0x51, 0xa6, 0xa4, 0x91, 0x08, 0x72, 0x4c, 0xc4, 0x47, 0xd1, - 0xec, 0xb4, 0xfb, 0x45, 0x2a, 0x65, 0xca, 0x69, 0xcf, 0x7a, 0x46, 0xd3, 0xc7, 0x5e, 0x32, 0x55, - 0xc4, 0x30, 0x29, 0x1c, 0xb6, 0x7b, 0xb0, 0xec, 0x37, 0x6c, 0x42, 0xb5, 0x21, 0x93, 0xcc, 0x01, - 0xc2, 0x7f, 0x3d, 0x40, 0xb7, 0x92, 0x24, 0x7d, 0xc2, 0x89, 0x18, 0xd3, 0x98, 0xfe, 0x31, 0xa5, - 0xda, 0xa0, 0x3b, 0xd8, 0x62, 0x82, 0x19, 0x46, 0x38, 0x56, 0xce, 0x14, 0x78, 0x87, 0xde, 0x71, - 0xeb, 0xec, 0xab, 0x68, 0x91, 0x3d, 0xba, 0x76, 0x90, 0xd5, 0xf8, 0xc1, 0x46, 0xfc, 0x71, 0x11, - 0x5f, 0x32, 0xfe, 0x00, 0xef, 0xc7, 0x9c, 0x51, 0x61, 0xb0, 0x36, 0xc4, 0xe8, 0xe0, 0x23, 0x4b, - 0xf7, 0x79, 0x95, 0xee, 0xc2, 0xfa, 0x87, 0xb9, 0x7b, 0xb0, 0x11, 0xb7, 0xc6, 0x8b, 0xdf, 0xfe, - 0x2e, 0x74, 0xb8, 0x24, 0x09, 0x1e, 0xb9, 0x34, 0x65, 0x51, 0xd8, 0xfc, 0x99, 0xd1, 0xb0, 0x07, - 0x9d, 0xb5, 0x95, 0x20, 0x04, 0xbe, 0x20, 0x13, 0x6a, 0xcb, 0x6f, 0xc6, 0xf6, 0x1c, 0xfe, 0x0e, - 0xdb, 0x95, 0x5c, 0x77, 0x54, 0xdd, 0xcb, 0x67, 0x2a, 0xd0, 0x09, 0xa0, 0x57, 0x49, 0x4c, 0x6e, - 0x2d, 0x02, 0xdb, 0x7c, 0x41, 0xed, 0xd0, 0xbb, 0xd0, 0x14, 0xd3, 0x09, 0x1e, 0x13, 0xce, 0x5d, - 0x37, 0xb5, 0xb8, 0x21, 0xa6, 0x93, 0x8b, 0xfc, 0x3f, 0xfc, 0xa7, 0x06, 0xad, 0x4a, 0x0a, 0xf4, - 0x1d, 0x34, 0xe7, 0x37, 0x5f, 0xdc, 0x64, 0x37, 0x72, 0xb3, 0x89, 0xca, 0xd9, 0x44, 0xf7, 0x25, - 0x22, 0x5e, 0x80, 0xd1, 0xd7, 0xf0, 0xc9, 0x3c, 0x4d, 0x7e, 0x75, 0xca, 0xd0, 0xa4, 0x48, 0xb7, - 0x55, 0xa6, 0x1b, 0x3a, 0x73, 0xde, 0xc0, 0x02, 0xfb, 0xc8, 0x04, 0xd3, 0x4f, 0x34, 0x09, 0x6a, - 0x16, 0xdc, 0x2e, 0xc1, 0x57, 0x85, 0x1d, 0xfd, 0x06, 0xdf, 0xac, 0xa2, 0xf1, 0x0b, 0x33, 0x4f, - 0xb8, 0x98, 0xd4, 0x23, 0x61, 0x9c, 0x26, 0xd8, 0x48, 0xac, 0xa9, 0x48, 0x82, 0xba, 0x25, 0x3a, - 0x5a, 0x26, 0xfa, 0x85, 0x99, 0x27, 0xd7, 0xeb, 0x95, 0xc5, 0xdf, 0xcb, 0x21, 0x15, 0x09, 0x1a, - 0xc0, 0x97, 0x6f, 0xd0, 0x3f, 0x0b, 0xf9, 0x22, 0xb0, 0xa2, 0x63, 0xca, 0x66, 0x34, 0x09, 0xde, - 0x59, 0xca, 0xfd, 0x65, 0xca, 0x9f, 0x73, 0x54, 0x5c, 0x80, 0xd0, 0xaf, 0x10, 0xbc, 0x55, 0x64, - 0xa2, 0x64, 0x16, 0x34, 0x0e, 0x6b, 0xc7, 0xad, 0xb3, 0x83, 0x35, 0x6b, 0x54, 0x8e, 0x36, 0xfe, - 0x6c, 0xbc, 0x5c, 0xf1, 0xa5, 0x92, 0xd9, 0x8d, 0xdf, 0xf0, 0xdb, 0x9b, 0x37, 0x7e, 0x63, 0xb3, - 0x5d, 0x0f, 0xff, 0xf3, 0x60, 0xfb, 0xd5, 0xfe, 0xe8, 0x4c, 0x0a, 0x4d, 0xd1, 0x10, 0xda, 0x0b, - 0x29, 0x38, 0x5b, 0x31, 0xc1, 0xa3, 0x0f, 0x69, 0xc1, 0xa1, 0x07, 0x1b, 0xf1, 0xd6, 0x5c, 0x0c, - 0x05, 0xe9, 0xf7, 0xd0, 0xd2, 0x54, 0xcd, 0xa8, 0xc2, 0x9c, 0x69, 0x53, 0x88, 0x61, 0xa7, 0xca, - 0x37, 0xb4, 0xee, 0x5b, 0x66, 0xc5, 0x04, 0x7a, 0xfe, 0xd7, 0xdf, 0x83, 0xee, 0x92, 0x14, 0x1c, - 0xa7, 0xd3, 0xc2, 0xdf, 0x1e, 0x74, 0xd7, 0x97, 0x82, 0xbe, 0x85, 0x9d, 0x6a, 0xb0, 0xc2, 0x09, - 0xe5, 0x34, 0x25, 0xa6, 0xd4, 0xc7, 0xa7, 0x95, 0x35, 0x57, 0x97, 0x85, 0x0f, 0x3d, 0xc0, 0x5e, - 0x55, 0xbb, 0x58, 0xd1, 0x4c, 0x2a, 0x83, 0x99, 0x30, 0x54, 0xcd, 0x08, 0x2f, 0xca, 0xef, 0xac, - 0x2c, 0xf4, 0x65, 0xf1, 0x18, 0xc5, 0x9d, 0x8a, 0x96, 0x63, 0x1b, 0x7c, 0x5d, 0xc4, 0x86, 0x3f, - 0x02, 0x2c, 0x5a, 0x45, 0x27, 0xf0, 0xce, 0xb5, 0xaa, 0x03, 0xcf, 0x4e, 0x16, 0xad, 0xde, 0x49, - 0x5c, 0x42, 0x6e, 0xfc, 0x46, 0xad, 0xed, 0x87, 0x7f, 0x79, 0x50, 0x77, 0x1e, 0xb4, 0x0f, 0xc0, - 0x32, 0x4c, 0x92, 0x44, 0x51, 0xad, 0x6d, 0x4b, 0xef, 0xe3, 0x26, 0xcb, 0x7e, 0x72, 0x86, 0xfc, - 0x2d, 0xc8, 0x73, 0xdb, 0x7a, 0x37, 0x63, 0x7b, 0x5e, 0x23, 0xfa, 0xda, 0x1a, 0xd1, 0x23, 0xf0, - 0xed, 0xda, 0xf9, 0x87, 0xde, 0x71, 0x23, 0xb6, 0x67, 0xb7, 0x3e, 0xfd, 0xf3, 0x87, 0xd3, 0xa2, - 0xfd, 0x54, 0x72, 0x22, 0xd2, 0x48, 0xaa, 0xb4, 0x97, 0xd7, 0x6e, 0x3f, 0x7c, 0xd4, 0x7b, 0xe3, - 0x65, 0x1f, 0xd5, 0xed, 0x55, 0x9d, 0xff, 0x1f, 0x00, 0x00, 0xff, 0xff, 0xc8, 0x88, 0xe6, 0xf4, - 0xf7, 0x05, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto b/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto deleted file mode 100755 index 56d767e..0000000 --- a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto +++ /dev/null @@ -1,133 +0,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. - -syntax = "proto3"; - -import "google/protobuf/duration.proto"; -import "google/protobuf/timestamp.proto"; - -package grpc.lb.v1; -option go_package = "google.golang.org/grpc/grpclb/grpc_lb_v1/messages"; - -message LoadBalanceRequest { - oneof load_balance_request_type { - // This message should be sent on the first request to the load balancer. - InitialLoadBalanceRequest initial_request = 1; - - // The client stats should be periodically reported to the load balancer - // based on the duration defined in the InitialLoadBalanceResponse. - ClientStats client_stats = 2; - } -} - -message InitialLoadBalanceRequest { - // Name of load balanced service (IE, balancer.service.com). Its - // length should be less than 256 bytes. - 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 client level statistics that are useful to load balancing. Each -// count except the timestamp should be reset to zero after reporting the stats. -message ClientStats { - // 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; -} - -message LoadBalanceResponse { - oneof load_balance_response_type { - // This message should be sent on the first response to the client. - InitialLoadBalanceResponse initial_response = 1; - - // Contains the list of servers selected by the load balancer. The client - // should send requests to these servers in the specified order. - ServerList server_list = 2; - } -} - -message InitialLoadBalanceResponse { - // This is an application layer redirect that indicates the client should use - // the specified server for load balancing. When this field is non-empty in - // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. Its length should - // be less than 64 bytes. - string load_balancer_delegate = 1; - - // This interval defines how often the client should send the client stats - // to the load balancer. Stats should only be reported when the duration is - // positive. - google.protobuf.Duration client_stats_report_interval = 2; -} - -message ServerList { - // Contains a list of servers selected by the load balancer. The list will - // be updated when server resolutions change or as needed to balance load - // across more servers. The client should consume the server list in order - // unless instructed otherwise via the client_config. - repeated Server servers = 1; - - // Was google.protobuf.Duration expiration_interval. - reserved 3; -} - -// 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. - bytes ip_address = 1; - - // A resolved port number for the server. - int32 port = 2; - - // An opaque but printable token given to the frontend for each pick. All - // frontend requests for that pick must include the token in its initial - // metadata. The token is used by the backend to verify the request and to - // allow the backend to report load to the gRPC LB system. The token is also - // used in client stats for reporting dropped calls. - 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; -} diff --git a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go b/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go deleted file mode 100755 index 3e4a97b..0000000 --- a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.pb.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_lb_v1/service/service.proto - -package service // import "google.golang.org/grpc/grpclb/grpc_lb_v1/service" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import messages "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// LoadBalancerClient is the client API for LoadBalancer service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type LoadBalancerClient interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) -} - -type loadBalancerClient struct { - cc *grpc.ClientConn -} - -func NewLoadBalancerClient(cc *grpc.ClientConn) LoadBalancerClient { - return &loadBalancerClient{cc} -} - -func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...grpc.CallOption) (LoadBalancer_BalanceLoadClient, error) { - stream, err := c.cc.NewStream(ctx, &_LoadBalancer_serviceDesc.Streams[0], "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) - if err != nil { - return nil, err - } - x := &loadBalancerBalanceLoadClient{stream} - return x, nil -} - -type LoadBalancer_BalanceLoadClient interface { - Send(*messages.LoadBalanceRequest) error - Recv() (*messages.LoadBalanceResponse, error) - grpc.ClientStream -} - -type loadBalancerBalanceLoadClient struct { - grpc.ClientStream -} - -func (x *loadBalancerBalanceLoadClient) Send(m *messages.LoadBalanceRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadClient) Recv() (*messages.LoadBalanceResponse, error) { - m := new(messages.LoadBalanceResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// LoadBalancerServer is the server API for LoadBalancer service. -type LoadBalancerServer interface { - // Bidirectional rpc to get a list of servers. - BalanceLoad(LoadBalancer_BalanceLoadServer) error -} - -func RegisterLoadBalancerServer(s *grpc.Server, srv LoadBalancerServer) { - s.RegisterService(&_LoadBalancer_serviceDesc, srv) -} - -func _LoadBalancer_BalanceLoad_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(LoadBalancerServer).BalanceLoad(&loadBalancerBalanceLoadServer{stream}) -} - -type LoadBalancer_BalanceLoadServer interface { - Send(*messages.LoadBalanceResponse) error - Recv() (*messages.LoadBalanceRequest, error) - grpc.ServerStream -} - -type loadBalancerBalanceLoadServer struct { - grpc.ServerStream -} - -func (x *loadBalancerBalanceLoadServer) Send(m *messages.LoadBalanceResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *loadBalancerBalanceLoadServer) Recv() (*messages.LoadBalanceRequest, error) { - m := new(messages.LoadBalanceRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _LoadBalancer_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.lb.v1.LoadBalancer", - HandlerType: (*LoadBalancerServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "BalanceLoad", - Handler: _LoadBalancer_BalanceLoad_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_lb_v1/service/service.proto", -} - -func init() { - proto.RegisterFile("grpc_lb_v1/service/service.proto", fileDescriptor_service_8695ac2203226366) -} - -var fileDescriptor_service_8695ac2203226366 = []byte{ - // 166 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x8f, 0xbd, 0x0e, 0xc2, 0x40, - 0x08, 0x80, 0xd3, 0xc5, 0xe1, 0x74, 0xea, 0xd8, 0x41, 0x8d, 0x93, 0x13, 0xfd, 0xf1, 0x0d, 0x3a, - 0x3b, 0x75, 0x74, 0x69, 0xee, 0x2a, 0x21, 0x26, 0x58, 0xea, 0x51, 0xef, 0xf9, 0xcd, 0xd5, 0xbf, - 0x26, 0xc6, 0x05, 0xbe, 0xc0, 0x07, 0x01, 0xb3, 0x25, 0x3f, 0x74, 0x2d, 0xbb, 0x36, 0x94, 0xb9, - 0xa2, 0x0f, 0x97, 0x0e, 0xdf, 0x19, 0x06, 0x2f, 0xa3, 0xa4, 0x26, 0x1a, 0xc0, 0x0e, 0x42, 0x99, - 0xed, 0x66, 0xf6, 0x15, 0x55, 0x2d, 0xa1, 0x7e, 0xe0, 0xe9, 0x57, 0xce, 0xac, 0x8e, 0x62, 0xcf, - 0xb5, 0x65, 0xdb, 0x77, 0xe8, 0xd3, 0xc6, 0x2c, 0x5f, 0x1c, 0xcb, 0xe9, 0x1a, 0xbe, 0xfb, 0x60, - 0x26, 0x36, 0x78, 0xbb, 0xa3, 0x8e, 0xd9, 0xe6, 0x6f, 0x5f, 0x07, 0xe9, 0x15, 0xf7, 0x49, 0x91, - 0xd4, 0xd5, 0xa9, 0x20, 0x11, 0x62, 0x04, 0x12, 0xb6, 0x3d, 0x81, 0x78, 0xca, 0xe3, 0xdc, 0x14, - 0xd8, 0xe5, 0xbf, 0x5f, 0xb9, 0xc5, 0x74, 0xde, 0xe1, 0x11, 0x00, 0x00, 0xff, 0xff, 0x13, 0xde, - 0x84, 0x21, 0xf2, 0x00, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto b/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto deleted file mode 100755 index 6971fdb..0000000 --- a/examples/google.golang.org/grpc/grpclb/grpc_lb_v1/service/service.proto +++ /dev/null @@ -1,26 +0,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. - -syntax = "proto3"; - -package grpc.lb.v1; -option go_package = "google.golang.org/grpc/grpclb/grpc_lb_v1/service"; - -import "grpc_lb_v1/messages/messages.proto"; - -service LoadBalancer { - // Bidirectional rpc to get a list of servers. - rpc BalanceLoad(stream LoadBalanceRequest) - returns (stream LoadBalanceResponse); -} diff --git a/examples/google.golang.org/grpc/grpclb/noimport.go b/examples/google.golang.org/grpc/grpclb/noimport.go deleted file mode 100755 index b1b2429..0000000 --- a/examples/google.golang.org/grpc/grpclb/noimport.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * 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. - * - */ - -//go:generate protoc --go_out=plugins=:$GOPATH/src grpc_lb_v1/messages/messages.proto -//go:generate protoc --go_out=plugins=grpc:$GOPATH/src grpc_lb_v1/service/service.proto - -// Package grpclb is a dummy package for generating code. Look at balancer/grpclb instead. -package grpclb - -func init() { - panic("Don't import this package. For grpclb, see package google.golang.org/grpc/balancer/grpclb") -} diff --git a/examples/google.golang.org/grpc/grpclog/glogger/glogger.go b/examples/google.golang.org/grpc/grpclog/glogger/glogger.go deleted file mode 100755 index e5498f8..0000000 --- a/examples/google.golang.org/grpc/grpclog/glogger/glogger.go +++ /dev/null @@ -1,86 +0,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. - * - */ - -// Package glogger defines glog-based logging for grpc. -// Importing this package will install glog as the logger used by grpclog. -package glogger - -import ( - "fmt" - - "github.com/golang/glog" - "google.golang.org/grpc/grpclog" -) - -func init() { - grpclog.SetLoggerV2(&glogger{}) -} - -type glogger struct{} - -func (g *glogger) Info(args ...interface{}) { - glog.InfoDepth(2, args...) -} - -func (g *glogger) Infoln(args ...interface{}) { - glog.InfoDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Infof(format string, args ...interface{}) { - glog.InfoDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Warning(args ...interface{}) { - glog.WarningDepth(2, args...) -} - -func (g *glogger) Warningln(args ...interface{}) { - glog.WarningDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Warningf(format string, args ...interface{}) { - glog.WarningDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Error(args ...interface{}) { - glog.ErrorDepth(2, args...) -} - -func (g *glogger) Errorln(args ...interface{}) { - glog.ErrorDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Errorf(format string, args ...interface{}) { - glog.ErrorDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) Fatal(args ...interface{}) { - glog.FatalDepth(2, args...) -} - -func (g *glogger) Fatalln(args ...interface{}) { - glog.FatalDepth(2, fmt.Sprintln(args...)) -} - -func (g *glogger) Fatalf(format string, args ...interface{}) { - glog.FatalDepth(2, fmt.Sprintf(format, args...)) -} - -func (g *glogger) V(l int) bool { - return bool(glog.V(glog.Level(l))) -} diff --git a/examples/google.golang.org/grpc/grpclog/grpclog.go b/examples/google.golang.org/grpc/grpclog/grpclog.go deleted file mode 100755 index 1fabb11..0000000 --- a/examples/google.golang.org/grpc/grpclog/grpclog.go +++ /dev/null @@ -1,126 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package grpclog defines logging for grpc. -// -// All logs in transport package only go to verbose level 2. -// All logs in other packages in grpc are logged in spite of the verbosity level. -// -// In the default logger, -// severity level can be set by environment variable GRPC_GO_LOG_SEVERITY_LEVEL, -// verbosity level can be set by GRPC_GO_LOG_VERBOSITY_LEVEL. -package grpclog // import "google.golang.org/grpc/grpclog" - -import "os" - -var logger = newLoggerV2() - -// V reports whether verbosity level l is at least the requested verbose level. -func V(l int) bool { - return logger.V(l) -} - -// Info logs to the INFO log. -func Info(args ...interface{}) { - logger.Info(args...) -} - -// Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf. -func Infof(format string, args ...interface{}) { - logger.Infof(format, args...) -} - -// Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println. -func Infoln(args ...interface{}) { - logger.Infoln(args...) -} - -// Warning logs to the WARNING log. -func Warning(args ...interface{}) { - logger.Warning(args...) -} - -// Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf. -func Warningf(format string, args ...interface{}) { - logger.Warningf(format, args...) -} - -// Warningln logs to the WARNING log. Arguments are handled in the manner of fmt.Println. -func Warningln(args ...interface{}) { - logger.Warningln(args...) -} - -// Error logs to the ERROR log. -func Error(args ...interface{}) { - logger.Error(args...) -} - -// Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf. -func Errorf(format string, args ...interface{}) { - logger.Errorf(format, args...) -} - -// Errorln logs to the ERROR log. Arguments are handled in the manner of fmt.Println. -func Errorln(args ...interface{}) { - logger.Errorln(args...) -} - -// Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Print. -// It calls os.Exit() with exit code 1. -func Fatal(args ...interface{}) { - logger.Fatal(args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf. -// It calles os.Exit() with exit code 1. -func Fatalf(format string, args ...interface{}) { - logger.Fatalf(format, args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Fatalln logs to the FATAL log. Arguments are handled in the manner of fmt.Println. -// It calle os.Exit()) with exit code 1. -func Fatalln(args ...interface{}) { - logger.Fatalln(args...) - // Make sure fatal logs will exit. - os.Exit(1) -} - -// Print prints to the logger. Arguments are handled in the manner of fmt.Print. -// -// Deprecated: use Info. -func Print(args ...interface{}) { - logger.Info(args...) -} - -// Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. -// -// Deprecated: use Infof. -func Printf(format string, args ...interface{}) { - logger.Infof(format, args...) -} - -// Println prints to the logger. Arguments are handled in the manner of fmt.Println. -// -// Deprecated: use Infoln. -func Println(args ...interface{}) { - logger.Infoln(args...) -} diff --git a/examples/google.golang.org/grpc/grpclog/logger.go b/examples/google.golang.org/grpc/grpclog/logger.go deleted file mode 100755 index 097494f..0000000 --- a/examples/google.golang.org/grpc/grpclog/logger.go +++ /dev/null @@ -1,85 +0,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. - * - */ - -package grpclog - -// Logger mimics golang's standard Logger as an interface. -// -// Deprecated: use LoggerV2. -type Logger interface { - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Fatalln(args ...interface{}) - Print(args ...interface{}) - Printf(format string, args ...interface{}) - Println(args ...interface{}) -} - -// SetLogger sets the logger that is used in grpc. Call only from -// init() functions. -// -// Deprecated: use SetLoggerV2. -func SetLogger(l Logger) { - logger = &loggerWrapper{Logger: l} -} - -// loggerWrapper wraps Logger into a LoggerV2. -type loggerWrapper struct { - Logger -} - -func (g *loggerWrapper) Info(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Infoln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Infof(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) Warning(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Warningln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Warningf(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) Error(args ...interface{}) { - g.Logger.Print(args...) -} - -func (g *loggerWrapper) Errorln(args ...interface{}) { - g.Logger.Println(args...) -} - -func (g *loggerWrapper) Errorf(format string, args ...interface{}) { - g.Logger.Printf(format, args...) -} - -func (g *loggerWrapper) V(l int) bool { - // Returns true for all verbose level. - return true -} diff --git a/examples/google.golang.org/grpc/grpclog/loggerv2.go b/examples/google.golang.org/grpc/grpclog/loggerv2.go deleted file mode 100755 index d493257..0000000 --- a/examples/google.golang.org/grpc/grpclog/loggerv2.go +++ /dev/null @@ -1,195 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpclog - -import ( - "io" - "io/ioutil" - "log" - "os" - "strconv" -) - -// LoggerV2 does underlying logging work for grpclog. -type LoggerV2 interface { - // Info logs to INFO log. Arguments are handled in the manner of fmt.Print. - Info(args ...interface{}) - // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. - Infoln(args ...interface{}) - // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. - Infof(format string, args ...interface{}) - // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print. - Warning(args ...interface{}) - // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. - Warningln(args ...interface{}) - // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. - Warningf(format string, args ...interface{}) - // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print. - Error(args ...interface{}) - // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - Errorln(args ...interface{}) - // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - Errorf(format string, args ...interface{}) - // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatal(args ...interface{}) - // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatalln(args ...interface{}) - // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. - // gRPC ensures that all Fatal logs will exit with os.Exit(1). - // Implementations may also call os.Exit() with a non-zero exit code. - Fatalf(format string, args ...interface{}) - // V reports whether verbosity level l is at least the requested verbose level. - V(l int) bool -} - -// SetLoggerV2 sets logger that is used in grpc to a V2 logger. -// Not mutex-protected, should be called before any gRPC functions. -func SetLoggerV2(l LoggerV2) { - logger = l -} - -const ( - // infoLog indicates Info severity. - infoLog int = iota - // warningLog indicates Warning severity. - warningLog - // errorLog indicates Error severity. - errorLog - // fatalLog indicates Fatal severity. - fatalLog -) - -// severityName contains the string representation of each severity. -var severityName = []string{ - infoLog: "INFO", - warningLog: "WARNING", - errorLog: "ERROR", - fatalLog: "FATAL", -} - -// loggerT is the default logger used by grpclog. -type loggerT struct { - m []*log.Logger - v int -} - -// NewLoggerV2 creates a loggerV2 with the provided writers. -// Fatal logs will be written to errorW, warningW, infoW, followed by exit(1). -// Error logs will be written to errorW, warningW and infoW. -// Warning logs will be written to warningW and infoW. -// Info logs will be written to infoW. -func NewLoggerV2(infoW, warningW, errorW io.Writer) LoggerV2 { - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, 0) -} - -// NewLoggerV2WithVerbosity creates a loggerV2 with the provided writers and -// verbosity level. -func NewLoggerV2WithVerbosity(infoW, warningW, errorW io.Writer, v int) LoggerV2 { - var m []*log.Logger - m = append(m, log.New(infoW, severityName[infoLog]+": ", log.LstdFlags)) - m = append(m, log.New(io.MultiWriter(infoW, warningW), severityName[warningLog]+": ", log.LstdFlags)) - ew := io.MultiWriter(infoW, warningW, errorW) // ew will be used for error and fatal. - m = append(m, log.New(ew, severityName[errorLog]+": ", log.LstdFlags)) - m = append(m, log.New(ew, severityName[fatalLog]+": ", log.LstdFlags)) - return &loggerT{m: m, v: v} -} - -// newLoggerV2 creates a loggerV2 to be used as default logger. -// All logs are written to stderr. -func newLoggerV2() LoggerV2 { - errorW := ioutil.Discard - warningW := ioutil.Discard - infoW := ioutil.Discard - - logLevel := os.Getenv("GRPC_GO_LOG_SEVERITY_LEVEL") - switch logLevel { - case "", "ERROR", "error": // If env is unset, set level to ERROR. - errorW = os.Stderr - case "WARNING", "warning": - warningW = os.Stderr - case "INFO", "info": - infoW = os.Stderr - } - - var v int - vLevel := os.Getenv("GRPC_GO_LOG_VERBOSITY_LEVEL") - if vl, err := strconv.Atoi(vLevel); err == nil { - v = vl - } - return NewLoggerV2WithVerbosity(infoW, warningW, errorW, v) -} - -func (g *loggerT) Info(args ...interface{}) { - g.m[infoLog].Print(args...) -} - -func (g *loggerT) Infoln(args ...interface{}) { - g.m[infoLog].Println(args...) -} - -func (g *loggerT) Infof(format string, args ...interface{}) { - g.m[infoLog].Printf(format, args...) -} - -func (g *loggerT) Warning(args ...interface{}) { - g.m[warningLog].Print(args...) -} - -func (g *loggerT) Warningln(args ...interface{}) { - g.m[warningLog].Println(args...) -} - -func (g *loggerT) Warningf(format string, args ...interface{}) { - g.m[warningLog].Printf(format, args...) -} - -func (g *loggerT) Error(args ...interface{}) { - g.m[errorLog].Print(args...) -} - -func (g *loggerT) Errorln(args ...interface{}) { - g.m[errorLog].Println(args...) -} - -func (g *loggerT) Errorf(format string, args ...interface{}) { - g.m[errorLog].Printf(format, args...) -} - -func (g *loggerT) Fatal(args ...interface{}) { - g.m[fatalLog].Fatal(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) Fatalln(args ...interface{}) { - g.m[fatalLog].Fatalln(args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) Fatalf(format string, args ...interface{}) { - g.m[fatalLog].Fatalf(format, args...) - // No need to call os.Exit() again because log.Logger.Fatal() calls os.Exit(). -} - -func (g *loggerT) V(l int) bool { - return l <= g.v -} diff --git a/examples/google.golang.org/grpc/grpclog/loggerv2_test.go b/examples/google.golang.org/grpc/grpclog/loggerv2_test.go deleted file mode 100755 index 756f215..0000000 --- a/examples/google.golang.org/grpc/grpclog/loggerv2_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpclog - -import ( - "bytes" - "fmt" - "regexp" - "testing" -) - -func TestLoggerV2Severity(t *testing.T) { - buffers := []*bytes.Buffer{new(bytes.Buffer), new(bytes.Buffer), new(bytes.Buffer)} - SetLoggerV2(NewLoggerV2(buffers[infoLog], buffers[warningLog], buffers[errorLog])) - - Info(severityName[infoLog]) - Warning(severityName[warningLog]) - Error(severityName[errorLog]) - - for i := 0; i < fatalLog; i++ { - buf := buffers[i] - // The content of info buffer should be something like: - // INFO: 2017/04/07 14:55:42 INFO - // WARNING: 2017/04/07 14:55:42 WARNING - // ERROR: 2017/04/07 14:55:42 ERROR - for j := i; j < fatalLog; j++ { - b, err := buf.ReadBytes('\n') - if err != nil { - t.Fatal(err) - } - if err := checkLogForSeverity(j, b); err != nil { - t.Fatal(err) - } - } - } -} - -// check if b is in the format of: -// WARNING: 2017/04/07 14:55:42 WARNING -func checkLogForSeverity(s int, b []byte) error { - expected := regexp.MustCompile(fmt.Sprintf(`^%s: [0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} %s\n$`, severityName[s], severityName[s])) - if m := expected.Match(b); !m { - return fmt.Errorf("got: %v, want string in format of: %v", string(b), severityName[s]+": 2016/10/05 17:09:26 "+severityName[s]) - } - return nil -} diff --git a/examples/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/examples/google.golang.org/grpc/health/grpc_health_v1/health.pb.go deleted file mode 100755 index a1fda28..0000000 --- a/examples/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ /dev/null @@ -1,227 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/health/v1/health.proto - -package grpc_health_v1 // import "google.golang.org/grpc/health/grpc_health_v1" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type HealthCheckResponse_ServingStatus int32 - -const ( - HealthCheckResponse_UNKNOWN HealthCheckResponse_ServingStatus = 0 - HealthCheckResponse_SERVING HealthCheckResponse_ServingStatus = 1 - HealthCheckResponse_NOT_SERVING HealthCheckResponse_ServingStatus = 2 -) - -var HealthCheckResponse_ServingStatus_name = map[int32]string{ - 0: "UNKNOWN", - 1: "SERVING", - 2: "NOT_SERVING", -} -var HealthCheckResponse_ServingStatus_value = map[string]int32{ - "UNKNOWN": 0, - "SERVING": 1, - "NOT_SERVING": 2, -} - -func (x HealthCheckResponse_ServingStatus) String() string { - return proto.EnumName(HealthCheckResponse_ServingStatus_name, int32(x)) -} -func (HealthCheckResponse_ServingStatus) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_health_85731b6c49265086, []int{1, 0} -} - -type HealthCheckRequest struct { - Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HealthCheckRequest) Reset() { *m = HealthCheckRequest{} } -func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) } -func (*HealthCheckRequest) ProtoMessage() {} -func (*HealthCheckRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_health_85731b6c49265086, []int{0} -} -func (m *HealthCheckRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HealthCheckRequest.Unmarshal(m, b) -} -func (m *HealthCheckRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HealthCheckRequest.Marshal(b, m, deterministic) -} -func (dst *HealthCheckRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_HealthCheckRequest.Merge(dst, src) -} -func (m *HealthCheckRequest) XXX_Size() int { - return xxx_messageInfo_HealthCheckRequest.Size(m) -} -func (m *HealthCheckRequest) XXX_DiscardUnknown() { - xxx_messageInfo_HealthCheckRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_HealthCheckRequest proto.InternalMessageInfo - -func (m *HealthCheckRequest) GetService() string { - if m != nil { - return m.Service - } - return "" -} - -type HealthCheckResponse struct { - Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=grpc.health.v1.HealthCheckResponse_ServingStatus" json:"status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HealthCheckResponse) Reset() { *m = HealthCheckResponse{} } -func (m *HealthCheckResponse) String() string { return proto.CompactTextString(m) } -func (*HealthCheckResponse) ProtoMessage() {} -func (*HealthCheckResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_health_85731b6c49265086, []int{1} -} -func (m *HealthCheckResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HealthCheckResponse.Unmarshal(m, b) -} -func (m *HealthCheckResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HealthCheckResponse.Marshal(b, m, deterministic) -} -func (dst *HealthCheckResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_HealthCheckResponse.Merge(dst, src) -} -func (m *HealthCheckResponse) XXX_Size() int { - return xxx_messageInfo_HealthCheckResponse.Size(m) -} -func (m *HealthCheckResponse) XXX_DiscardUnknown() { - xxx_messageInfo_HealthCheckResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_HealthCheckResponse proto.InternalMessageInfo - -func (m *HealthCheckResponse) GetStatus() HealthCheckResponse_ServingStatus { - if m != nil { - return m.Status - } - return HealthCheckResponse_UNKNOWN -} - -func init() { - proto.RegisterType((*HealthCheckRequest)(nil), "grpc.health.v1.HealthCheckRequest") - proto.RegisterType((*HealthCheckResponse)(nil), "grpc.health.v1.HealthCheckResponse") - proto.RegisterEnum("grpc.health.v1.HealthCheckResponse_ServingStatus", HealthCheckResponse_ServingStatus_name, HealthCheckResponse_ServingStatus_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// HealthClient is the client API for Health service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type HealthClient interface { - Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) -} - -type healthClient struct { - cc *grpc.ClientConn -} - -func NewHealthClient(cc *grpc.ClientConn) HealthClient { - return &healthClient{cc} -} - -func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { - out := new(HealthCheckResponse) - err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// HealthServer is the server API for Health service. -type HealthServer interface { - Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) -} - -func RegisterHealthServer(s *grpc.Server, srv HealthServer) { - s.RegisterService(&_Health_serviceDesc, srv) -} - -func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HealthCheckRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(HealthServer).Check(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.health.v1.Health/Check", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Health_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.health.v1.Health", - HandlerType: (*HealthServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Check", - Handler: _Health_Check_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc/health/v1/health.proto", -} - -func init() { proto.RegisterFile("grpc/health/v1/health.proto", fileDescriptor_health_85731b6c49265086) } - -var fileDescriptor_health_85731b6c49265086 = []byte{ - // 271 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0x2f, 0x2a, 0x48, - 0xd6, 0xcf, 0x48, 0x4d, 0xcc, 0x29, 0xc9, 0xd0, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, - 0x4b, 0xf2, 0x85, 0xf8, 0x40, 0x92, 0x7a, 0x50, 0xa1, 0x32, 0x43, 0x25, 0x3d, 0x2e, 0x21, 0x0f, - 0x30, 0xc7, 0x39, 0x23, 0x35, 0x39, 0x3b, 0x28, 0xb5, 0xb0, 0x34, 0xb5, 0xb8, 0x44, 0x48, 0x82, - 0x8b, 0xbd, 0x38, 0xb5, 0xa8, 0x2c, 0x33, 0x39, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x08, - 0xc6, 0x55, 0x9a, 0xc3, 0xc8, 0x25, 0x8c, 0xa2, 0xa1, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0xc8, - 0x93, 0x8b, 0xad, 0xb8, 0x24, 0xb1, 0xa4, 0xb4, 0x18, 0xac, 0x81, 0xcf, 0xc8, 0x50, 0x0f, 0xd5, - 0x22, 0x3d, 0x2c, 0x9a, 0xf4, 0x82, 0x41, 0x86, 0xe6, 0xa5, 0x07, 0x83, 0x35, 0x06, 0x41, 0x0d, - 0x50, 0xb2, 0xe2, 0xe2, 0x45, 0x91, 0x10, 0xe2, 0xe6, 0x62, 0x0f, 0xf5, 0xf3, 0xf6, 0xf3, 0x0f, - 0xf7, 0x13, 0x60, 0x00, 0x71, 0x82, 0x5d, 0x83, 0xc2, 0x3c, 0xfd, 0xdc, 0x05, 0x18, 0x85, 0xf8, - 0xb9, 0xb8, 0xfd, 0xfc, 0x43, 0xe2, 0x61, 0x02, 0x4c, 0x46, 0x51, 0x5c, 0x6c, 0x10, 0x8b, 0x84, - 0x02, 0xb8, 0x58, 0xc1, 0x96, 0x09, 0x29, 0xe1, 0x75, 0x09, 0xd8, 0xbf, 0x52, 0xca, 0x44, 0xb8, - 0xd6, 0x29, 0x91, 0x4b, 0x30, 0x33, 0x1f, 0x4d, 0xa1, 0x13, 0x37, 0x44, 0x65, 0x00, 0x28, 0x70, - 0x03, 0x18, 0xa3, 0x74, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0xd2, 0xf3, 0x73, 0x12, 0xf3, - 0xd2, 0xf5, 0xf2, 0x8b, 0xd2, 0xf5, 0x91, 0x63, 0x03, 0xc4, 0x8e, 0x87, 0xb0, 0xe3, 0xcb, 0x0c, - 0x57, 0x31, 0xf1, 0xb9, 0x83, 0x4c, 0x83, 0x18, 0xa1, 0x17, 0x66, 0x98, 0xc4, 0x06, 0x8e, 0x24, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xec, 0x66, 0x81, 0xcb, 0xc3, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/health/health.go b/examples/google.golang.org/grpc/health/health.go deleted file mode 100755 index c258886..0000000 --- a/examples/google.golang.org/grpc/health/health.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate ./regenerate.sh - -// Package health provides some utility functions to health-check a server. The implementation -// is based on protobuf. Users need to write their own implementations if other IDLs are used. -package health - -import ( - "sync" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - healthpb "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/status" -) - -// Server implements `service Health`. -type Server struct { - mu sync.Mutex - // statusMap stores the serving status of the services this Server monitors. - statusMap map[string]healthpb.HealthCheckResponse_ServingStatus -} - -// NewServer returns a new Server. -func NewServer() *Server { - return &Server{ - statusMap: make(map[string]healthpb.HealthCheckResponse_ServingStatus), - } -} - -// Check implements `service Health`. -func (s *Server) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { - s.mu.Lock() - defer s.mu.Unlock() - if in.Service == "" { - // check the server overall health status. - return &healthpb.HealthCheckResponse{ - Status: healthpb.HealthCheckResponse_SERVING, - }, nil - } - if status, ok := s.statusMap[in.Service]; ok { - return &healthpb.HealthCheckResponse{ - Status: status, - }, nil - } - return nil, status.Error(codes.NotFound, "unknown service") -} - -// SetServingStatus is called when need to reset the serving status of a service -// or insert a new service entry into the statusMap. -func (s *Server) SetServingStatus(service string, status healthpb.HealthCheckResponse_ServingStatus) { - s.mu.Lock() - s.statusMap[service] = status - s.mu.Unlock() -} diff --git a/examples/google.golang.org/grpc/health/regenerate.sh b/examples/google.golang.org/grpc/health/regenerate.sh deleted file mode 100755 index b11eccb..0000000 --- a/examples/google.golang.org/grpc/health/regenerate.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/health/v1 -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/health/v1/health.proto > grpc/health/v1/health.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/health/v1/*.proto -popd -rm -f grpc_health_v1/*.pb.go -cp "$TMP"/grpc/health/v1/*.pb.go grpc_health_v1/ - diff --git a/examples/google.golang.org/grpc/interceptor.go b/examples/google.golang.org/grpc/interceptor.go deleted file mode 100755 index 1f6ef67..0000000 --- a/examples/google.golang.org/grpc/interceptor.go +++ /dev/null @@ -1,77 +0,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. - * - */ - -package grpc - -import ( - "golang.org/x/net/context" -) - -// UnaryInvoker is called by UnaryClientInterceptor to complete RPCs. -type UnaryInvoker func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error - -// UnaryClientInterceptor intercepts the execution of a unary RPC on the client. invoker is the handler to complete the RPC -// and it is the responsibility of the interceptor to call it. -// This is an EXPERIMENTAL API. -type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error - -// Streamer is called by StreamClientInterceptor to create a ClientStream. -type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) - -// StreamClientInterceptor intercepts the creation of ClientStream. It may return a custom ClientStream to intercept all I/O -// operations. streamer is the handler to create a ClientStream and it is the responsibility of the interceptor to call it. -// This is an EXPERIMENTAL API. -type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) - -// UnaryServerInfo consists of various information about a unary RPC on -// server side. All per-rpc information may be mutated by the interceptor. -type UnaryServerInfo struct { - // Server is the service implementation the user provides. This is read-only. - Server interface{} - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string -} - -// UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal -// execution of a unary RPC. If a UnaryHandler returns an error, it should be produced by the -// status package, or else gRPC will use codes.Unknown as the status code and err.Error() as -// the status message of the RPC. -type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) - -// UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info -// contains all the information of this RPC the interceptor can operate on. And handler is the wrapper -// of the service method implementation. It is the responsibility of the interceptor to invoke handler -// to complete the RPC. -type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error) - -// StreamServerInfo consists of various information about a streaming RPC on -// server side. All per-rpc information may be mutated by the interceptor. -type StreamServerInfo struct { - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // IsClientStream indicates whether the RPC is a client streaming RPC. - IsClientStream bool - // IsServerStream indicates whether the RPC is a server streaming RPC. - IsServerStream bool -} - -// StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server. -// info contains all the information of this RPC the interceptor can operate on. And handler is the -// service method implementation. It is the responsibility of the interceptor to invoke handler to -// complete the RPC. -type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error diff --git a/examples/google.golang.org/grpc/internal/backoff/backoff.go b/examples/google.golang.org/grpc/internal/backoff/backoff.go deleted file mode 100755 index 1bd0cce..0000000 --- a/examples/google.golang.org/grpc/internal/backoff/backoff.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package backoff implement the backoff strategy for gRPC. -// -// This is kept in internal until the gRPC project decides whether or not to -// allow alternative backoff strategies. -package backoff - -import ( - "time" - - "google.golang.org/grpc/internal/grpcrand" -) - -// Strategy defines the methodology for backing off after a grpc connection -// failure. -// -type Strategy interface { - // Backoff returns the amount of time to wait before the next retry given - // the number of consecutive failures. - Backoff(retries int) time.Duration -} - -const ( - // baseDelay is the amount of time to wait before retrying after the first - // failure. - baseDelay = 1.0 * time.Second - // factor is applied to the backoff after each retry. - factor = 1.6 - // jitter provides a range to randomize backoff delays. - jitter = 0.2 -) - -// Exponential implements exponential backoff algorithm as defined in -// https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. -type Exponential struct { - // MaxDelay is the upper bound of backoff delay. - MaxDelay time.Duration -} - -// Backoff returns the amount of time to wait before the next retry given the -// number of retries. -func (bc Exponential) Backoff(retries int) time.Duration { - if retries == 0 { - return baseDelay - } - backoff, max := float64(baseDelay), float64(bc.MaxDelay) - for backoff < max && retries > 0 { - backoff *= factor - retries-- - } - if backoff > max { - backoff = max - } - // Randomize backoff delays so that if a cluster of requests start at - // the same time, they won't operate in lockstep. - backoff *= 1 + jitter*(grpcrand.Float64()*2-1) - if backoff < 0 { - return 0 - } - return time.Duration(backoff) -} diff --git a/examples/google.golang.org/grpc/internal/channelz/funcs.go b/examples/google.golang.org/grpc/internal/channelz/funcs.go deleted file mode 100755 index 586a033..0000000 --- a/examples/google.golang.org/grpc/internal/channelz/funcs.go +++ /dev/null @@ -1,573 +0,0 @@ -/* - * - * 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. - * - */ - -// Package channelz defines APIs for enabling channelz service, entry -// registration/deletion, and accessing channelz data. It also defines channelz -// metric struct formats. -// -// All APIs in this package are experimental. -package channelz - -import ( - "sort" - "sync" - "sync/atomic" - - "google.golang.org/grpc/grpclog" -) - -var ( - db dbWrapper - idGen idGenerator - // EntryPerPage defines the number of channelz entries to be shown on a web page. - EntryPerPage = 50 - curState int32 -) - -// TurnOn turns on channelz data collection. -func TurnOn() { - if !IsOn() { - NewChannelzStorage() - atomic.StoreInt32(&curState, 1) - } -} - -// IsOn returns whether channelz data collection is on. -func IsOn() bool { - return atomic.CompareAndSwapInt32(&curState, 1, 1) -} - -// dbWarpper wraps around a reference to internal channelz data storage, and -// provide synchronized functionality to set and get the reference. -type dbWrapper struct { - mu sync.RWMutex - DB *channelMap -} - -func (d *dbWrapper) set(db *channelMap) { - d.mu.Lock() - d.DB = db - d.mu.Unlock() -} - -func (d *dbWrapper) get() *channelMap { - d.mu.RLock() - defer d.mu.RUnlock() - return d.DB -} - -// NewChannelzStorage initializes channelz data storage and id generator. -// -// Note: This function is exported for testing purpose only. User should not call -// it in most cases. -func NewChannelzStorage() { - db.set(&channelMap{ - topLevelChannels: make(map[int64]struct{}), - channels: make(map[int64]*channel), - listenSockets: make(map[int64]*listenSocket), - normalSockets: make(map[int64]*normalSocket), - servers: make(map[int64]*server), - subChannels: make(map[int64]*subChannel), - }) - idGen.reset() -} - -// GetTopChannels returns a slice of top channel's ChannelMetric, along with a -// boolean indicating whether there's more top channels to be queried for. -// -// The arg id specifies that only top channel with id at or above it will be included -// in the result. The returned slice is up to a length of EntryPerPage, and is -// sorted in ascending id order. -func GetTopChannels(id int64) ([]*ChannelMetric, bool) { - return db.get().GetTopChannels(id) -} - -// GetServers returns a slice of server's ServerMetric, along with a -// boolean indicating whether there's more servers to be queried for. -// -// The arg id specifies that only server with id at or above it will be included -// in the result. The returned slice is up to a length of EntryPerPage, and is -// sorted in ascending id order. -func GetServers(id int64) ([]*ServerMetric, bool) { - return db.get().GetServers(id) -} - -// GetServerSockets returns a slice of server's (identified by id) normal socket's -// SocketMetric, along with a boolean indicating whether there's more sockets to -// be queried for. -// -// The arg startID specifies that only sockets with id at or above it will be -// included in the result. The returned slice is up to a length of EntryPerPage, -// and is sorted in ascending id order. -func GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { - return db.get().GetServerSockets(id, startID) -} - -// GetChannel returns the ChannelMetric for the channel (identified by id). -func GetChannel(id int64) *ChannelMetric { - return db.get().GetChannel(id) -} - -// GetSubChannel returns the SubChannelMetric for the subchannel (identified by id). -func GetSubChannel(id int64) *SubChannelMetric { - return db.get().GetSubChannel(id) -} - -// GetSocket returns the SocketInternalMetric for the socket (identified by id). -func GetSocket(id int64) *SocketMetric { - return db.get().GetSocket(id) -} - -// RegisterChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). pid = 0 means no parent. It returns the unique channelz tracking id -// assigned to this channel. -func RegisterChannel(c Channel, pid int64, ref string) int64 { - id := idGen.genID() - cn := &channel{ - refName: ref, - c: c, - subChans: make(map[int64]string), - nestedChans: make(map[int64]string), - id: id, - pid: pid, - } - if pid == 0 { - db.get().addChannel(id, cn, true, pid, ref) - } else { - db.get().addChannel(id, cn, false, pid, ref) - } - return id -} - -// RegisterSubChannel registers the given channel c in channelz database with ref -// as its reference name, and add it to the child list of its parent (identified -// by pid). It returns the unique channelz tracking id assigned to this subchannel. -func RegisterSubChannel(c Channel, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a SubChannel's parent id cannot be 0") - return 0 - } - id := idGen.genID() - sc := &subChannel{ - refName: ref, - c: c, - sockets: make(map[int64]string), - id: id, - pid: pid, - } - db.get().addSubChannel(id, sc, pid, ref) - return id -} - -// RegisterServer registers the given server s in channelz database. It returns -// the unique channelz tracking id assigned to this server. -func RegisterServer(s Server, ref string) int64 { - id := idGen.genID() - svr := &server{ - refName: ref, - s: s, - sockets: make(map[int64]string), - listenSockets: make(map[int64]string), - id: id, - } - db.get().addServer(id, svr) - return id -} - -// RegisterListenSocket registers the given listen socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent -// (identified by pid). It returns the unique channelz tracking id assigned to -// this listen socket. -func RegisterListenSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a ListenSocket's parent id cannot be 0") - return 0 - } - id := idGen.genID() - ls := &listenSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addListenSocket(id, ls, pid, ref) - return id -} - -// RegisterNormalSocket registers the given normal socket s in channelz database -// with ref as its reference name, and add it to the child list of its parent -// (identified by pid). It returns the unique channelz tracking id assigned to -// this normal socket. -func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { - if pid == 0 { - grpclog.Error("a NormalSocket's parent id cannot be 0") - return 0 - } - id := idGen.genID() - ns := &normalSocket{refName: ref, s: s, id: id, pid: pid} - db.get().addNormalSocket(id, ns, pid, ref) - return id -} - -// RemoveEntry removes an entry with unique channelz trakcing id to be id from -// channelz database. -func RemoveEntry(id int64) { - db.get().removeEntry(id) -} - -// channelMap is the storage data structure for channelz. -// Methods of channelMap can be divided in two two categories with respect to locking. -// 1. Methods acquire the global lock. -// 2. Methods that can only be called when global lock is held. -// A second type of method need always to be called inside a first type of method. -type channelMap struct { - mu sync.RWMutex - topLevelChannels map[int64]struct{} - servers map[int64]*server - channels map[int64]*channel - subChannels map[int64]*subChannel - listenSockets map[int64]*listenSocket - normalSockets map[int64]*normalSocket -} - -func (c *channelMap) addServer(id int64, s *server) { - c.mu.Lock() - s.cm = c - c.servers[id] = s - c.mu.Unlock() -} - -func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64, ref string) { - c.mu.Lock() - cn.cm = c - c.channels[id] = cn - if isTopChannel { - c.topLevelChannels[id] = struct{}{} - } else { - c.findEntry(pid).addChild(id, cn) - } - c.mu.Unlock() -} - -func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref string) { - c.mu.Lock() - sc.cm = c - c.subChannels[id] = sc - c.findEntry(pid).addChild(id, sc) - c.mu.Unlock() -} - -func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref string) { - c.mu.Lock() - ls.cm = c - c.listenSockets[id] = ls - c.findEntry(pid).addChild(id, ls) - c.mu.Unlock() -} - -func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64, ref string) { - c.mu.Lock() - ns.cm = c - c.normalSockets[id] = ns - c.findEntry(pid).addChild(id, ns) - c.mu.Unlock() -} - -// removeEntry triggers the removal of an entry, which may not indeed delete the -// entry, if it has to wait on the deletion of its children, or may lead to a chain -// of entry deletion. For example, deleting the last socket of a gracefully shutting -// down server will lead to the server being also deleted. -func (c *channelMap) removeEntry(id int64) { - c.mu.Lock() - c.findEntry(id).triggerDelete() - c.mu.Unlock() -} - -// c.mu must be held by the caller. -func (c *channelMap) findEntry(id int64) entry { - var v entry - var ok bool - if v, ok = c.channels[id]; ok { - return v - } - if v, ok = c.subChannels[id]; ok { - return v - } - if v, ok = c.servers[id]; ok { - return v - } - if v, ok = c.listenSockets[id]; ok { - return v - } - if v, ok = c.normalSockets[id]; ok { - return v - } - return &dummyEntry{idNotFound: id} -} - -// c.mu must be held by the caller -// deleteEntry simply deletes an entry from the channelMap. Before calling this -// method, caller must check this entry is ready to be deleted, i.e removeEntry() -// has been called on it, and no children still exist. -// Conditionals are ordered by the expected frequency of deletion of each entity -// type, in order to optimize performance. -func (c *channelMap) deleteEntry(id int64) { - var ok bool - if _, ok = c.normalSockets[id]; ok { - delete(c.normalSockets, id) - return - } - if _, ok = c.subChannels[id]; ok { - delete(c.subChannels, id) - return - } - if _, ok = c.channels[id]; ok { - delete(c.channels, id) - delete(c.topLevelChannels, id) - return - } - if _, ok = c.listenSockets[id]; ok { - delete(c.listenSockets, id) - return - } - if _, ok = c.servers[id]; ok { - delete(c.servers, id) - return - } -} - -type int64Slice []int64 - -func (s int64Slice) Len() int { return len(s) } -func (s int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s int64Slice) Less(i, j int) bool { return s[i] < s[j] } - -func copyMap(m map[int64]string) map[int64]string { - n := make(map[int64]string) - for k, v := range m { - n[k] = v - } - return n -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func (c *channelMap) GetTopChannels(id int64) ([]*ChannelMetric, bool) { - c.mu.RLock() - l := len(c.topLevelChannels) - ids := make([]int64, 0, l) - cns := make([]*channel, 0, min(l, EntryPerPage)) - - for k := range c.topLevelChannels { - ids = append(ids, k) - } - sort.Sort(int64Slice(ids)) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - var t []*ChannelMetric - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if cn, ok := c.channels[v]; ok { - cns = append(cns, cn) - t = append(t, &ChannelMetric{ - NestedChans: copyMap(cn.nestedChans), - SubChans: copyMap(cn.subChans), - }) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - - for i, cn := range cns { - t[i].ChannelData = cn.c.ChannelzMetric() - t[i].ID = cn.id - t[i].RefName = cn.refName - } - return t, end -} - -func (c *channelMap) GetServers(id int64) ([]*ServerMetric, bool) { - c.mu.RLock() - l := len(c.servers) - ids := make([]int64, 0, l) - ss := make([]*server, 0, min(l, EntryPerPage)) - for k := range c.servers { - ids = append(ids, k) - } - sort.Sort(int64Slice(ids)) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - var s []*ServerMetric - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if svr, ok := c.servers[v]; ok { - ss = append(ss, svr) - s = append(s, &ServerMetric{ - ListenSockets: copyMap(svr.listenSockets), - }) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - - for i, svr := range ss { - s[i].ServerData = svr.s.ChannelzMetric() - s[i].ID = svr.id - s[i].RefName = svr.refName - } - return s, end -} - -func (c *channelMap) GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { - var svr *server - var ok bool - c.mu.RLock() - if svr, ok = c.servers[id]; !ok { - // server with id doesn't exist. - c.mu.RUnlock() - return nil, true - } - svrskts := svr.sockets - l := len(svrskts) - ids := make([]int64, 0, l) - sks := make([]*normalSocket, 0, min(l, EntryPerPage)) - for k := range svrskts { - ids = append(ids, k) - } - sort.Sort((int64Slice(ids))) - idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) - count := 0 - var end bool - for i, v := range ids[idx:] { - if count == EntryPerPage { - break - } - if ns, ok := c.normalSockets[v]; ok { - sks = append(sks, ns) - count++ - } - if i == len(ids[idx:])-1 { - end = true - break - } - } - c.mu.RUnlock() - if count == 0 { - end = true - } - var s []*SocketMetric - for _, ns := range sks { - sm := &SocketMetric{} - sm.SocketData = ns.s.ChannelzMetric() - sm.ID = ns.id - sm.RefName = ns.refName - s = append(s, sm) - } - return s, end -} - -func (c *channelMap) GetChannel(id int64) *ChannelMetric { - cm := &ChannelMetric{} - var cn *channel - var ok bool - c.mu.RLock() - if cn, ok = c.channels[id]; !ok { - // channel with id doesn't exist. - c.mu.RUnlock() - return nil - } - cm.NestedChans = copyMap(cn.nestedChans) - cm.SubChans = copyMap(cn.subChans) - c.mu.RUnlock() - cm.ChannelData = cn.c.ChannelzMetric() - cm.ID = cn.id - cm.RefName = cn.refName - return cm -} - -func (c *channelMap) GetSubChannel(id int64) *SubChannelMetric { - cm := &SubChannelMetric{} - var sc *subChannel - var ok bool - c.mu.RLock() - if sc, ok = c.subChannels[id]; !ok { - // subchannel with id doesn't exist. - c.mu.RUnlock() - return nil - } - cm.Sockets = copyMap(sc.sockets) - c.mu.RUnlock() - cm.ChannelData = sc.c.ChannelzMetric() - cm.ID = sc.id - cm.RefName = sc.refName - return cm -} - -func (c *channelMap) GetSocket(id int64) *SocketMetric { - sm := &SocketMetric{} - c.mu.RLock() - if ls, ok := c.listenSockets[id]; ok { - c.mu.RUnlock() - sm.SocketData = ls.s.ChannelzMetric() - sm.ID = ls.id - sm.RefName = ls.refName - return sm - } - if ns, ok := c.normalSockets[id]; ok { - c.mu.RUnlock() - sm.SocketData = ns.s.ChannelzMetric() - sm.ID = ns.id - sm.RefName = ns.refName - return sm - } - c.mu.RUnlock() - return nil -} - -type idGenerator struct { - id int64 -} - -func (i *idGenerator) reset() { - atomic.StoreInt64(&i.id, 0) -} - -func (i *idGenerator) genID() int64 { - return atomic.AddInt64(&i.id, 1) -} diff --git a/examples/google.golang.org/grpc/internal/channelz/types.go b/examples/google.golang.org/grpc/internal/channelz/types.go deleted file mode 100755 index 153d753..0000000 --- a/examples/google.golang.org/grpc/internal/channelz/types.go +++ /dev/null @@ -1,418 +0,0 @@ -/* - * - * 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. - * - */ - -package channelz - -import ( - "net" - "time" - - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" -) - -// entry represents a node in the channelz database. -type entry interface { - // addChild adds a child e, whose channelz id is id to child list - addChild(id int64, e entry) - // deleteChild deletes a child with channelz id to be id from child list - deleteChild(id int64) - // triggerDelete tries to delete self from channelz database. However, if child - // list is not empty, then deletion from the database is on hold until the last - // child is deleted from database. - triggerDelete() - // deleteSelfIfReady check whether triggerDelete() has been called before, and whether child - // list is now empty. If both conditions are met, then delete self from database. - deleteSelfIfReady() -} - -// dummyEntry is a fake entry to handle entry not found case. -type dummyEntry struct { - idNotFound int64 -} - -func (d *dummyEntry) addChild(id int64, e entry) { - // Note: It is possible for a normal program to reach here under race condition. - // For example, there could be a race between ClientConn.Close() info being propagated - // to addrConn and http2Client. ClientConn.Close() cancel the context and result - // in http2Client to error. The error info is then caught by transport monitor - // and before addrConn.tearDown() is called in side ClientConn.Close(). Therefore, - // the addrConn will create a new transport. And when registering the new transport in - // channelz, its parent addrConn could have already been torn down and deleted - // from channelz tracking, and thus reach the code here. - grpclog.Infof("attempt to add child of type %T with id %d to a parent (id=%d) that doesn't currently exist", e, id, d.idNotFound) -} - -func (d *dummyEntry) deleteChild(id int64) { - // It is possible for a normal program to reach here under race condition. - // Refer to the example described in addChild(). - grpclog.Infof("attempt to delete child with id %d from a parent (id=%d) that doesn't currently exist", id, d.idNotFound) -} - -func (d *dummyEntry) triggerDelete() { - grpclog.Warningf("attempt to delete an entry (id=%d) that doesn't currently exist", d.idNotFound) -} - -func (*dummyEntry) deleteSelfIfReady() { - // code should not reach here. deleteSelfIfReady is always called on an existing entry. -} - -// ChannelMetric defines the info channelz provides for a specific Channel, which -// includes ChannelInternalMetric and channelz-specific data, such as channelz id, -// child list, etc. -type ChannelMetric struct { - // ID is the channelz id of this channel. - ID int64 - // RefName is the human readable reference string of this channel. - RefName string - // ChannelData contains channel internal metric reported by the channel through - // ChannelzMetric(). - ChannelData *ChannelInternalMetric - // NestedChans tracks the nested channel type children of this channel in the format of - // a map from nested channel channelz id to corresponding reference string. - NestedChans map[int64]string - // SubChans tracks the subchannel type children of this channel in the format of a - // map from subchannel channelz id to corresponding reference string. - SubChans map[int64]string - // Sockets tracks the socket type children of this channel in the format of a map - // from socket channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow channel having sockets directly, - // therefore, this is field is unused. - Sockets map[int64]string -} - -// SubChannelMetric defines the info channelz provides for a specific SubChannel, -// which includes ChannelInternalMetric and channelz-specific data, such as -// channelz id, child list, etc. -type SubChannelMetric struct { - // ID is the channelz id of this subchannel. - ID int64 - // RefName is the human readable reference string of this subchannel. - RefName string - // ChannelData contains subchannel internal metric reported by the subchannel - // through ChannelzMetric(). - ChannelData *ChannelInternalMetric - // NestedChans tracks the nested channel type children of this subchannel in the format of - // a map from nested channel channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow subchannel to have nested channels - // as children, therefore, this field is unused. - NestedChans map[int64]string - // SubChans tracks the subchannel type children of this subchannel in the format of a - // map from subchannel channelz id to corresponding reference string. - // Note current grpc implementation doesn't allow subchannel to have subchannels - // as children, therefore, this field is unused. - SubChans map[int64]string - // Sockets tracks the socket type children of this subchannel in the format of a map - // from socket channelz id to corresponding reference string. - Sockets map[int64]string -} - -// ChannelInternalMetric defines the struct that the implementor of Channel interface -// should return from ChannelzMetric(). -type ChannelInternalMetric struct { - // current connectivity state of the channel. - State connectivity.State - // The target this channel originally tried to connect to. May be absent - Target string - // The number of calls started on the channel. - CallsStarted int64 - // The number of calls that have completed with an OK status. - CallsSucceeded int64 - // The number of calls that have a completed with a non-OK status. - CallsFailed int64 - // The last time a call was started on the channel. - LastCallStartedTimestamp time.Time - //TODO: trace -} - -// Channel is the interface that should be satisfied in order to be tracked by -// channelz as Channel or SubChannel. -type Channel interface { - ChannelzMetric() *ChannelInternalMetric -} - -type channel struct { - refName string - c Channel - closeCalled bool - nestedChans map[int64]string - subChans map[int64]string - id int64 - pid int64 - cm *channelMap -} - -func (c *channel) addChild(id int64, e entry) { - switch v := e.(type) { - case *subChannel: - c.subChans[id] = v.refName - case *channel: - c.nestedChans[id] = v.refName - default: - grpclog.Errorf("cannot add a child (id = %d) of type %T to a channel", id, e) - } -} - -func (c *channel) deleteChild(id int64) { - delete(c.subChans, id) - delete(c.nestedChans, id) - c.deleteSelfIfReady() -} - -func (c *channel) triggerDelete() { - c.closeCalled = true - c.deleteSelfIfReady() -} - -func (c *channel) deleteSelfIfReady() { - if !c.closeCalled || len(c.subChans)+len(c.nestedChans) != 0 { - return - } - c.cm.deleteEntry(c.id) - // not top channel - if c.pid != 0 { - c.cm.findEntry(c.pid).deleteChild(c.id) - } -} - -type subChannel struct { - refName string - c Channel - closeCalled bool - sockets map[int64]string - id int64 - pid int64 - cm *channelMap -} - -func (sc *subChannel) addChild(id int64, e entry) { - if v, ok := e.(*normalSocket); ok { - sc.sockets[id] = v.refName - } else { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a subChannel", id, e) - } -} - -func (sc *subChannel) deleteChild(id int64) { - delete(sc.sockets, id) - sc.deleteSelfIfReady() -} - -func (sc *subChannel) triggerDelete() { - sc.closeCalled = true - sc.deleteSelfIfReady() -} - -func (sc *subChannel) deleteSelfIfReady() { - if !sc.closeCalled || len(sc.sockets) != 0 { - return - } - sc.cm.deleteEntry(sc.id) - sc.cm.findEntry(sc.pid).deleteChild(sc.id) -} - -// SocketMetric defines the info channelz provides for a specific Socket, which -// includes SocketInternalMetric and channelz-specific data, such as channelz id, etc. -type SocketMetric struct { - // ID is the channelz id of this socket. - ID int64 - // RefName is the human readable reference string of this socket. - RefName string - // SocketData contains socket internal metric reported by the socket through - // ChannelzMetric(). - SocketData *SocketInternalMetric -} - -// SocketInternalMetric defines the struct that the implementor of Socket interface -// should return from ChannelzMetric(). -type SocketInternalMetric struct { - // The number of streams that have been started. - StreamsStarted int64 - // The number of streams that have ended successfully: - // On client side, receiving frame with eos bit set. - // On server side, sending frame with eos bit set. - StreamsSucceeded int64 - // The number of streams that have ended unsuccessfully: - // On client side, termination without receiving frame with eos bit set. - // On server side, termination without sending frame with eos bit set. - StreamsFailed int64 - // The number of messages successfully sent on this socket. - MessagesSent int64 - MessagesReceived int64 - // The number of keep alives sent. This is typically implemented with HTTP/2 - // ping messages. - KeepAlivesSent int64 - // The last time a stream was created by this endpoint. Usually unset for - // servers. - LastLocalStreamCreatedTimestamp time.Time - // The last time a stream was created by the remote endpoint. Usually unset - // for clients. - LastRemoteStreamCreatedTimestamp time.Time - // The last time a message was sent by this endpoint. - LastMessageSentTimestamp time.Time - // The last time a message was received by this endpoint. - LastMessageReceivedTimestamp time.Time - // 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. - LocalFlowControlWindow int64 - // 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. - RemoteFlowControlWindow int64 - // The locally bound address. - LocalAddr net.Addr - // The remote bound address. May be absent. - RemoteAddr net.Addr - // Optional, represents the name of the remote endpoint, if different than - // the original target name. - RemoteName string - //TODO: socket options - //TODO: Security -} - -// Socket is the interface that should be satisfied in order to be tracked by -// channelz as Socket. -type Socket interface { - ChannelzMetric() *SocketInternalMetric -} - -type listenSocket struct { - refName string - s Socket - id int64 - pid int64 - cm *channelMap -} - -func (ls *listenSocket) addChild(id int64, e entry) { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a listen socket", id, e) -} - -func (ls *listenSocket) deleteChild(id int64) { - grpclog.Errorf("cannot delete a child (id = %d) from a listen socket", id) -} - -func (ls *listenSocket) triggerDelete() { - ls.cm.deleteEntry(ls.id) - ls.cm.findEntry(ls.pid).deleteChild(ls.id) -} - -func (ls *listenSocket) deleteSelfIfReady() { - grpclog.Errorf("cannot call deleteSelfIfReady on a listen socket") -} - -type normalSocket struct { - refName string - s Socket - id int64 - pid int64 - cm *channelMap -} - -func (ns *normalSocket) addChild(id int64, e entry) { - grpclog.Errorf("cannot add a child (id = %d) of type %T to a normal socket", id, e) -} - -func (ns *normalSocket) deleteChild(id int64) { - grpclog.Errorf("cannot delete a child (id = %d) from a normal socket", id) -} - -func (ns *normalSocket) triggerDelete() { - ns.cm.deleteEntry(ns.id) - ns.cm.findEntry(ns.pid).deleteChild(ns.id) -} - -func (ns *normalSocket) deleteSelfIfReady() { - grpclog.Errorf("cannot call deleteSelfIfReady on a normal socket") -} - -// ServerMetric defines the info channelz provides for a specific Server, which -// includes ServerInternalMetric and channelz-specific data, such as channelz id, -// child list, etc. -type ServerMetric struct { - // ID is the channelz id of this server. - ID int64 - // RefName is the human readable reference string of this server. - RefName string - // ServerData contains server internal metric reported by the server through - // ChannelzMetric(). - ServerData *ServerInternalMetric - // ListenSockets tracks the listener socket type children of this server in the - // format of a map from socket channelz id to corresponding reference string. - ListenSockets map[int64]string -} - -// ServerInternalMetric defines the struct that the implementor of Server interface -// should return from ChannelzMetric(). -type ServerInternalMetric struct { - // The number of incoming calls started on the server. - CallsStarted int64 - // The number of incoming calls that have completed with an OK status. - CallsSucceeded int64 - // The number of incoming calls that have a completed with a non-OK status. - CallsFailed int64 - // The last time a call was started on the server. - LastCallStartedTimestamp time.Time - //TODO: trace -} - -// Server is the interface to be satisfied in order to be tracked by channelz as -// Server. -type Server interface { - ChannelzMetric() *ServerInternalMetric -} - -type server struct { - refName string - s Server - closeCalled bool - sockets map[int64]string - listenSockets map[int64]string - id int64 - cm *channelMap -} - -func (s *server) addChild(id int64, e entry) { - switch v := e.(type) { - case *normalSocket: - s.sockets[id] = v.refName - case *listenSocket: - s.listenSockets[id] = v.refName - default: - grpclog.Errorf("cannot add a child (id = %d) of type %T to a server", id, e) - } -} - -func (s *server) deleteChild(id int64) { - delete(s.sockets, id) - delete(s.listenSockets, id) - s.deleteSelfIfReady() -} - -func (s *server) triggerDelete() { - s.closeCalled = true - s.deleteSelfIfReady() -} - -func (s *server) deleteSelfIfReady() { - if !s.closeCalled || len(s.sockets)+len(s.listenSockets) != 0 { - return - } - s.cm.deleteEntry(s.id) -} diff --git a/examples/google.golang.org/grpc/internal/grpcrand/grpcrand.go b/examples/google.golang.org/grpc/internal/grpcrand/grpcrand.go deleted file mode 100755 index 200b115..0000000 --- a/examples/google.golang.org/grpc/internal/grpcrand/grpcrand.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * - * 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. - * - */ - -// Package grpcrand implements math/rand functions in a concurrent-safe way -// with a global random source, independent of math/rand's global source. -package grpcrand - -import ( - "math/rand" - "sync" - "time" -) - -var ( - r = rand.New(rand.NewSource(time.Now().UnixNano())) - mu sync.Mutex -) - -// Int63n implements rand.Int63n on the grpcrand global source. -func Int63n(n int64) int64 { - mu.Lock() - res := r.Int63n(n) - mu.Unlock() - return res -} - -// Intn implements rand.Intn on the grpcrand global source. -func Intn(n int) int { - mu.Lock() - res := r.Intn(n) - mu.Unlock() - return res -} - -// Float64 implements rand.Float64 on the grpcrand global source. -func Float64() float64 { - mu.Lock() - res := r.Float64() - mu.Unlock() - return res -} diff --git a/examples/google.golang.org/grpc/internal/internal.go b/examples/google.golang.org/grpc/internal/internal.go deleted file mode 100755 index cd34267..0000000 --- a/examples/google.golang.org/grpc/internal/internal.go +++ /dev/null @@ -1,36 +0,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. - * - */ - -// Package internal contains gRPC-internal code, to avoid polluting -// the godoc of the top-level grpc package. It must not import any grpc -// symbols to avoid circular dependencies. -package internal - -var ( - - // TestingUseHandlerImpl enables the http.Handler-based server implementation. - // It must be called before Serve and requires TLS credentials. - // - // The provided grpcServer must be of type *grpc.Server. It is untyped - // for circular dependency reasons. - TestingUseHandlerImpl func(grpcServer interface{}) - - // WithContextDialer is exported by clientconn.go - WithContextDialer interface{} // func(context.Context, string) (net.Conn, error) grpc.DialOption - // WithResolverBuilder is exported by clientconn.go - WithResolverBuilder interface{} // func (resolver.Builder) grpc.DialOption -) diff --git a/examples/google.golang.org/grpc/internal/leakcheck/leakcheck.go b/examples/google.golang.org/grpc/internal/leakcheck/leakcheck.go deleted file mode 100755 index 76f9fc5..0000000 --- a/examples/google.golang.org/grpc/internal/leakcheck/leakcheck.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package leakcheck contains functions to check leaked goroutines. -// -// Call "defer leakcheck.Check(t)" at the beginning of tests. -package leakcheck - -import ( - "runtime" - "sort" - "strings" - "time" -) - -var goroutinesToIgnore = []string{ - "testing.Main(", - "testing.tRunner(", - "testing.(*M).", - "runtime.goexit", - "created by runtime.gc", - "created by runtime/trace.Start", - "interestingGoroutines", - "runtime.MHeap_Scavenger", - "signal.signal_recv", - "sigterm.handler", - "runtime_mcall", - "(*loggingT).flushDaemon", - "goroutine in C code", -} - -// RegisterIgnoreGoroutine appends s into the ignore goroutine list. The -// goroutines whose stack trace contains s will not be identified as leaked -// goroutines. Not thread-safe, only call this function in init(). -func RegisterIgnoreGoroutine(s string) { - goroutinesToIgnore = append(goroutinesToIgnore, s) -} - -func ignore(g string) bool { - sl := strings.SplitN(g, "\n", 2) - if len(sl) != 2 { - return true - } - stack := strings.TrimSpace(sl[1]) - if strings.HasPrefix(stack, "testing.RunTests") { - return true - } - - if stack == "" { - return true - } - - for _, s := range goroutinesToIgnore { - if strings.Contains(stack, s) { - return true - } - } - - return false -} - -// interestingGoroutines returns all goroutines we care about for the purpose of -// leak checking. It excludes testing or runtime ones. -func interestingGoroutines() (gs []string) { - buf := make([]byte, 2<<20) - buf = buf[:runtime.Stack(buf, true)] - for _, g := range strings.Split(string(buf), "\n\n") { - if !ignore(g) { - gs = append(gs, g) - } - } - sort.Strings(gs) - return -} - -// Errorfer is the interface that wraps the Errorf method. It's a subset of -// testing.TB to make it easy to use Check. -type Errorfer interface { - Errorf(format string, args ...interface{}) -} - -func check(efer Errorfer, timeout time.Duration) { - // Loop, waiting for goroutines to shut down. - // Wait up to timeout, but finish as quickly as possible. - deadline := time.Now().Add(timeout) - var leaked []string - for time.Now().Before(deadline) { - if leaked = interestingGoroutines(); len(leaked) == 0 { - return - } - time.Sleep(50 * time.Millisecond) - } - for _, g := range leaked { - efer.Errorf("Leaked goroutine: %v", g) - } -} - -// Check looks at the currently-running goroutines and checks if there are any -// interestring (created by gRPC) goroutines leaked. It waits up to 10 seconds -// in the error cases. -func Check(efer Errorfer) { - check(efer, 10*time.Second) -} diff --git a/examples/google.golang.org/grpc/internal/leakcheck/leakcheck_test.go b/examples/google.golang.org/grpc/internal/leakcheck/leakcheck_test.go deleted file mode 100755 index 50927e9..0000000 --- a/examples/google.golang.org/grpc/internal/leakcheck/leakcheck_test.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package leakcheck - -import ( - "fmt" - "strings" - "testing" - "time" -) - -type testErrorfer struct { - errorCount int - errors []string -} - -func (e *testErrorfer) Errorf(format string, args ...interface{}) { - e.errors = append(e.errors, fmt.Sprintf(format, args...)) - e.errorCount++ -} - -func TestCheck(t *testing.T) { - const leakCount = 3 - for i := 0; i < leakCount; i++ { - go func() { time.Sleep(2 * time.Second) }() - } - if ig := interestingGoroutines(); len(ig) == 0 { - t.Error("blah") - } - e := &testErrorfer{} - check(e, time.Second) - if e.errorCount != leakCount { - t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) - t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) - } - check(t, 3*time.Second) -} - -func ignoredTestingLeak(d time.Duration) { - time.Sleep(d) -} - -func TestCheckRegisterIgnore(t *testing.T) { - RegisterIgnoreGoroutine("ignoredTestingLeak") - const leakCount = 3 - for i := 0; i < leakCount; i++ { - go func() { time.Sleep(2 * time.Second) }() - } - go func() { ignoredTestingLeak(3 * time.Second) }() - if ig := interestingGoroutines(); len(ig) == 0 { - t.Error("blah") - } - e := &testErrorfer{} - check(e, time.Second) - if e.errorCount != leakCount { - t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) - t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) - } - check(t, 3*time.Second) -} diff --git a/examples/google.golang.org/grpc/interop/alts/client/client.go b/examples/google.golang.org/grpc/interop/alts/client/client.go deleted file mode 100755 index 3710c4b..0000000 --- a/examples/google.golang.org/grpc/interop/alts/client/client.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * 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. - * - */ - -// This binary can only run on Google Cloud Platform (GCP). -package main - -import ( - "flag" - "time" - - "golang.org/x/net/context" - grpc "google.golang.org/grpc" - "google.golang.org/grpc/credentials/alts" - "google.golang.org/grpc/grpclog" - testpb "google.golang.org/grpc/interop/grpc_testing" -) - -const ( - value = "test_value" -) - -var ( - hsAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address") - serverAddr = flag.String("server_address", ":8080", "The port on which the server is listening") -) - -func main() { - flag.Parse() - - opts := alts.DefaultClientOptions() - if *hsAddr != "" { - opts.HandshakerServiceAddress = *hsAddr - } - altsTC := alts.NewClientCreds(opts) - // Block until the server is ready. - conn, err := grpc.Dial(*serverAddr, grpc.WithTransportCredentials(altsTC), grpc.WithBlock()) - if err != nil { - grpclog.Fatalf("gRPC Client: failed to dial the server at %v: %v", *serverAddr, err) - } - defer conn.Close() - grpcClient := testpb.NewTestServiceClient(conn) - - // Call the EmptyCall API. - ctx := context.Background() - request := &testpb.Empty{} - if _, err := grpcClient.EmptyCall(ctx, request); err != nil { - grpclog.Fatalf("grpc Client: EmptyCall(_, %v) failed: %v", request, err) - } - grpclog.Info("grpc Client: empty call succeeded") - - // This sleep prevents the connection from being abruptly disconnected - // when running this binary (along with grpc_server) on GCP dev cluster. - time.Sleep(1 * time.Second) -} diff --git a/examples/google.golang.org/grpc/interop/alts/server/server.go b/examples/google.golang.org/grpc/interop/alts/server/server.go deleted file mode 100755 index c70a20b..0000000 --- a/examples/google.golang.org/grpc/interop/alts/server/server.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * 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. - * - */ - -// This binary can only run on Google Cloud Platform (GCP). -package main - -import ( - "flag" - "net" - - grpc "google.golang.org/grpc" - "google.golang.org/grpc/credentials/alts" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" -) - -var ( - hsAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address") - serverAddr = flag.String("server_address", ":8080", "The port on which the server is listening") -) - -func main() { - flag.Parse() - - lis, err := net.Listen("tcp", *serverAddr) - if err != nil { - grpclog.Fatalf("gRPC Server: failed to start the server at %v: %v", *serverAddr, err) - } - opts := alts.DefaultServerOptions() - if *hsAddr != "" { - opts.HandshakerServiceAddress = *hsAddr - } - altsTC := alts.NewServerCreds(opts) - grpcServer := grpc.NewServer(grpc.Creds(altsTC)) - testpb.RegisterTestServiceServer(grpcServer, interop.NewTestServer()) - grpcServer.Serve(lis) -} diff --git a/examples/google.golang.org/grpc/interop/client/client.go b/examples/google.golang.org/grpc/interop/client/client.go deleted file mode 100755 index c8acae9..0000000 --- a/examples/google.golang.org/grpc/interop/client/client.go +++ /dev/null @@ -1,204 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "net" - "strconv" - - "google.golang.org/grpc" - _ "google.golang.org/grpc/balancer/grpclb" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/alts" - "google.golang.org/grpc/credentials/oauth" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true") - useALTS = flag.Bool("use_alts", false, "Connection uses ALTS if true (this option can only be used on GCP)") - altsHSAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address") - testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root") - serviceAccountKeyFile = flag.String("service_account_key_file", "", "Path to service account json key file") - oauthScope = flag.String("oauth_scope", "", "The scope for OAuth2 tokens") - defaultServiceAccount = flag.String("default_service_account", "", "Email of GCE default service account") - serverHost = flag.String("server_host", "localhost", "The server host name") - serverPort = flag.Int("server_port", 10000, "The server port number") - tlsServerName = flag.String("server_host_override", "", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.") - testCase = flag.String("test_case", "large_unary", - `Configure different test cases. Valid options are: - empty_unary : empty (zero bytes) request and response; - large_unary : single request and (large) response; - client_streaming : request streaming with single response; - server_streaming : single request with response streaming; - ping_pong : full-duplex streaming; - empty_stream : full-duplex streaming with zero message; - timeout_on_sleeping_server: fullduplex streaming on a sleeping server; - compute_engine_creds: large_unary with compute engine auth; - service_account_creds: large_unary with service account auth; - jwt_token_creds: large_unary with jwt token auth; - per_rpc_creds: large_unary with per rpc token; - oauth2_auth_token: large_unary with oauth2 token auth; - cancel_after_begin: cancellation after metadata has been sent but before payloads are sent; - cancel_after_first_response: cancellation after receiving 1st message from the server; - status_code_and_message: status code propagated back to client; - custom_metadata: server will echo custom metadata; - unimplemented_method: client attempts to call unimplemented method; - unimplemented_service: client attempts to call unimplemented service.`) -) - -func main() { - flag.Parse() - if *useTLS && *useALTS { - grpclog.Fatalf("use_tls and use_alts cannot be both set to true") - } - serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort)) - var opts []grpc.DialOption - if *useTLS { - var sn string - if *tlsServerName != "" { - sn = *tlsServerName - } - var creds credentials.TransportCredentials - if *testCA { - var err error - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err = credentials.NewClientTLSFromFile(*caFile, sn) - if err != nil { - grpclog.Fatalf("Failed to create TLS credentials %v", err) - } - } else { - creds = credentials.NewClientTLSFromCert(nil, sn) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - if *testCase == "compute_engine_creds" { - opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewComputeEngine())) - } else if *testCase == "service_account_creds" { - jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope) - if err != nil { - grpclog.Fatalf("Failed to create JWT credentials: %v", err) - } - opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) - } else if *testCase == "jwt_token_creds" { - jwtCreds, err := oauth.NewJWTAccessFromFile(*serviceAccountKeyFile) - if err != nil { - grpclog.Fatalf("Failed to create JWT credentials: %v", err) - } - opts = append(opts, grpc.WithPerRPCCredentials(jwtCreds)) - } else if *testCase == "oauth2_auth_token" { - opts = append(opts, grpc.WithPerRPCCredentials(oauth.NewOauthAccess(interop.GetToken(*serviceAccountKeyFile, *oauthScope)))) - } - } else if *useALTS { - altsOpts := alts.DefaultClientOptions() - if *altsHSAddr != "" { - altsOpts.HandshakerServiceAddress = *altsHSAddr - } - altsTC := alts.NewClientCreds(altsOpts) - opts = append(opts, grpc.WithTransportCredentials(altsTC)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - opts = append(opts, grpc.WithBlock()) - conn, err := grpc.Dial(serverAddr, opts...) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - tc := testpb.NewTestServiceClient(conn) - switch *testCase { - case "empty_unary": - interop.DoEmptyUnaryCall(tc) - grpclog.Infoln("EmptyUnaryCall done") - case "large_unary": - interop.DoLargeUnaryCall(tc) - grpclog.Infoln("LargeUnaryCall done") - case "client_streaming": - interop.DoClientStreaming(tc) - grpclog.Infoln("ClientStreaming done") - case "server_streaming": - interop.DoServerStreaming(tc) - grpclog.Infoln("ServerStreaming done") - case "ping_pong": - interop.DoPingPong(tc) - grpclog.Infoln("Pingpong done") - case "empty_stream": - interop.DoEmptyStream(tc) - grpclog.Infoln("Emptystream done") - case "timeout_on_sleeping_server": - interop.DoTimeoutOnSleepingServer(tc) - grpclog.Infoln("TimeoutOnSleepingServer done") - case "compute_engine_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute compute_engine_creds test case.") - } - interop.DoComputeEngineCreds(tc, *defaultServiceAccount, *oauthScope) - grpclog.Infoln("ComputeEngineCreds done") - case "service_account_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute service_account_creds test case.") - } - interop.DoServiceAccountCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Infoln("ServiceAccountCreds done") - case "jwt_token_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute jwt_token_creds test case.") - } - interop.DoJWTTokenCreds(tc, *serviceAccountKeyFile) - grpclog.Infoln("JWTtokenCreds done") - case "per_rpc_creds": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute per_rpc_creds test case.") - } - interop.DoPerRPCCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Infoln("PerRPCCreds done") - case "oauth2_auth_token": - if !*useTLS { - grpclog.Fatalf("TLS is not enabled. TLS is required to execute oauth2_auth_token test case.") - } - interop.DoOauth2TokenCreds(tc, *serviceAccountKeyFile, *oauthScope) - grpclog.Infoln("Oauth2TokenCreds done") - case "cancel_after_begin": - interop.DoCancelAfterBegin(tc) - grpclog.Infoln("CancelAfterBegin done") - case "cancel_after_first_response": - interop.DoCancelAfterFirstResponse(tc) - grpclog.Infoln("CancelAfterFirstResponse done") - case "status_code_and_message": - interop.DoStatusCodeAndMessage(tc) - grpclog.Infoln("StatusCodeAndMessage done") - case "custom_metadata": - interop.DoCustomMetadata(tc) - grpclog.Infoln("CustomMetadata done") - case "unimplemented_method": - interop.DoUnimplementedMethod(conn) - grpclog.Infoln("UnimplementedMethod done") - case "unimplemented_service": - interop.DoUnimplementedService(testpb.NewUnimplementedServiceClient(conn)) - grpclog.Infoln("UnimplementedService done") - default: - grpclog.Fatal("Unsupported test case: ", *testCase) - } -} diff --git a/examples/google.golang.org/grpc/interop/grpc_testing/test.pb.go b/examples/google.golang.org/grpc/interop/grpc_testing/test.pb.go deleted file mode 100755 index bb5e2ee..0000000 --- a/examples/google.golang.org/grpc/interop/grpc_testing/test.pb.go +++ /dev/null @@ -1,1087 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{0} -} - -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{0} -} -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type PayloadType `protobuf:"varint,1,opt,name=type,proto3,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{1} -} -func (m *Payload) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Payload.Unmarshal(m, b) -} -func (m *Payload) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Payload.Marshal(b, m, deterministic) -} -func (dst *Payload) XXX_Merge(src proto.Message) { - xxx_messageInfo_Payload.Merge(dst, src) -} -func (m *Payload) XXX_Size() int { - return xxx_messageInfo_Payload.Size(m) -} -func (m *Payload) XXX_DiscardUnknown() { - xxx_messageInfo_Payload.DiscardUnknown(m) -} - -var xxx_messageInfo_Payload proto.InternalMessageInfo - -func (m *Payload) GetType() PayloadType { - if m != nil { - return m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -type EchoStatus struct { - Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EchoStatus) Reset() { *m = EchoStatus{} } -func (m *EchoStatus) String() string { return proto.CompactTextString(m) } -func (*EchoStatus) ProtoMessage() {} -func (*EchoStatus) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{2} -} -func (m *EchoStatus) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EchoStatus.Unmarshal(m, b) -} -func (m *EchoStatus) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EchoStatus.Marshal(b, m, deterministic) -} -func (dst *EchoStatus) XXX_Merge(src proto.Message) { - xxx_messageInfo_EchoStatus.Merge(dst, src) -} -func (m *EchoStatus) XXX_Size() int { - return xxx_messageInfo_EchoStatus.Size(m) -} -func (m *EchoStatus) XXX_DiscardUnknown() { - xxx_messageInfo_EchoStatus.DiscardUnknown(m) -} - -var xxx_messageInfo_EchoStatus proto.InternalMessageInfo - -func (m *EchoStatus) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *EchoStatus) GetMessage() string { - if m != nil { - return m.Message - } - return "" -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize,proto3" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername,proto3" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope,proto3" json:"fill_oauth_scope,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{3} -} -func (m *SimpleRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleRequest.Unmarshal(m, b) -} -func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic) -} -func (dst *SimpleRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleRequest.Merge(dst, src) -} -func (m *SimpleRequest) XXX_Size() int { - return xxx_messageInfo_SimpleRequest.Size(m) -} -func (m *SimpleRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil { - return m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil { - return m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil { - return m.FillOauthScope - } - return false -} - -func (m *SimpleRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - // OAuth scope. - OauthScope string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope,proto3" json:"oauth_scope,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{4} -} -func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) -} -func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) -} -func (dst *SimpleResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleResponse.Merge(dst, src) -} -func (m *SimpleResponse) XXX_Size() int { - return xxx_messageInfo_SimpleResponse.Size(m) -} -func (m *SimpleResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil { - return m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{5} -} -func (m *StreamingInputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallRequest.Unmarshal(m, b) -} -func (m *StreamingInputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallRequest.Merge(dst, src) -} -func (m *StreamingInputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallRequest.Size(m) -} -func (m *StreamingInputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallRequest proto.InternalMessageInfo - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize,proto3" json:"aggregated_payload_size,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{6} -} -func (m *StreamingInputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallResponse.Unmarshal(m, b) -} -func (m *StreamingInputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallResponse.Merge(dst, src) -} -func (m *StreamingInputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallResponse.Size(m) -} -func (m *StreamingInputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallResponse proto.InternalMessageInfo - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil { - return m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size int32 `protobuf:"varint,1,opt,name=size,proto3" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs,proto3" json:"interval_us,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{7} -} -func (m *ResponseParameters) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseParameters.Unmarshal(m, b) -} -func (m *ResponseParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseParameters.Marshal(b, m, deterministic) -} -func (dst *ResponseParameters) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseParameters.Merge(dst, src) -} -func (m *ResponseParameters) XXX_Size() int { - return xxx_messageInfo_ResponseParameters.Size(m) -} -func (m *ResponseParameters) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseParameters.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseParameters proto.InternalMessageInfo - -func (m *ResponseParameters) GetSize() int32 { - if m != nil { - return m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil { - return m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters,proto3" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - // Whether server should return a given status - ResponseStatus *EchoStatus `protobuf:"bytes,7,opt,name=response_status,json=responseStatus,proto3" json:"response_status,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{8} -} -func (m *StreamingOutputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallRequest.Unmarshal(m, b) -} -func (m *StreamingOutputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallRequest.Merge(dst, src) -} -func (m *StreamingOutputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallRequest.Size(m) -} -func (m *StreamingOutputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallRequest proto.InternalMessageInfo - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *StreamingOutputCallRequest) GetResponseStatus() *EchoStatus { - if m != nil { - return m.ResponseStatus - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_4001f755b984bb27, []int{9} -} -func (m *StreamingOutputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallResponse.Unmarshal(m, b) -} -func (m *StreamingOutputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallResponse.Merge(dst, src) -} -func (m *StreamingOutputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallResponse.Size(m) -} -func (m *StreamingOutputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallResponse proto.InternalMessageInfo - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func init() { - proto.RegisterType((*Empty)(nil), "grpc.testing.Empty") - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*EchoStatus)(nil), "grpc.testing.EchoStatus") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// TestServiceClient is the client API for TestService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TestServiceClient interface { - // One empty request followed by one empty response. - EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingOutputCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_StreamingOutputCallClient interface { - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingOutputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingInputCallClient{stream} - return x, nil -} - -type TestService_StreamingInputCallClient interface { - Send(*StreamingInputCallRequest) error - CloseAndRecv() (*StreamingInputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingInputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(StreamingInputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceHalfDuplexCallClient{stream} - return x, nil -} - -type TestService_HalfDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceHalfDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// TestServiceServer is the server API for TestService service. -type TestServiceServer interface { - // One empty request followed by one empty response. - EmptyCall(context.Context, *Empty) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(TestService_StreamingInputCallServer) error - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - HalfDuplexCall(TestService_HalfDuplexCallServer) error -} - -func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { - s.RegisterService(&_TestService_serviceDesc, srv) -} - -func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).EmptyCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/EmptyCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(StreamingOutputCallRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} - -type TestService_StreamingOutputCallServer interface { - Send(*StreamingOutputCallResponse) error - grpc.ServerStream -} - -type testServiceStreamingOutputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream}) -} - -type TestService_StreamingInputCallServer interface { - SendAndClose(*StreamingInputCallResponse) error - Recv() (*StreamingInputCallRequest, error) - grpc.ServerStream -} - -type testServiceStreamingInputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) { - m := new(StreamingInputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) -} - -type TestService_HalfDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceHalfDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: _TestService_EmptyCall_Handler, - }, - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingOutputCall", - Handler: _TestService_StreamingOutputCall_Handler, - ServerStreams: true, - }, - { - StreamName: "StreamingInputCall", - Handler: _TestService_StreamingInputCall_Handler, - ClientStreams: true, - }, - { - StreamName: "FullDuplexCall", - Handler: _TestService_FullDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "HalfDuplexCall", - Handler: _TestService_HalfDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_testing/test.proto", -} - -// UnimplementedServiceClient is the client API for UnimplementedService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type UnimplementedServiceClient interface { - // A call that no server should implement - UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) -} - -type unimplementedServiceClient struct { - cc *grpc.ClientConn -} - -func NewUnimplementedServiceClient(cc *grpc.ClientConn) UnimplementedServiceClient { - return &unimplementedServiceClient{cc} -} - -func (c *unimplementedServiceClient) UnimplementedCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/grpc.testing.UnimplementedService/UnimplementedCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// UnimplementedServiceServer is the server API for UnimplementedService service. -type UnimplementedServiceServer interface { - // A call that no server should implement - UnimplementedCall(context.Context, *Empty) (*Empty, error) -} - -func RegisterUnimplementedServiceServer(s *grpc.Server, srv UnimplementedServiceServer) { - s.RegisterService(&_UnimplementedService_serviceDesc, srv) -} - -func _UnimplementedService_UnimplementedCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.UnimplementedService/UnimplementedCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(UnimplementedServiceServer).UnimplementedCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -var _UnimplementedService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.UnimplementedService", - HandlerType: (*UnimplementedServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnimplementedCall", - Handler: _UnimplementedService_UnimplementedCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor_test_4001f755b984bb27) } - -var fileDescriptor_test_4001f755b984bb27 = []byte{ - // 664 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xdd, 0x6e, 0xd3, 0x4c, - 0x10, 0xfd, 0x9c, 0x26, 0x4d, 0x3b, 0x49, 0xfd, 0x85, 0x2d, 0x55, 0xdd, 0x14, 0x89, 0xc8, 0x5c, - 0x60, 0x90, 0x48, 0x51, 0x10, 0x5c, 0x20, 0x01, 0x2a, 0x6d, 0x2a, 0x2a, 0xb5, 0x4d, 0xb1, 0x9b, - 0xeb, 0x68, 0x9b, 0x4c, 0x5d, 0x4b, 0xfe, 0xc3, 0xbb, 0xae, 0x48, 0x2f, 0x78, 0x19, 0x1e, 0x82, - 0x0b, 0x5e, 0x0e, 0xed, 0xda, 0x4e, 0x9c, 0xd4, 0x15, 0x0d, 0x7f, 0x57, 0xf1, 0x9e, 0x39, 0x33, - 0x3b, 0x67, 0xe6, 0xd8, 0x81, 0x4d, 0x3b, 0x0a, 0x87, 0x03, 0x8e, 0x8c, 0x3b, 0xbe, 0xbd, 0x23, - 0x7e, 0xdb, 0x61, 0x14, 0xf0, 0x80, 0xd4, 0x45, 0xa0, 0x9d, 0x06, 0xf4, 0x2a, 0x54, 0xba, 0x5e, - 0xc8, 0xc7, 0xfa, 0x11, 0x54, 0x4f, 0xe9, 0xd8, 0x0d, 0xe8, 0x88, 0x3c, 0x83, 0x32, 0x1f, 0x87, - 0xa8, 0x29, 0x2d, 0xc5, 0x50, 0x3b, 0x5b, 0xed, 0x7c, 0x42, 0x3b, 0x25, 0x9d, 0x8d, 0x43, 0x34, - 0x25, 0x8d, 0x10, 0x28, 0x9f, 0x07, 0xa3, 0xb1, 0x56, 0x6a, 0x29, 0x46, 0xdd, 0x94, 0xcf, 0xfa, - 0x6b, 0x80, 0xee, 0xf0, 0x32, 0xb0, 0x38, 0xe5, 0x31, 0x13, 0x8c, 0x61, 0x30, 0x4a, 0x0a, 0x56, - 0x4c, 0xf9, 0x4c, 0x34, 0xa8, 0x7a, 0xc8, 0x18, 0xb5, 0x51, 0x26, 0xae, 0x9a, 0xd9, 0x51, 0xff, - 0x56, 0x82, 0x35, 0xcb, 0xf1, 0x42, 0x17, 0x4d, 0xfc, 0x14, 0x23, 0xe3, 0xe4, 0x2d, 0xac, 0x45, - 0xc8, 0xc2, 0xc0, 0x67, 0x38, 0xb8, 0x5b, 0x67, 0xf5, 0x8c, 0x2f, 0x4e, 0xe4, 0x51, 0x2e, 0x9f, - 0x39, 0xd7, 0xc9, 0x8d, 0x95, 0x29, 0xc9, 0x72, 0xae, 0x91, 0xec, 0x40, 0x35, 0x4c, 0x2a, 0x68, - 0x4b, 0x2d, 0xc5, 0xa8, 0x75, 0x36, 0x0a, 0xcb, 0x9b, 0x19, 0x4b, 0x54, 0xbd, 0x70, 0x5c, 0x77, - 0x10, 0x33, 0x8c, 0x7c, 0xea, 0xa1, 0x56, 0x6e, 0x29, 0xc6, 0x8a, 0x59, 0x17, 0x60, 0x3f, 0xc5, - 0x88, 0x01, 0x0d, 0x49, 0x0a, 0x68, 0xcc, 0x2f, 0x07, 0x6c, 0x18, 0x84, 0xa8, 0x55, 0x24, 0x4f, - 0x15, 0x78, 0x4f, 0xc0, 0x96, 0x40, 0xc9, 0x2e, 0xfc, 0x3f, 0x6d, 0x52, 0xce, 0x4d, 0xab, 0xca, - 0x3e, 0xb4, 0xd9, 0x3e, 0xa6, 0x73, 0x35, 0xd5, 0x89, 0x00, 0x79, 0xd6, 0xbf, 0x80, 0x9a, 0x0d, - 0x2e, 0xc1, 0xf3, 0xa2, 0x94, 0x3b, 0x89, 0x6a, 0xc2, 0xca, 0x44, 0x4f, 0xb2, 0x97, 0xc9, 0x99, - 0x3c, 0x84, 0x5a, 0x5e, 0xc6, 0x92, 0x0c, 0x43, 0x30, 0x91, 0xa0, 0x1f, 0xc1, 0x96, 0xc5, 0x23, - 0xa4, 0x9e, 0xe3, 0xdb, 0x87, 0x7e, 0x18, 0xf3, 0x3d, 0xea, 0xba, 0xd9, 0x12, 0x17, 0x6d, 0x45, - 0x3f, 0x83, 0x66, 0x51, 0xb5, 0x54, 0xd9, 0x2b, 0xd8, 0xa4, 0xb6, 0x1d, 0xa1, 0x4d, 0x39, 0x8e, - 0x06, 0x69, 0x4e, 0xb2, 0xdd, 0xc4, 0x66, 0x1b, 0xd3, 0x70, 0x5a, 0x5a, 0xac, 0x59, 0x3f, 0x04, - 0x92, 0xd5, 0x38, 0xa5, 0x11, 0xf5, 0x90, 0x63, 0x24, 0x1d, 0x9a, 0x4b, 0x95, 0xcf, 0x42, 0xae, - 0xe3, 0x73, 0x8c, 0xae, 0xa8, 0xd8, 0x71, 0xea, 0x19, 0xc8, 0xa0, 0x3e, 0xd3, 0xbf, 0x96, 0x72, - 0x1d, 0xf6, 0x62, 0x3e, 0x27, 0xf8, 0x77, 0x5d, 0xfb, 0x11, 0xd6, 0x27, 0xf9, 0xe1, 0xa4, 0x55, - 0xad, 0xd4, 0x5a, 0x32, 0x6a, 0x9d, 0xd6, 0x6c, 0x95, 0x9b, 0x92, 0x4c, 0x12, 0xdd, 0x94, 0xb9, - 0xb0, 0xc7, 0xff, 0x80, 0x29, 0x4f, 0x60, 0xbb, 0x70, 0x48, 0xbf, 0xe8, 0xd0, 0xa7, 0xef, 0xa0, - 0x96, 0x9b, 0x19, 0x69, 0x40, 0x7d, 0xaf, 0x77, 0x7c, 0x6a, 0x76, 0x2d, 0x6b, 0xf7, 0xfd, 0x51, - 0xb7, 0xf1, 0x1f, 0x21, 0xa0, 0xf6, 0x4f, 0x66, 0x30, 0x85, 0x00, 0x2c, 0x9b, 0xbb, 0x27, 0xfb, - 0xbd, 0xe3, 0x46, 0xa9, 0xf3, 0xbd, 0x0c, 0xb5, 0x33, 0x64, 0xdc, 0xc2, 0xe8, 0xca, 0x19, 0x22, - 0x79, 0x09, 0xab, 0xf2, 0x13, 0x28, 0xda, 0x22, 0xeb, 0x73, 0xba, 0x44, 0xa0, 0x59, 0x04, 0x92, - 0x03, 0x58, 0xed, 0xfb, 0x34, 0x4a, 0xd2, 0xb6, 0x67, 0x19, 0x33, 0x9f, 0xaf, 0xe6, 0x83, 0xe2, - 0x60, 0x3a, 0x00, 0x17, 0xd6, 0x0b, 0xe6, 0x43, 0x8c, 0xb9, 0xa4, 0x5b, 0x7d, 0xd6, 0x7c, 0x72, - 0x07, 0x66, 0x72, 0xd7, 0x73, 0x85, 0x38, 0x40, 0x6e, 0xbe, 0x54, 0xe4, 0xf1, 0x2d, 0x25, 0xe6, - 0x5f, 0xe2, 0xa6, 0xf1, 0x73, 0x62, 0x72, 0x95, 0x21, 0xae, 0x52, 0x0f, 0x62, 0xd7, 0xdd, 0x8f, - 0x43, 0x17, 0x3f, 0xff, 0x35, 0x4d, 0x86, 0x22, 0x55, 0xa9, 0x1f, 0xa8, 0x7b, 0xf1, 0x0f, 0xae, - 0xea, 0xf4, 0xe1, 0x7e, 0xdf, 0x97, 0x1b, 0xf4, 0xd0, 0xe7, 0x38, 0xca, 0x5c, 0xf4, 0x06, 0xee, - 0xcd, 0xe0, 0x8b, 0xb9, 0xe9, 0x7c, 0x59, 0xfe, 0x39, 0xbf, 0xf8, 0x11, 0x00, 0x00, 0xff, 0xff, - 0x87, 0xd4, 0xf3, 0x98, 0xb7, 0x07, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/interop/grpc_testing/test.proto b/examples/google.golang.org/grpc/interop/grpc_testing/test.proto deleted file mode 100755 index f9f303d..0000000 --- a/examples/google.golang.org/grpc/interop/grpc_testing/test.proto +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto3"; - -package grpc.testing; - -message Empty {} - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - PayloadType type = 1; - // Primary contents of payload. - bytes body = 2; -} - -// A protobuf representation for grpc status. This is used by test -// clients to specify a status that the server should attempt to return. -message EchoStatus { - int32 code = 1; - string message = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 response_size = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Whether SimpleResponse should include username. - bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - bool fill_oauth_scope = 5; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - Payload payload = 1; - - // The user the request came from, for verifying authentication was - // successful when the client expected it. - string username = 2; - - // OAuth scope. - string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Whether server should return a given status - EchoStatus response_status = 7; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - Payload payload = 1; -} - -// A simple service to test the various types of RPCs and experiment with -// performance with various types of payload. -service TestService { - // One empty request followed by one empty response. - rpc EmptyCall(Empty) returns (Empty); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - rpc StreamingOutputCall(StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - rpc StreamingInputCall(stream StreamingInputCallRequest) - returns (StreamingInputCallResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - rpc HalfDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); -} - -// A simple service NOT implemented at servers so clients can test for -// that case. -service UnimplementedService { - // A call that no server should implement - rpc UnimplementedCall(grpc.testing.Empty) returns (grpc.testing.Empty); -} diff --git a/examples/google.golang.org/grpc/interop/http2/negative_http2_client.go b/examples/google.golang.org/grpc/interop/http2/negative_http2_client.go deleted file mode 100755 index 7658a63..0000000 --- a/examples/google.golang.org/grpc/interop/http2/negative_http2_client.go +++ /dev/null @@ -1,159 +0,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. - * - * - * Client used to test http2 error edge cases like GOAWAYs and RST_STREAMs - * - * Documentation: - * https://github.com/grpc/grpc/blob/master/doc/negative-http2-interop-test-descriptions.md - */ - -package main - -import ( - "flag" - "net" - "strconv" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/status" -) - -var ( - serverHost = flag.String("server_host", "127.0.0.1", "The server host name") - serverPort = flag.Int("server_port", 8080, "The server port number") - testCase = flag.String("test_case", "goaway", - `Configure different test cases. Valid options are: - goaway : client sends two requests, the server will send a goaway in between; - rst_after_header : server will send rst_stream after it sends headers; - rst_during_data : server will send rst_stream while sending data; - rst_after_data : server will send rst_stream after sending data; - ping : server will send pings between each http2 frame; - max_streams : server will ensure that the max_concurrent_streams limit is upheld;`) - largeReqSize = 271828 - largeRespSize = 314159 -) - -func largeSimpleRequest() *testpb.SimpleRequest { - pl := interop.ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - return &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - } -} - -// sends two unary calls. The server asserts that the calls use different connections. -func goaway(tc testpb.TestServiceClient) { - interop.DoLargeUnaryCall(tc) - // sleep to ensure that the client has time to recv the GOAWAY. - // TODO(ncteisen): make this less hacky. - time.Sleep(1 * time.Second) - interop.DoLargeUnaryCall(tc) -} - -func rstAfterHeader(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream after header") - } - if status.Code(err) != codes.Internal { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, status.Code(err), codes.Internal) - } -} - -func rstDuringData(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream during data") - } - if status.Code(err) != codes.Unknown { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, status.Code(err), codes.Unknown) - } -} - -func rstAfterData(tc testpb.TestServiceClient) { - req := largeSimpleRequest() - reply, err := tc.UnaryCall(context.Background(), req) - if reply != nil { - grpclog.Fatalf("Client received reply despite server sending rst stream after data") - } - if status.Code(err) != codes.Internal { - grpclog.Fatalf("%v.UnaryCall() = _, %v, want _, %v", tc, status.Code(err), codes.Internal) - } -} - -func ping(tc testpb.TestServiceClient) { - // The server will assert that every ping it sends was ACK-ed by the client. - interop.DoLargeUnaryCall(tc) -} - -func maxStreams(tc testpb.TestServiceClient) { - interop.DoLargeUnaryCall(tc) - var wg sync.WaitGroup - for i := 0; i < 15; i++ { - wg.Add(1) - go func() { - defer wg.Done() - interop.DoLargeUnaryCall(tc) - }() - } - wg.Wait() -} - -func main() { - flag.Parse() - serverAddr := net.JoinHostPort(*serverHost, strconv.Itoa(*serverPort)) - var opts []grpc.DialOption - opts = append(opts, grpc.WithInsecure()) - conn, err := grpc.Dial(serverAddr, opts...) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - tc := testpb.NewTestServiceClient(conn) - switch *testCase { - case "goaway": - goaway(tc) - grpclog.Infoln("goaway done") - case "rst_after_header": - rstAfterHeader(tc) - grpclog.Infoln("rst_after_header done") - case "rst_during_data": - rstDuringData(tc) - grpclog.Infoln("rst_during_data done") - case "rst_after_data": - rstAfterData(tc) - grpclog.Infoln("rst_after_data done") - case "ping": - ping(tc) - grpclog.Infoln("ping done") - case "max_streams": - maxStreams(tc) - grpclog.Infoln("max_streams done") - default: - grpclog.Fatal("Unsupported test case: ", *testCase) - } -} diff --git a/examples/google.golang.org/grpc/interop/server/server.go b/examples/google.golang.org/grpc/interop/server/server.go deleted file mode 100755 index dd0e897..0000000 --- a/examples/google.golang.org/grpc/interop/server/server.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package main - -import ( - "flag" - "net" - "strconv" - - "google.golang.org/grpc" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/alts" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") - useALTS = flag.Bool("use_alts", false, "Connection uses ALTS if true (this option can only be used on GCP)") - altsHSAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address") - certFile = flag.String("tls_cert_file", "", "The TLS cert file") - keyFile = flag.String("tls_key_file", "", "The TLS key file") - port = flag.Int("port", 10000, "The server port") -) - -func main() { - flag.Parse() - if *useTLS && *useALTS { - grpclog.Fatalf("use_tls and use_alts cannot be both set to true") - } - p := strconv.Itoa(*port) - lis, err := net.Listen("tcp", ":"+p) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - var opts []grpc.ServerOption - if *useTLS { - if *certFile == "" { - *certFile = testdata.Path("server1.pem") - } - if *keyFile == "" { - *keyFile = testdata.Path("server1.key") - } - creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) - if err != nil { - grpclog.Fatalf("Failed to generate credentials %v", err) - } - opts = append(opts, grpc.Creds(creds)) - } else if *useALTS { - altsOpts := alts.DefaultServerOptions() - if *altsHSAddr != "" { - altsOpts.HandshakerServiceAddress = *altsHSAddr - } - altsTC := alts.NewServerCreds(altsOpts) - opts = append(opts, grpc.Creds(altsTC)) - } - server := grpc.NewServer(opts...) - testpb.RegisterTestServiceServer(server, interop.NewTestServer()) - server.Serve(lis) -} diff --git a/examples/google.golang.org/grpc/interop/test_utils.go b/examples/google.golang.org/grpc/interop/test_utils.go deleted file mode 100755 index cbc7756..0000000 --- a/examples/google.golang.org/grpc/interop/test_utils.go +++ /dev/null @@ -1,745 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -package interop - -import ( - "fmt" - "io" - "io/ioutil" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -var ( - reqSizes = []int{27182, 8, 1828, 45904} - respSizes = []int{31415, 9, 2653, 58979} - largeReqSize = 271828 - largeRespSize = 314159 - initialMetadataKey = "x-grpc-test-echo-initial" - trailingMetadataKey = "x-grpc-test-echo-trailing-bin" -) - -// ClientNewPayload returns a payload of the given type and size. -func ClientNewPayload(t testpb.PayloadType, size int) *testpb.Payload { - if size < 0 { - grpclog.Fatalf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - grpclog.Fatalf("PayloadType UNCOMPRESSABLE is not supported") - default: - grpclog.Fatalf("Unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t, - Body: body, - } -} - -// DoEmptyUnaryCall performs a unary RPC with empty request and response messages. -func DoEmptyUnaryCall(tc testpb.TestServiceClient, args ...grpc.CallOption) { - reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, args...) - if err != nil { - grpclog.Fatal("/TestService/EmptyCall RPC failed: ", err) - } - if !proto.Equal(&testpb.Empty{}, reply) { - grpclog.Fatalf("/TestService/EmptyCall receives %v, want %v", reply, testpb.Empty{}) - } -} - -// DoLargeUnaryCall performs a unary RPC with large payload in the request and response. -func DoLargeUnaryCall(tc testpb.TestServiceClient, args ...grpc.CallOption) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - } - reply, err := tc.UnaryCall(context.Background(), req, args...) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - t := reply.GetPayload().GetType() - s := len(reply.GetPayload().GetBody()) - if t != testpb.PayloadType_COMPRESSABLE || s != largeRespSize { - grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, largeRespSize) - } -} - -// DoClientStreaming performs a client streaming RPC. -func DoClientStreaming(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.StreamingInputCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err) - } - var sum int - for _, s := range reqSizes { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, s) - req := &testpb.StreamingInputCallRequest{ - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - sum += s - } - reply, err := stream.CloseAndRecv() - if err != nil { - grpclog.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - if reply.GetAggregatedPayloadSize() != int32(sum) { - grpclog.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum) - } -} - -// DoServerStreaming performs a server streaming RPC. -func DoServerStreaming(tc testpb.TestServiceClient, args ...grpc.CallOption) { - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: int32(s), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - } - stream, err := tc.StreamingOutputCall(context.Background(), req, args...) - if err != nil { - grpclog.Fatalf("%v.StreamingOutputCall(_) = _, %v", tc, err) - } - var rpcStatus error - var respCnt int - var index int - for { - reply, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - t := reply.GetPayload().GetType() - if t != testpb.PayloadType_COMPRESSABLE { - grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != respSizes[index] { - grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - respCnt++ - } - if rpcStatus != io.EOF { - grpclog.Fatalf("Failed to finish the server streaming rpc: %v", rpcStatus) - } - if respCnt != len(respSizes) { - grpclog.Fatalf("Got %d reply, want %d", len(respSizes), respCnt) - } -} - -// DoPingPong performs ping-pong style bi-directional streaming RPC. -func DoPingPong(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - var index int - for index < len(reqSizes) { - respParam := []*testpb.ResponseParameters{ - { - Size: int32(respSizes[index]), - }, - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, reqSizes[index]) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - reply, err := stream.Recv() - if err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - t := reply.GetPayload().GetType() - if t != testpb.PayloadType_COMPRESSABLE { - grpclog.Fatalf("Got the reply of type %d, want %d", t, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != respSizes[index] { - grpclog.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complele the ping pong test: %v", stream, err) - } -} - -// DoEmptyStream sets up a bi-directional streaming with zero message. -func DoEmptyStream(tc testpb.TestServiceClient, args ...grpc.CallOption) { - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complete the empty stream test: %v", stream, err) - } -} - -// DoTimeoutOnSleepingServer performs an RPC on a sleep server which causes RPC timeout. -func DoTimeoutOnSleepingServer(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) - defer cancel() - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - if status.Code(err) == codes.DeadlineExceeded { - return - } - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 27182) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - Payload: pl, - } - if err := stream.Send(req); err != nil && err != io.EOF { - grpclog.Fatalf("%v.Send(_) = %v", stream, err) - } - if _, err := stream.Recv(); status.Code(err) != codes.DeadlineExceeded { - grpclog.Fatalf("%v.Recv() = _, %v, want error code %d", stream, err, codes.DeadlineExceeded) - } -} - -// DoComputeEngineCreds performs a unary RPC with compute engine auth. -func DoComputeEngineCreds(tc testpb.TestServiceClient, serviceAccount, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - FillUsername: true, - FillOauthScope: true, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - user := reply.GetUsername() - scope := reply.GetOauthScope() - if user != serviceAccount { - grpclog.Fatalf("Got user name %q, want %q.", user, serviceAccount) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -func getServiceAccountJSONKey(keyFile string) []byte { - jsonKey, err := ioutil.ReadFile(keyFile) - if err != nil { - grpclog.Fatalf("Failed to read the service account key file: %v", err) - } - return jsonKey -} - -// DoServiceAccountCreds performs a unary RPC with service account auth. -func DoServiceAccountCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - FillUsername: true, - FillOauthScope: true, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -// DoJWTTokenCreds performs a unary RPC with JWT token auth. -func DoJWTTokenCreds(tc testpb.TestServiceClient, serviceAccountKeyFile string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - FillUsername: true, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } -} - -// GetToken obtains an OAUTH token from the input. -func GetToken(serviceAccountKeyFile string, oauthScope string) *oauth2.Token { - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - config, err := google.JWTConfigFromJSON(jsonKey, oauthScope) - if err != nil { - grpclog.Fatalf("Failed to get the config: %v", err) - } - token, err := config.TokenSource(context.Background()).Token() - if err != nil { - grpclog.Fatalf("Failed to get the token: %v", err) - } - return token -} - -// DoOauth2TokenCreds performs a unary RPC with OAUTH2 token auth. -func DoOauth2TokenCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - FillUsername: true, - FillOauthScope: true, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -// DoPerRPCCreds performs a unary RPC with per RPC OAUTH2 token. -func DoPerRPCCreds(tc testpb.TestServiceClient, serviceAccountKeyFile, oauthScope string) { - jsonKey := getServiceAccountJSONKey(serviceAccountKeyFile) - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, largeReqSize) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeRespSize), - Payload: pl, - FillUsername: true, - FillOauthScope: true, - } - token := GetToken(serviceAccountKeyFile, oauthScope) - kv := map[string]string{"authorization": token.Type() + " " + token.AccessToken} - ctx := metadata.NewOutgoingContext(context.Background(), metadata.MD{"authorization": []string{kv["authorization"]}}) - reply, err := tc.UnaryCall(ctx, req) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - user := reply.GetUsername() - scope := reply.GetOauthScope() - if !strings.Contains(string(jsonKey), user) { - grpclog.Fatalf("Got user name %q which is NOT a substring of %q.", user, jsonKey) - } - if !strings.Contains(oauthScope, scope) { - grpclog.Fatalf("Got OAuth scope %q which is NOT a substring of %q.", scope, oauthScope) - } -} - -var testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, -} - -// DoCancelAfterBegin cancels the RPC after metadata has been sent but before payloads are sent. -func DoCancelAfterBegin(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithCancel(metadata.NewOutgoingContext(context.Background(), testMetadata)) - stream, err := tc.StreamingInputCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err) - } - cancel() - _, err = stream.CloseAndRecv() - if status.Code(err) != codes.Canceled { - grpclog.Fatalf("%v.CloseAndRecv() got error code %d, want %d", stream, status.Code(err), codes.Canceled) - } -} - -// DoCancelAfterFirstResponse cancels the RPC after receiving the first message from the server. -func DoCancelAfterFirstResponse(tc testpb.TestServiceClient, args ...grpc.CallOption) { - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: 31415, - }, - } - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 27182) - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(req); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, req) - } - if _, err := stream.Recv(); err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - cancel() - if _, err := stream.Recv(); status.Code(err) != codes.Canceled { - grpclog.Fatalf("%v compleled with error code %d, want %d", stream, status.Code(err), codes.Canceled) - } -} - -var ( - initialMetadataValue = "test_initial_metadata_value" - trailingMetadataValue = "\x0a\x0b\x0a\x0b\x0a\x0b" - customMetadata = metadata.Pairs( - initialMetadataKey, initialMetadataValue, - trailingMetadataKey, trailingMetadataValue, - ) -) - -func validateMetadata(header, trailer metadata.MD) { - if len(header[initialMetadataKey]) != 1 { - grpclog.Fatalf("Expected exactly one header from server. Received %d", len(header[initialMetadataKey])) - } - if header[initialMetadataKey][0] != initialMetadataValue { - grpclog.Fatalf("Got header %s; want %s", header[initialMetadataKey][0], initialMetadataValue) - } - if len(trailer[trailingMetadataKey]) != 1 { - grpclog.Fatalf("Expected exactly one trailer from server. Received %d", len(trailer[trailingMetadataKey])) - } - if trailer[trailingMetadataKey][0] != trailingMetadataValue { - grpclog.Fatalf("Got trailer %s; want %s", trailer[trailingMetadataKey][0], trailingMetadataValue) - } -} - -// DoCustomMetadata checks that metadata is echoed back to the client. -func DoCustomMetadata(tc testpb.TestServiceClient, args ...grpc.CallOption) { - // Testing with UnaryCall. - pl := ClientNewPayload(testpb.PayloadType_COMPRESSABLE, 1) - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(1), - Payload: pl, - } - ctx := metadata.NewOutgoingContext(context.Background(), customMetadata) - var header, trailer metadata.MD - args = append(args, grpc.Header(&header), grpc.Trailer(&trailer)) - reply, err := tc.UnaryCall( - ctx, - req, - args..., - ) - if err != nil { - grpclog.Fatal("/TestService/UnaryCall RPC failed: ", err) - } - t := reply.GetPayload().GetType() - s := len(reply.GetPayload().GetBody()) - if t != testpb.PayloadType_COMPRESSABLE || s != 1 { - grpclog.Fatalf("Got the reply with type %d len %d; want %d, %d", t, s, testpb.PayloadType_COMPRESSABLE, 1) - } - validateMetadata(header, trailer) - - // Testing with FullDuplex. - stream, err := tc.FullDuplexCall(ctx, args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: 1, - }, - } - streamReq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: pl, - } - if err := stream.Send(streamReq); err != nil { - grpclog.Fatalf("%v has error %v while sending %v", stream, err, streamReq) - } - streamHeader, err := stream.Header() - if err != nil { - grpclog.Fatalf("%v.Header() = %v", stream, err) - } - if _, err := stream.Recv(); err != nil { - grpclog.Fatalf("%v.Recv() = %v", stream, err) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() = %v, want ", stream, err) - } - if _, err := stream.Recv(); err != io.EOF { - grpclog.Fatalf("%v failed to complete the custom metadata test: %v", stream, err) - } - streamTrailer := stream.Trailer() - validateMetadata(streamHeader, streamTrailer) -} - -// DoStatusCodeAndMessage checks that the status code is propagated back to the client. -func DoStatusCodeAndMessage(tc testpb.TestServiceClient, args ...grpc.CallOption) { - var code int32 = 2 - msg := "test status message" - expectedErr := status.Error(codes.Code(code), msg) - respStatus := &testpb.EchoStatus{ - Code: code, - Message: msg, - } - // Test UnaryCall. - req := &testpb.SimpleRequest{ - ResponseStatus: respStatus, - } - if _, err := tc.UnaryCall(context.Background(), req, args...); err == nil || err.Error() != expectedErr.Error() { - grpclog.Fatalf("%v.UnaryCall(_, %v) = _, %v, want _, %v", tc, req, err, expectedErr) - } - // Test FullDuplexCall. - stream, err := tc.FullDuplexCall(context.Background(), args...) - if err != nil { - grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - streamReq := &testpb.StreamingOutputCallRequest{ - ResponseStatus: respStatus, - } - if err := stream.Send(streamReq); err != nil { - grpclog.Fatalf("%v has error %v while sending %v, want ", stream, err, streamReq) - } - if err := stream.CloseSend(); err != nil { - grpclog.Fatalf("%v.CloseSend() = %v, want ", stream, err) - } - if _, err = stream.Recv(); err.Error() != expectedErr.Error() { - grpclog.Fatalf("%v.Recv() returned error %v, want %v", stream, err, expectedErr) - } -} - -// DoUnimplementedService attempts to call a method from an unimplemented service. -func DoUnimplementedService(tc testpb.UnimplementedServiceClient) { - _, err := tc.UnimplementedCall(context.Background(), &testpb.Empty{}) - if status.Code(err) != codes.Unimplemented { - grpclog.Fatalf("%v.UnimplementedCall() = _, %v, want _, %v", tc, status.Code(err), codes.Unimplemented) - } -} - -// DoUnimplementedMethod attempts to call an unimplemented method. -func DoUnimplementedMethod(cc *grpc.ClientConn) { - var req, reply proto.Message - if err := cc.Invoke(context.Background(), "/grpc.testing.TestService/UnimplementedCall", req, reply); err == nil || status.Code(err) != codes.Unimplemented { - grpclog.Fatalf("ClientConn.Invoke(_, _, _, _, _) = %v, want error code %s", err, codes.Unimplemented) - } -} - -type testServer struct { -} - -// NewTestServer creates a test server for test service. -func NewTestServer() testpb.TestServiceServer { - return &testServer{} -} - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return new(testpb.Empty), nil -} - -func serverNewPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) { - if size < 0 { - return nil, fmt.Errorf("requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - return nil, fmt.Errorf("payloadType UNCOMPRESSABLE is not supported") - default: - return nil, fmt.Errorf("unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t, - Body: body, - }, nil -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - st := in.GetResponseStatus() - if md, ok := metadata.FromIncomingContext(ctx); ok { - if initialMetadata, ok := md[initialMetadataKey]; ok { - header := metadata.Pairs(initialMetadataKey, initialMetadata[0]) - grpc.SendHeader(ctx, header) - } - if trailingMetadata, ok := md[trailingMetadataKey]; ok { - trailer := metadata.Pairs(trailingMetadataKey, trailingMetadata[0]) - grpc.SetTrailer(ctx, trailer) - } - } - if st != nil && st.Code != 0 { - return nil, status.Error(codes.Code(st.Code), st.Message) - } - pl, err := serverNewPayload(in.GetResponseType(), in.GetResponseSize()) - if err != nil { - return nil, err - } - return &testpb.SimpleResponse{ - Payload: pl, - }, nil -} - -func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - cs := args.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(args.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - return nil -} - -func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - var sum int - for { - in, err := stream.Recv() - if err == io.EOF { - return stream.SendAndClose(&testpb.StreamingInputCallResponse{ - AggregatedPayloadSize: int32(sum), - }) - } - if err != nil { - return err - } - p := in.GetPayload().GetBody() - sum += len(p) - } -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - if md, ok := metadata.FromIncomingContext(stream.Context()); ok { - if initialMetadata, ok := md[initialMetadataKey]; ok { - header := metadata.Pairs(initialMetadataKey, initialMetadata[0]) - stream.SendHeader(header) - } - if trailingMetadata, ok := md[trailingMetadataKey]; ok { - trailer := metadata.Pairs(trailingMetadataKey, trailingMetadata[0]) - stream.SetTrailer(trailer) - } - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - st := in.GetResponseStatus() - if st != nil && st.Code != 0 { - return status.Error(codes.Code(st.Code), st.Message) - } - cs := in.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(in.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - } -} - -func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error { - var msgBuf []*testpb.StreamingOutputCallRequest - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - break - } - if err != nil { - return err - } - msgBuf = append(msgBuf, in) - } - for _, m := range msgBuf { - cs := m.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - pl, err := serverNewPayload(m.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: pl, - }); err != nil { - return err - } - } - } - return nil -} diff --git a/examples/google.golang.org/grpc/keepalive/keepalive.go b/examples/google.golang.org/grpc/keepalive/keepalive.go deleted file mode 100755 index f8adc7e..0000000 --- a/examples/google.golang.org/grpc/keepalive/keepalive.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package keepalive defines configurable parameters for point-to-point healthcheck. -package keepalive - -import ( - "time" -) - -// ClientParameters is used to set keepalive parameters on the client-side. -// These configure how the client will actively probe to notice when a connection is broken -// and send pings so intermediaries will be aware of the liveness of the connection. -// Make sure these parameters are set in coordination with the keepalive policy on the server, -// as incompatible settings can result in closing of connection. -type ClientParameters struct { - // After a duration of this time if the client doesn't see any activity it pings the server to see if the transport is still alive. - Time time.Duration // The current default value is infinity. - // After having pinged for keepalive check, the client waits for a duration of Timeout and if no activity is seen even after that - // the connection is closed. - Timeout time.Duration // The current default value is 20 seconds. - // If true, client runs keepalive checks even with no active RPCs. - PermitWithoutStream bool // false by default. -} - -// ServerParameters is used to set keepalive and max-age parameters on the server-side. -type ServerParameters struct { - // MaxConnectionIdle is a duration for the amount of time after which an idle connection would be closed by sending a GoAway. - // Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment. - MaxConnectionIdle time.Duration // The current default value is infinity. - // MaxConnectionAge is a duration for the maximum amount of time a connection may exist before it will be closed by sending a GoAway. - // A random jitter of +/-10% will be added to MaxConnectionAge to spread out connection storms. - MaxConnectionAge time.Duration // The current default value is infinity. - // MaxConnectinoAgeGrace is an additive period after MaxConnectionAge after which the connection will be forcibly closed. - MaxConnectionAgeGrace time.Duration // The current default value is infinity. - // After a duration of this time if the server doesn't see any activity it pings the client to see if the transport is still alive. - Time time.Duration // The current default value is 2 hours. - // After having pinged for keepalive check, the server waits for a duration of Timeout and if no activity is seen even after that - // the connection is closed. - Timeout time.Duration // The current default value is 20 seconds. -} - -// EnforcementPolicy is used to set keepalive enforcement policy on the server-side. -// Server will close connection with a client that violates this policy. -type EnforcementPolicy struct { - // MinTime is the minimum amount of time a client should wait before sending a keepalive ping. - MinTime time.Duration // The current default value is 5 minutes. - // If true, server expects keepalive pings even when there are no active streams(RPCs). - PermitWithoutStream bool // false by default. -} diff --git a/examples/google.golang.org/grpc/metadata/metadata.go b/examples/google.golang.org/grpc/metadata/metadata.go deleted file mode 100755 index bd2eaf4..0000000 --- a/examples/google.golang.org/grpc/metadata/metadata.go +++ /dev/null @@ -1,210 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package metadata define the structure of the metadata supported by gRPC library. -// Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md -// for more information about custom-metadata. -package metadata // import "google.golang.org/grpc/metadata" - -import ( - "fmt" - "strings" - - "golang.org/x/net/context" -) - -// DecodeKeyValue returns k, v, nil. -// -// Deprecated: use k and v directly instead. -func DecodeKeyValue(k, v string) (string, string, error) { - return k, v, nil -} - -// MD is a mapping from metadata keys to values. Users should use the following -// two convenience functions New and Pairs to generate MD. -type MD map[string][]string - -// New creates an MD from a given key-value map. -// -// Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// Uppercase letters are automatically converted to lowercase. -// -// Keys beginning with "grpc-" are reserved for grpc-internal use only and may -// result in errors if set in metadata. -func New(m map[string]string) MD { - md := MD{} - for k, val := range m { - key := strings.ToLower(k) - md[key] = append(md[key], val) - } - return md -} - -// Pairs returns an MD formed by the mapping of key, value ... -// Pairs panics if len(kv) is odd. -// -// Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// Uppercase letters are automatically converted to lowercase. -// -// Keys beginning with "grpc-" are reserved for grpc-internal use only and may -// result in errors if set in metadata. -func Pairs(kv ...string) MD { - if len(kv)%2 == 1 { - panic(fmt.Sprintf("metadata: Pairs got the odd number of input pairs for metadata: %d", len(kv))) - } - md := MD{} - var key string - for i, s := range kv { - if i%2 == 0 { - key = strings.ToLower(s) - continue - } - md[key] = append(md[key], s) - } - return md -} - -// Len returns the number of items in md. -func (md MD) Len() int { - return len(md) -} - -// Copy returns a copy of md. -func (md MD) Copy() MD { - return Join(md) -} - -// Get obtains the values for a given key. -func (md MD) Get(k string) []string { - k = strings.ToLower(k) - return md[k] -} - -// Set sets the value of a given key with a slice of values. -func (md MD) Set(k string, vals ...string) { - if len(vals) == 0 { - return - } - k = strings.ToLower(k) - md[k] = vals -} - -// Append adds the values to key k, not overwriting what was already stored at that key. -func (md MD) Append(k string, vals ...string) { - if len(vals) == 0 { - return - } - k = strings.ToLower(k) - md[k] = append(md[k], vals...) -} - -// Join joins any number of mds into a single MD. -// The order of values for each key is determined by the order in which -// the mds containing those values are presented to Join. -func Join(mds ...MD) MD { - out := MD{} - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return out -} - -type mdIncomingKey struct{} -type mdOutgoingKey struct{} - -// NewIncomingContext creates a new context with incoming md attached. -func NewIncomingContext(ctx context.Context, md MD) context.Context { - return context.WithValue(ctx, mdIncomingKey{}, md) -} - -// NewOutgoingContext creates a new context with outgoing md attached. If used -// in conjunction with AppendToOutgoingContext, NewOutgoingContext will -// overwrite any previously-appended metadata. -func NewOutgoingContext(ctx context.Context, md MD) context.Context { - return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) -} - -// AppendToOutgoingContext returns a new context with the provided kv merged -// with any existing metadata in the context. Please refer to the -// documentation of Pairs for a description of kv. -func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context { - if len(kv)%2 == 1 { - panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv))) - } - md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) - added := make([][]string, len(md.added)+1) - copy(added, md.added) - added[len(added)-1] = make([]string, len(kv)) - copy(added[len(added)-1], kv) - return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) -} - -// FromIncomingContext returns the incoming metadata in ctx if it exists. The -// returned MD should not be modified. Writing to it may cause races. -// Modification should be made to copies of the returned MD. -func FromIncomingContext(ctx context.Context) (md MD, ok bool) { - md, ok = ctx.Value(mdIncomingKey{}).(MD) - return -} - -// FromOutgoingContextRaw returns the un-merged, intermediary contents -// of rawMD. Remember to perform strings.ToLower on the keys. The returned -// MD should not be modified. Writing to it may cause races. Modification -// should be made to copies of the returned MD. -// -// This is intended for gRPC-internal use ONLY. -func FromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) { - raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) - if !ok { - return nil, nil, false - } - - return raw.md, raw.added, true -} - -// FromOutgoingContext returns the outgoing metadata in ctx if it exists. The -// returned MD should not be modified. Writing to it may cause races. -// Modification should be made to copies of the returned MD. -func FromOutgoingContext(ctx context.Context) (MD, bool) { - raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) - if !ok { - return nil, false - } - - mds := make([]MD, 0, len(raw.added)+1) - mds = append(mds, raw.md) - for _, vv := range raw.added { - mds = append(mds, Pairs(vv...)) - } - return Join(mds...), ok -} - -type rawMD struct { - md MD - added [][]string -} diff --git a/examples/google.golang.org/grpc/metadata/metadata_test.go b/examples/google.golang.org/grpc/metadata/metadata_test.go deleted file mode 100755 index 4392145..0000000 --- a/examples/google.golang.org/grpc/metadata/metadata_test.go +++ /dev/null @@ -1,251 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package metadata - -import ( - "reflect" - "strconv" - "testing" - - "golang.org/x/net/context" -) - -func TestPairsMD(t *testing.T) { - for _, test := range []struct { - // input - kv []string - // output - md MD - }{ - {[]string{}, MD{}}, - {[]string{"k1", "v1", "k1", "v2"}, MD{"k1": []string{"v1", "v2"}}}, - } { - md := Pairs(test.kv...) - if !reflect.DeepEqual(md, test.md) { - t.Fatalf("Pairs(%v) = %v, want %v", test.kv, md, test.md) - } - } -} - -func TestCopy(t *testing.T) { - const key, val = "key", "val" - orig := Pairs(key, val) - copy := orig.Copy() - if !reflect.DeepEqual(orig, copy) { - t.Errorf("copied value not equal to the original, got %v, want %v", copy, orig) - } - orig[key][0] = "foo" - if v := copy[key][0]; v != val { - t.Errorf("change in original should not affect copy, got %q, want %q", v, val) - } -} - -func TestJoin(t *testing.T) { - for _, test := range []struct { - mds []MD - want MD - }{ - {[]MD{}, MD{}}, - {[]MD{Pairs("foo", "bar")}, Pairs("foo", "bar")}, - {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz")}, Pairs("foo", "bar", "foo", "baz")}, - {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz"), Pairs("zip", "zap")}, Pairs("foo", "bar", "foo", "baz", "zip", "zap")}, - } { - md := Join(test.mds...) - if !reflect.DeepEqual(md, test.want) { - t.Errorf("context's metadata is %v, want %v", md, test.want) - } - } -} - -func TestGet(t *testing.T) { - for _, test := range []struct { - md MD - key string - wantVals []string - }{ - {md: Pairs("My-Optional-Header", "42"), key: "My-Optional-Header", wantVals: []string{"42"}}, - {md: Pairs("Header", "42", "Header", "43", "Header", "44", "other", "1"), key: "HEADER", wantVals: []string{"42", "43", "44"}}, - {md: Pairs("HEADER", "10"), key: "HEADER", wantVals: []string{"10"}}, - } { - vals := test.md.Get(test.key) - if !reflect.DeepEqual(vals, test.wantVals) { - t.Errorf("value of metadata %v is %v, want %v", test.key, vals, test.wantVals) - } - } -} - -func TestSet(t *testing.T) { - for _, test := range []struct { - md MD - setKey string - setVals []string - want MD - }{ - { - md: Pairs("My-Optional-Header", "42", "other-key", "999"), - setKey: "Other-Key", - setVals: []string{"1"}, - want: Pairs("my-optional-header", "42", "other-key", "1"), - }, - { - md: Pairs("My-Optional-Header", "42"), - setKey: "Other-Key", - setVals: []string{"1", "2", "3"}, - want: Pairs("my-optional-header", "42", "other-key", "1", "other-key", "2", "other-key", "3"), - }, - { - md: Pairs("My-Optional-Header", "42"), - setKey: "Other-Key", - setVals: []string{}, - want: Pairs("my-optional-header", "42"), - }, - } { - test.md.Set(test.setKey, test.setVals...) - if !reflect.DeepEqual(test.md, test.want) { - t.Errorf("value of metadata is %v, want %v", test.md, test.want) - } - } -} - -func TestAppend(t *testing.T) { - for _, test := range []struct { - md MD - appendKey string - appendVals []string - want MD - }{ - { - md: Pairs("My-Optional-Header", "42"), - appendKey: "Other-Key", - appendVals: []string{"1"}, - want: Pairs("my-optional-header", "42", "other-key", "1"), - }, - { - md: Pairs("My-Optional-Header", "42"), - appendKey: "my-OptIoNal-HeAder", - appendVals: []string{"1", "2", "3"}, - want: Pairs("my-optional-header", "42", "my-optional-header", "1", - "my-optional-header", "2", "my-optional-header", "3"), - }, - { - md: Pairs("My-Optional-Header", "42"), - appendKey: "my-OptIoNal-HeAder", - appendVals: []string{}, - want: Pairs("my-optional-header", "42"), - }, - } { - test.md.Append(test.appendKey, test.appendVals...) - if !reflect.DeepEqual(test.md, test.want) { - t.Errorf("value of metadata is %v, want %v", test.md, test.want) - } - } -} - -func TestAppendToOutgoingContext(t *testing.T) { - // Pre-existing metadata - ctx := NewOutgoingContext(context.Background(), Pairs("k1", "v1", "k2", "v2")) - ctx = AppendToOutgoingContext(ctx, "k1", "v3") - ctx = AppendToOutgoingContext(ctx, "k1", "v4") - md, ok := FromOutgoingContext(ctx) - if !ok { - t.Errorf("Expected MD to exist in ctx, but got none") - } - want := Pairs("k1", "v1", "k1", "v3", "k1", "v4", "k2", "v2") - if !reflect.DeepEqual(md, want) { - t.Errorf("context's metadata is %v, want %v", md, want) - } - - // No existing metadata - ctx = AppendToOutgoingContext(context.Background(), "k1", "v1") - md, ok = FromOutgoingContext(ctx) - if !ok { - t.Errorf("Expected MD to exist in ctx, but got none") - } - want = Pairs("k1", "v1") - if !reflect.DeepEqual(md, want) { - t.Errorf("context's metadata is %v, want %v", md, want) - } -} - -func TestAppendToOutgoingContext_Repeated(t *testing.T) { - ctx := context.Background() - - for i := 0; i < 100; i = i + 2 { - ctx1 := AppendToOutgoingContext(ctx, "k", strconv.Itoa(i)) - ctx2 := AppendToOutgoingContext(ctx, "k", strconv.Itoa(i+1)) - - md1, _ := FromOutgoingContext(ctx1) - md2, _ := FromOutgoingContext(ctx2) - - if reflect.DeepEqual(md1, md2) { - t.Fatalf("md1, md2 = %v, %v; should not be equal", md1, md2) - } - - ctx = ctx1 - } -} - -func TestAppendToOutgoingContext_FromKVSlice(t *testing.T) { - const k, v = "a", "b" - kv := []string{k, v} - ctx := AppendToOutgoingContext(context.Background(), kv...) - md, _ := FromOutgoingContext(ctx) - if md[k][0] != v { - t.Fatalf("md[%q] = %q; want %q", k, md[k], v) - } - kv[1] = "xxx" - md, _ = FromOutgoingContext(ctx) - if md[k][0] != v { - t.Fatalf("md[%q] = %q; want %q", k, md[k], v) - } -} - -// Old/slow approach to adding metadata to context -func Benchmark_AddingMetadata_ContextManipulationApproach(b *testing.B) { - // TODO: Add in N=1-100 tests once Go1.6 support is removed. - const num = 10 - for n := 0; n < b.N; n++ { - ctx := context.Background() - for i := 0; i < num; i++ { - md, _ := FromOutgoingContext(ctx) - NewOutgoingContext(ctx, Join(Pairs("k1", "v1", "k2", "v2"), md)) - } - } -} - -// Newer/faster approach to adding metadata to context -func BenchmarkAppendToOutgoingContext(b *testing.B) { - const num = 10 - for n := 0; n < b.N; n++ { - ctx := context.Background() - for i := 0; i < num; i++ { - ctx = AppendToOutgoingContext(ctx, "k1", "v1", "k2", "v2") - } - } -} - -func BenchmarkFromOutgoingContext(b *testing.B) { - ctx := context.Background() - ctx = NewOutgoingContext(ctx, MD{"k3": {"v3", "v4"}}) - ctx = AppendToOutgoingContext(ctx, "k1", "v1", "k2", "v2") - - for n := 0; n < b.N; n++ { - FromOutgoingContext(ctx) - } -} diff --git a/examples/google.golang.org/grpc/naming/dns_resolver.go b/examples/google.golang.org/grpc/naming/dns_resolver.go deleted file mode 100755 index 0f8a908..0000000 --- a/examples/google.golang.org/grpc/naming/dns_resolver.go +++ /dev/null @@ -1,290 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import ( - "errors" - "fmt" - "net" - "strconv" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" -) - -const ( - defaultPort = "443" - defaultFreq = time.Minute * 30 -) - -var ( - errMissingAddr = errors.New("missing address") - errWatcherClose = errors.New("watcher has been closed") -) - -// NewDNSResolverWithFreq creates a DNS Resolver that can resolve DNS names, and -// create watchers that poll the DNS server using the frequency set by freq. -func NewDNSResolverWithFreq(freq time.Duration) (Resolver, error) { - return &dnsResolver{freq: freq}, nil -} - -// NewDNSResolver creates a DNS Resolver that can resolve DNS names, and create -// watchers that poll the DNS server using the default frequency defined by defaultFreq. -func NewDNSResolver() (Resolver, error) { - return NewDNSResolverWithFreq(defaultFreq) -} - -// dnsResolver handles name resolution for names following the DNS scheme -type dnsResolver struct { - // frequency of polling the DNS server that the watchers created by this resolver will use. - freq time.Duration -} - -// formatIP returns ok = false if addr is not a valid textual representation of an IP address. -// If addr is an IPv4 address, return the addr and ok = true. -// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. -func formatIP(addr string) (addrIP string, ok bool) { - ip := net.ParseIP(addr) - if ip == nil { - return "", false - } - if ip.To4() != nil { - return addr, true - } - return "[" + addr + "]", true -} - -// parseTarget takes the user input target string, returns formatted host and port info. -// If target doesn't specify a port, set the port to be the defaultPort. -// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets -// are strippd when setting the host. -// examples: -// target: "www.google.com" returns host: "www.google.com", port: "443" -// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" -// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" -// target: ":80" returns host: "localhost", port: "80" -// target: ":" returns host: "localhost", port: "443" -func parseTarget(target string) (host, port string, err error) { - if target == "" { - return "", "", errMissingAddr - } - - if ip := net.ParseIP(target); ip != nil { - // target is an IPv4 or IPv6(without brackets) address - return target, defaultPort, nil - } - if host, port, err := net.SplitHostPort(target); err == nil { - // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port - if host == "" { - // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. - host = "localhost" - } - if port == "" { - // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. - port = defaultPort - } - return host, port, nil - } - if host, port, err := net.SplitHostPort(target + ":" + defaultPort); err == nil { - // target doesn't have port - return host, port, nil - } - return "", "", fmt.Errorf("invalid target address %v", target) -} - -// Resolve creates a watcher that watches the name resolution of the target. -func (r *dnsResolver) Resolve(target string) (Watcher, error) { - host, port, err := parseTarget(target) - if err != nil { - return nil, err - } - - if net.ParseIP(host) != nil { - ipWatcher := &ipWatcher{ - updateChan: make(chan *Update, 1), - } - host, _ = formatIP(host) - ipWatcher.updateChan <- &Update{Op: Add, Addr: host + ":" + port} - return ipWatcher, nil - } - - ctx, cancel := context.WithCancel(context.Background()) - return &dnsWatcher{ - r: r, - host: host, - port: port, - ctx: ctx, - cancel: cancel, - t: time.NewTimer(0), - }, nil -} - -// dnsWatcher watches for the name resolution update for a specific target -type dnsWatcher struct { - r *dnsResolver - host string - port string - // The latest resolved address set - curAddrs map[string]*Update - ctx context.Context - cancel context.CancelFunc - t *time.Timer -} - -// ipWatcher watches for the name resolution update for an IP address. -type ipWatcher struct { - updateChan chan *Update -} - -// Next returns the address resolution Update for the target. For IP address, -// the resolution is itself, thus polling name server is unnecessary. Therefore, -// Next() will return an Update the first time it is called, and will be blocked -// for all following calls as no Update exists until watcher is closed. -func (i *ipWatcher) Next() ([]*Update, error) { - u, ok := <-i.updateChan - if !ok { - return nil, errWatcherClose - } - return []*Update{u}, nil -} - -// Close closes the ipWatcher. -func (i *ipWatcher) Close() { - close(i.updateChan) -} - -// AddressType indicates the address type returned by name resolution. -type AddressType uint8 - -const ( - // Backend indicates the server is a backend server. - Backend AddressType = iota - // GRPCLB indicates the server is a grpclb load balancer. - GRPCLB -) - -// AddrMetadataGRPCLB contains the information the name resolver for grpclb should provide. The -// name resolver used by the grpclb balancer is required to provide this type of metadata in -// its address updates. -type AddrMetadataGRPCLB struct { - // AddrType is the type of server (grpc load balancer or backend). - AddrType AddressType - // ServerName is the name of the grpc load balancer. Used for authentication. - ServerName string -} - -// compileUpdate compares the old resolved addresses and newly resolved addresses, -// and generates an update list -func (w *dnsWatcher) compileUpdate(newAddrs map[string]*Update) []*Update { - var res []*Update - for a, u := range w.curAddrs { - if _, ok := newAddrs[a]; !ok { - u.Op = Delete - res = append(res, u) - } - } - for a, u := range newAddrs { - if _, ok := w.curAddrs[a]; !ok { - res = append(res, u) - } - } - return res -} - -func (w *dnsWatcher) lookupSRV() map[string]*Update { - newAddrs := make(map[string]*Update) - _, srvs, err := lookupSRV(w.ctx, "grpclb", "tcp", w.host) - if err != nil { - grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) - return nil - } - for _, s := range srvs { - lbAddrs, err := lookupHost(w.ctx, s.Target) - if err != nil { - grpclog.Warningf("grpc: failed load banlacer address dns lookup due to %v.\n", err) - continue - } - for _, a := range lbAddrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + strconv.Itoa(int(s.Port)) - newAddrs[addr] = &Update{Addr: addr, - Metadata: AddrMetadataGRPCLB{AddrType: GRPCLB, ServerName: s.Target}} - } - } - return newAddrs -} - -func (w *dnsWatcher) lookupHost() map[string]*Update { - newAddrs := make(map[string]*Update) - addrs, err := lookupHost(w.ctx, w.host) - if err != nil { - grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) - return nil - } - for _, a := range addrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + w.port - newAddrs[addr] = &Update{Addr: addr} - } - return newAddrs -} - -func (w *dnsWatcher) lookup() []*Update { - newAddrs := w.lookupSRV() - if newAddrs == nil { - // If failed to get any balancer address (either no corresponding SRV for the - // target, or caused by failure during resolution/parsing of the balancer target), - // return any A record info available. - newAddrs = w.lookupHost() - } - result := w.compileUpdate(newAddrs) - w.curAddrs = newAddrs - return result -} - -// Next returns the resolved address update(delta) for the target. If there's no -// change, it will sleep for 30 mins and try to resolve again after that. -func (w *dnsWatcher) Next() ([]*Update, error) { - for { - select { - case <-w.ctx.Done(): - return nil, errWatcherClose - case <-w.t.C: - } - result := w.lookup() - // Next lookup should happen after an interval defined by w.r.freq. - w.t.Reset(w.r.freq) - if len(result) > 0 { - return result, nil - } - } -} - -func (w *dnsWatcher) Close() { - w.cancel() -} diff --git a/examples/google.golang.org/grpc/naming/dns_resolver_test.go b/examples/google.golang.org/grpc/naming/dns_resolver_test.go deleted file mode 100755 index be1ac1a..0000000 --- a/examples/google.golang.org/grpc/naming/dns_resolver_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import ( - "fmt" - "net" - "reflect" - "sync" - "testing" - "time" -) - -func newUpdateWithMD(op Operation, addr, lb string) *Update { - return &Update{ - Op: op, - Addr: addr, - Metadata: AddrMetadataGRPCLB{AddrType: GRPCLB, ServerName: lb}, - } -} - -func toMap(u []*Update) map[string]*Update { - m := make(map[string]*Update) - for _, v := range u { - m[v.Addr] = v - } - return m -} - -func TestCompileUpdate(t *testing.T) { - tests := []struct { - oldAddrs []string - newAddrs []string - want []*Update - }{ - { - []string{}, - []string{"1.0.0.1"}, - []*Update{{Op: Add, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.1"}, - []*Update{}, - }, - { - []string{"1.0.0.0"}, - []string{"1.0.0.1"}, - []*Update{{Op: Delete, Addr: "1.0.0.0"}, {Op: Add, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.0"}, - []*Update{{Op: Add, Addr: "1.0.0.0"}, {Op: Delete, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.1", "1.0.0.2", "1.0.0.3"}, - []*Update{{Op: Add, Addr: "1.0.0.2"}, {Op: Add, Addr: "1.0.0.3"}}, - }, - { - []string{"1.0.0.1", "1.0.0.2", "1.0.0.3"}, - []string{"1.0.0.0"}, - []*Update{{Op: Add, Addr: "1.0.0.0"}, {Op: Delete, Addr: "1.0.0.1"}, {Op: Delete, Addr: "1.0.0.2"}, {Op: Delete, Addr: "1.0.0.3"}}, - }, - { - []string{"1.0.0.1", "1.0.0.3", "1.0.0.5"}, - []string{"1.0.0.2", "1.0.0.3", "1.0.0.6"}, - []*Update{{Op: Delete, Addr: "1.0.0.1"}, {Op: Add, Addr: "1.0.0.2"}, {Op: Delete, Addr: "1.0.0.5"}, {Op: Add, Addr: "1.0.0.6"}}, - }, - { - []string{"1.0.0.1", "1.0.0.1", "1.0.0.2"}, - []string{"1.0.0.1"}, - []*Update{{Op: Delete, Addr: "1.0.0.2"}}, - }, - } - - var w dnsWatcher - for _, c := range tests { - w.curAddrs = make(map[string]*Update) - newUpdates := make(map[string]*Update) - for _, a := range c.oldAddrs { - w.curAddrs[a] = &Update{Addr: a} - } - for _, a := range c.newAddrs { - newUpdates[a] = &Update{Addr: a} - } - r := w.compileUpdate(newUpdates) - if !reflect.DeepEqual(toMap(c.want), toMap(r)) { - t.Errorf("w(%+v).compileUpdate(%+v) = %+v, want %+v", c.oldAddrs, c.newAddrs, updatesToSlice(r), updatesToSlice(c.want)) - } - } -} - -func TestResolveFunc(t *testing.T) { - tests := []struct { - addr string - want error - }{ - // TODO(yuxuanli): More false cases? - {"www.google.com", nil}, - {"foo.bar:12345", nil}, - {"127.0.0.1", nil}, - {"127.0.0.1:12345", nil}, - {"[::1]:80", nil}, - {"[2001:db8:a0b:12f0::1]:21", nil}, - {":80", nil}, - {"127.0.0...1:12345", nil}, - {"[fe80::1%lo0]:80", nil}, - {"golang.org:http", nil}, - {"[2001:db8::1]:http", nil}, - {":", nil}, - {"", errMissingAddr}, - {"[2001:db8:a0b:12f0::1", fmt.Errorf("invalid target address %v", "[2001:db8:a0b:12f0::1")}, - } - - r, err := NewDNSResolver() - if err != nil { - t.Errorf("%v", err) - } - for _, v := range tests { - _, err := r.Resolve(v.addr) - if !reflect.DeepEqual(err, v.want) { - t.Errorf("Resolve(%q) = %v, want %v", v.addr, err, v.want) - } - } -} - -var hostLookupTbl = map[string][]string{ - "foo.bar.com": {"1.2.3.4", "5.6.7.8"}, - "ipv4.single.fake": {"1.2.3.4"}, - "ipv4.multi.fake": {"1.2.3.4", "5.6.7.8", "9.10.11.12"}, - "ipv6.single.fake": {"2607:f8b0:400a:801::1001"}, - "ipv6.multi.fake": {"2607:f8b0:400a:801::1001", "2607:f8b0:400a:801::1002", "2607:f8b0:400a:801::1003"}, -} - -func hostLookup(host string) ([]string, error) { - if addrs, ok := hostLookupTbl[host]; ok { - return addrs, nil - } - return nil, fmt.Errorf("failed to lookup host:%s resolution in hostLookupTbl", host) -} - -var srvLookupTbl = map[string][]*net.SRV{ - "_grpclb._tcp.srv.ipv4.single.fake": {&net.SRV{Target: "ipv4.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv4.multi.fake": {&net.SRV{Target: "ipv4.multi.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.single.fake": {&net.SRV{Target: "ipv6.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.multi.fake": {&net.SRV{Target: "ipv6.multi.fake", Port: 1234}}, -} - -func srvLookup(service, proto, name string) (string, []*net.SRV, error) { - cname := "_" + service + "._" + proto + "." + name - if srvs, ok := srvLookupTbl[cname]; ok { - return cname, srvs, nil - } - return "", nil, fmt.Errorf("failed to lookup srv record for %s in srvLookupTbl", cname) -} - -func updatesToSlice(updates []*Update) []Update { - res := make([]Update, len(updates)) - for i, u := range updates { - res[i] = *u - } - return res -} - -func testResolver(t *testing.T, freq time.Duration, slp time.Duration) { - tests := []struct { - target string - want []*Update - }{ - { - "foo.bar.com", - []*Update{{Op: Add, Addr: "1.2.3.4" + colonDefaultPort}, {Op: Add, Addr: "5.6.7.8" + colonDefaultPort}}, - }, - { - "foo.bar.com:1234", - []*Update{{Op: Add, Addr: "1.2.3.4:1234"}, {Op: Add, Addr: "5.6.7.8:1234"}}, - }, - { - "srv.ipv4.single.fake", - []*Update{newUpdateWithMD(Add, "1.2.3.4:1234", "ipv4.single.fake")}, - }, - { - "srv.ipv4.multi.fake", - []*Update{ - newUpdateWithMD(Add, "1.2.3.4:1234", "ipv4.multi.fake"), - newUpdateWithMD(Add, "5.6.7.8:1234", "ipv4.multi.fake"), - newUpdateWithMD(Add, "9.10.11.12:1234", "ipv4.multi.fake")}, - }, - { - "srv.ipv6.single.fake", - []*Update{newUpdateWithMD(Add, "[2607:f8b0:400a:801::1001]:1234", "ipv6.single.fake")}, - }, - { - "srv.ipv6.multi.fake", - []*Update{ - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1001]:1234", "ipv6.multi.fake"), - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1002]:1234", "ipv6.multi.fake"), - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1003]:1234", "ipv6.multi.fake"), - }, - }, - } - - for _, a := range tests { - r, err := NewDNSResolverWithFreq(freq) - if err != nil { - t.Fatalf("%v\n", err) - } - w, err := r.Resolve(a.target) - if err != nil { - t.Fatalf("%v\n", err) - } - updates, err := w.Next() - if err != nil { - t.Fatalf("%v\n", err) - } - if !reflect.DeepEqual(toMap(a.want), toMap(updates)) { - t.Errorf("Resolve(%q) = %+v, want %+v\n", a.target, updatesToSlice(updates), updatesToSlice(a.want)) - } - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - for { - _, err := w.Next() - if err != nil { - return - } - t.Error("Execution shouldn't reach here, since w.Next() should be blocked until close happen.") - } - }() - // Sleep for sometime to let watcher do more than one lookup - time.Sleep(slp) - w.Close() - wg.Wait() - } -} - -func TestResolve(t *testing.T) { - defer replaceNetFunc()() - testResolver(t, time.Millisecond*5, time.Millisecond*10) -} - -const colonDefaultPort = ":" + defaultPort - -func TestIPWatcher(t *testing.T) { - tests := []struct { - target string - want []*Update - }{ - {"127.0.0.1", []*Update{{Op: Add, Addr: "127.0.0.1" + colonDefaultPort}}}, - {"127.0.0.1:12345", []*Update{{Op: Add, Addr: "127.0.0.1:12345"}}}, - {"::1", []*Update{{Op: Add, Addr: "[::1]" + colonDefaultPort}}}, - {"[::1]:12345", []*Update{{Op: Add, Addr: "[::1]:12345"}}}, - {"[::1]:", []*Update{{Op: Add, Addr: "[::1]:443"}}}, - {"2001:db8:85a3::8a2e:370:7334", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]:12345", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]:12345"}}}, - {"[2001:db8::1]:http", []*Update{{Op: Add, Addr: "[2001:db8::1]:http"}}}, - // TODO(yuxuanli): zone support? - } - - for _, v := range tests { - r, err := NewDNSResolverWithFreq(time.Millisecond * 5) - if err != nil { - t.Fatalf("%v\n", err) - } - w, err := r.Resolve(v.target) - if err != nil { - t.Fatalf("%v\n", err) - } - var updates []*Update - var wg sync.WaitGroup - wg.Add(1) - count := 0 - go func() { - defer wg.Done() - for { - u, err := w.Next() - if err != nil { - return - } - updates = u - count++ - } - }() - // Sleep for sometime to let watcher do more than one lookup - time.Sleep(time.Millisecond * 10) - w.Close() - wg.Wait() - if !reflect.DeepEqual(v.want, updates) { - t.Errorf("Resolve(%q) = %v, want %+v\n", v.target, updatesToSlice(updates), updatesToSlice(v.want)) - } - if count != 1 { - t.Errorf("IPWatcher Next() should return only once, not %d times\n", count) - } - } -} diff --git a/examples/google.golang.org/grpc/naming/go17.go b/examples/google.golang.org/grpc/naming/go17.go deleted file mode 100755 index 57b65d7..0000000 --- a/examples/google.golang.org/grpc/naming/go17.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build go1.6,!go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import ( - "net" - - "golang.org/x/net/context" -) - -var ( - lookupHost = func(ctx context.Context, host string) ([]string, error) { return net.LookupHost(host) } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return net.LookupSRV(service, proto, name) - } -) diff --git a/examples/google.golang.org/grpc/naming/go17_test.go b/examples/google.golang.org/grpc/naming/go17_test.go deleted file mode 100755 index db39b9a..0000000 --- a/examples/google.golang.org/grpc/naming/go17_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build go1.6, !go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import ( - "net" - - "golang.org/x/net/context" -) - -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) - } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - } -} diff --git a/examples/google.golang.org/grpc/naming/go18.go b/examples/google.golang.org/grpc/naming/go18.go deleted file mode 100755 index b5a0f84..0000000 --- a/examples/google.golang.org/grpc/naming/go18.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import "net" - -var ( - lookupHost = net.DefaultResolver.LookupHost - lookupSRV = net.DefaultResolver.LookupSRV -) diff --git a/examples/google.golang.org/grpc/naming/go18_test.go b/examples/google.golang.org/grpc/naming/go18_test.go deleted file mode 100755 index 5e29753..0000000 --- a/examples/google.golang.org/grpc/naming/go18_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package naming - -import ( - "context" - "net" -) - -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) - } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - } -} diff --git a/examples/google.golang.org/grpc/naming/naming.go b/examples/google.golang.org/grpc/naming/naming.go deleted file mode 100755 index 8cc39e9..0000000 --- a/examples/google.golang.org/grpc/naming/naming.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package naming defines the naming API and related data structures for gRPC. -// The interface is EXPERIMENTAL and may be suject to change. -// -// Deprecated: please use package resolver. -package naming - -// Operation defines the corresponding operations for a name resolution change. -// -// Deprecated: please use package resolver. -type Operation uint8 - -const ( - // Add indicates a new address is added. - Add Operation = iota - // Delete indicates an existing address is deleted. - Delete -) - -// Update defines a name resolution update. Notice that it is not valid having both -// empty string Addr and nil Metadata in an Update. -// -// Deprecated: please use package resolver. -type Update struct { - // Op indicates the operation of the update. - Op Operation - // Addr is the updated address. It is empty string if there is no address update. - Addr string - // Metadata is the updated metadata. It is nil if there is no metadata update. - // Metadata is not required for a custom naming implementation. - Metadata interface{} -} - -// Resolver creates a Watcher for a target to track its resolution changes. -// -// Deprecated: please use package resolver. -type Resolver interface { - // Resolve creates a Watcher for target. - Resolve(target string) (Watcher, error) -} - -// Watcher watches for the updates on the specified target. -// -// Deprecated: please use package resolver. -type Watcher interface { - // Next blocks until an update or error happens. It may return one or more - // updates. The first call should get the full set of the results. It should - // return an error if and only if Watcher cannot recover. - Next() ([]*Update, error) - // Close closes the Watcher. - Close() -} diff --git a/examples/google.golang.org/grpc/peer/peer.go b/examples/google.golang.org/grpc/peer/peer.go deleted file mode 100755 index 317b8b9..0000000 --- a/examples/google.golang.org/grpc/peer/peer.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package peer defines various peer information associated with RPCs and -// corresponding utils. -package peer - -import ( - "net" - - "golang.org/x/net/context" - "google.golang.org/grpc/credentials" -) - -// Peer contains the information of the peer for an RPC, such as the address -// and authentication information. -type Peer struct { - // Addr is the peer address. - Addr net.Addr - // AuthInfo is the authentication information of the transport. - // It is nil if there is no transport security being used. - AuthInfo credentials.AuthInfo -} - -type peerKey struct{} - -// NewContext creates a new context with peer information attached. -func NewContext(ctx context.Context, p *Peer) context.Context { - return context.WithValue(ctx, peerKey{}, p) -} - -// FromContext returns the peer information in ctx if it exists. -func FromContext(ctx context.Context) (p *Peer, ok bool) { - p, ok = ctx.Value(peerKey{}).(*Peer) - return -} diff --git a/examples/google.golang.org/grpc/picker_wrapper.go b/examples/google.golang.org/grpc/picker_wrapper.go deleted file mode 100755 index 019e658..0000000 --- a/examples/google.golang.org/grpc/picker_wrapper.go +++ /dev/null @@ -1,336 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "io" - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick -// actions and unblock when there's a picker update. -type pickerWrapper struct { - mu sync.Mutex - done bool - blockingCh chan struct{} - picker balancer.Picker - - // The latest connection happened. - connErrMu sync.Mutex - connErr error - - stickinessMDKey atomic.Value - stickiness *stickyStore -} - -func newPickerWrapper() *pickerWrapper { - bp := &pickerWrapper{ - blockingCh: make(chan struct{}), - stickiness: newStickyStore(), - } - return bp -} - -func (bp *pickerWrapper) updateConnectionError(err error) { - bp.connErrMu.Lock() - bp.connErr = err - bp.connErrMu.Unlock() -} - -func (bp *pickerWrapper) connectionError() error { - bp.connErrMu.Lock() - err := bp.connErr - bp.connErrMu.Unlock() - return err -} - -func (bp *pickerWrapper) updateStickinessMDKey(newKey string) { - // No need to check ok because mdKey == "" if ok == false. - if oldKey, _ := bp.stickinessMDKey.Load().(string); oldKey != newKey { - bp.stickinessMDKey.Store(newKey) - bp.stickiness.reset(newKey) - } -} - -func (bp *pickerWrapper) getStickinessMDKey() string { - // No need to check ok because mdKey == "" if ok == false. - mdKey, _ := bp.stickinessMDKey.Load().(string) - return mdKey -} - -func (bp *pickerWrapper) clearStickinessState() { - if oldKey := bp.getStickinessMDKey(); oldKey != "" { - // There's no need to reset store if mdKey was "". - bp.stickiness.reset(oldKey) - } -} - -// updatePicker is called by UpdateBalancerState. It unblocks all blocked pick. -func (bp *pickerWrapper) updatePicker(p balancer.Picker) { - bp.mu.Lock() - if bp.done { - bp.mu.Unlock() - return - } - bp.picker = p - // bp.blockingCh should never be nil. - close(bp.blockingCh) - bp.blockingCh = make(chan struct{}) - bp.mu.Unlock() -} - -func doneChannelzWrapper(acw *acBalancerWrapper, done func(balancer.DoneInfo)) func(balancer.DoneInfo) { - acw.mu.Lock() - ac := acw.ac - acw.mu.Unlock() - ac.incrCallsStarted() - return func(b balancer.DoneInfo) { - if b.Err != nil && b.Err != io.EOF { - ac.incrCallsFailed() - } else { - ac.incrCallsSucceeded() - } - if done != nil { - done(b) - } - } -} - -// pick returns the transport that will be used for the RPC. -// It may block in the following cases: -// - there's no picker -// - the current picker returns ErrNoSubConnAvailable -// - the current picker returns other errors and failfast is false. -// - the subConn returned by the current picker is not READY -// When one of these situations happens, pick blocks until the picker gets updated. -func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer.PickOptions) (transport.ClientTransport, func(balancer.DoneInfo), error) { - - mdKey := bp.getStickinessMDKey() - stickyKey, isSticky := stickyKeyFromContext(ctx, mdKey) - - // Potential race here: if stickinessMDKey is updated after the above two - // lines, and this pick is a sticky pick, the following put could add an - // entry to sticky store with an outdated sticky key. - // - // The solution: keep the current md key in sticky store, and at the - // beginning of each get/put, check the mdkey against store.curMDKey. - // - Cons: one more string comparing for each get/put. - // - Pros: the string matching happens inside get/put, so the overhead for - // non-sticky RPCs will be minimal. - - if isSticky { - if t, ok := bp.stickiness.get(mdKey, stickyKey); ok { - // Done function returned is always nil. - return t, nil, nil - } - } - - var ( - p balancer.Picker - ch chan struct{} - ) - - for { - bp.mu.Lock() - if bp.done { - bp.mu.Unlock() - return nil, nil, ErrClientConnClosing - } - - if bp.picker == nil { - ch = bp.blockingCh - } - if ch == bp.blockingCh { - // This could happen when either: - // - bp.picker is nil (the previous if condition), or - // - has called pick on the current picker. - bp.mu.Unlock() - select { - case <-ctx.Done(): - return nil, nil, ctx.Err() - case <-ch: - } - continue - } - - ch = bp.blockingCh - p = bp.picker - bp.mu.Unlock() - - subConn, done, err := p.Pick(ctx, opts) - - if err != nil { - switch err { - case balancer.ErrNoSubConnAvailable: - continue - case balancer.ErrTransientFailure: - if !failfast { - continue - } - return nil, nil, status.Errorf(codes.Unavailable, "%v, latest connection error: %v", err, bp.connectionError()) - default: - // err is some other error. - return nil, nil, toRPCErr(err) - } - } - - acw, ok := subConn.(*acBalancerWrapper) - if !ok { - grpclog.Infof("subconn returned from pick is not *acBalancerWrapper") - continue - } - if t, ok := acw.getAddrConn().getReadyTransport(); ok { - if isSticky { - bp.stickiness.put(mdKey, stickyKey, acw) - } - if channelz.IsOn() { - return t, doneChannelzWrapper(acw, done), nil - } - return t, done, nil - } - grpclog.Infof("blockingPicker: the picked transport is not ready, loop back to repick") - // If ok == false, ac.state is not READY. - // A valid picker always returns READY subConn. This means the state of ac - // just changed, and picker will be updated shortly. - // continue back to the beginning of the for loop to repick. - } -} - -func (bp *pickerWrapper) close() { - bp.mu.Lock() - defer bp.mu.Unlock() - if bp.done { - return - } - bp.done = true - close(bp.blockingCh) -} - -const stickinessKeyCountLimit = 1000 - -type stickyStoreEntry struct { - acw *acBalancerWrapper - addr resolver.Address -} - -type stickyStore struct { - mu sync.Mutex - // curMDKey is check before every get/put to avoid races. The operation will - // abort immediately when the given mdKey is different from the curMDKey. - curMDKey string - store *linkedMap -} - -func newStickyStore() *stickyStore { - return &stickyStore{ - store: newLinkedMap(), - } -} - -// reset clears the map in stickyStore, and set the currentMDKey to newMDKey. -func (ss *stickyStore) reset(newMDKey string) { - ss.mu.Lock() - ss.curMDKey = newMDKey - ss.store.clear() - ss.mu.Unlock() -} - -// stickyKey is the key to look up in store. mdKey will be checked against -// curMDKey to avoid races. -func (ss *stickyStore) put(mdKey, stickyKey string, acw *acBalancerWrapper) { - ss.mu.Lock() - defer ss.mu.Unlock() - if mdKey != ss.curMDKey { - return - } - // TODO(stickiness): limit the total number of entries. - ss.store.put(stickyKey, &stickyStoreEntry{ - acw: acw, - addr: acw.getAddrConn().getCurAddr(), - }) - if ss.store.len() > stickinessKeyCountLimit { - ss.store.removeOldest() - } -} - -// stickyKey is the key to look up in store. mdKey will be checked against -// curMDKey to avoid races. -func (ss *stickyStore) get(mdKey, stickyKey string) (transport.ClientTransport, bool) { - ss.mu.Lock() - defer ss.mu.Unlock() - if mdKey != ss.curMDKey { - return nil, false - } - entry, ok := ss.store.get(stickyKey) - if !ok { - return nil, false - } - ac := entry.acw.getAddrConn() - if ac.getCurAddr() != entry.addr { - ss.store.remove(stickyKey) - return nil, false - } - t, ok := ac.getReadyTransport() - if !ok { - ss.store.remove(stickyKey) - return nil, false - } - return t, true -} - -// Get one value from metadata in ctx with key stickinessMDKey. -// -// It returns "", false if stickinessMDKey is an empty string. -func stickyKeyFromContext(ctx context.Context, stickinessMDKey string) (string, bool) { - if stickinessMDKey == "" { - return "", false - } - - md, added, ok := metadata.FromOutgoingContextRaw(ctx) - if !ok { - return "", false - } - - if vv, ok := md[stickinessMDKey]; ok { - if len(vv) > 0 { - return vv[0], true - } - } - - for _, ss := range added { - for i := 0; i < len(ss)-1; i += 2 { - if ss[i] == stickinessMDKey { - return ss[i+1], true - } - } - } - - return "", false -} diff --git a/examples/google.golang.org/grpc/picker_wrapper_test.go b/examples/google.golang.org/grpc/picker_wrapper_test.go deleted file mode 100755 index d455286..0000000 --- a/examples/google.golang.org/grpc/picker_wrapper_test.go +++ /dev/null @@ -1,160 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/transport" -) - -const goroutineCount = 5 - -var ( - testT = &testTransport{} - testSC = &acBalancerWrapper{ac: &addrConn{ - state: connectivity.Ready, - transport: testT, - }} - testSCNotReady = &acBalancerWrapper{ac: &addrConn{ - state: connectivity.TransientFailure, - }} -) - -type testTransport struct { - transport.ClientTransport -} - -type testingPicker struct { - err error - sc balancer.SubConn - maxCalled int64 -} - -func (p *testingPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if atomic.AddInt64(&p.maxCalled, -1) < 0 { - return nil, nil, fmt.Errorf("Pick called to many times (> goroutineCount)") - } - if p.err != nil { - return nil, nil, p.err - } - return p.sc, nil, nil -} - -func TestBlockingPickTimeout(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, _, err := bp.pick(ctx, true, balancer.PickOptions{}); err != context.DeadlineExceeded { - t.Errorf("bp.pick returned error %v, want DeadlineExceeded", err) - } -} - -func TestBlockingPick(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - // All goroutines should block because picker is nil in bp. - var finishedCount uint64 - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(50 * time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickNoSubAvailable(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - var finishedCount uint64 - bp.updatePicker(&testingPicker{err: balancer.ErrNoSubConnAvailable, maxCalled: goroutineCount}) - // All goroutines should block because picker returns no sc available. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(50 * time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickTransientWaitforready(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - bp.updatePicker(&testingPicker{err: balancer.ErrTransientFailure, maxCalled: goroutineCount}) - var finishedCount uint64 - // All goroutines should block because picker returns transientFailure and - // picks are not failfast. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), false, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickSCNotReady(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - bp.updatePicker(&testingPicker{sc: testSCNotReady, maxCalled: goroutineCount}) - var finishedCount uint64 - // All goroutines should block because sc is not ready. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} diff --git a/examples/google.golang.org/grpc/pickfirst.go b/examples/google.golang.org/grpc/pickfirst.go deleted file mode 100755 index bf659d4..0000000 --- a/examples/google.golang.org/grpc/pickfirst.go +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// PickFirstBalancerName is the name of the pick_first balancer. -const PickFirstBalancerName = "pick_first" - -func newPickfirstBuilder() balancer.Builder { - return &pickfirstBuilder{} -} - -type pickfirstBuilder struct{} - -func (*pickfirstBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { - return &pickfirstBalancer{cc: cc} -} - -func (*pickfirstBuilder) Name() string { - return PickFirstBalancerName -} - -type pickfirstBalancer struct { - cc balancer.ClientConn - sc balancer.SubConn -} - -func (b *pickfirstBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - if err != nil { - grpclog.Infof("pickfirstBalancer: HandleResolvedAddrs called with error %v", err) - return - } - if b.sc == nil { - b.sc, err = b.cc.NewSubConn(addrs, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Errorf("pickfirstBalancer: failed to NewSubConn: %v", err) - return - } - b.cc.UpdateBalancerState(connectivity.Idle, &picker{sc: b.sc}) - b.sc.Connect() - } else { - b.sc.UpdateAddresses(addrs) - b.sc.Connect() - } -} - -func (b *pickfirstBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("pickfirstBalancer: HandleSubConnStateChange: %p, %v", sc, s) - if b.sc != sc { - grpclog.Infof("pickfirstBalancer: ignored state change because sc is not recognized") - return - } - if s == connectivity.Shutdown { - b.sc = nil - return - } - - switch s { - case connectivity.Ready, connectivity.Idle: - b.cc.UpdateBalancerState(s, &picker{sc: sc}) - case connectivity.Connecting: - b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrNoSubConnAvailable}) - case connectivity.TransientFailure: - b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrTransientFailure}) - } -} - -func (b *pickfirstBalancer) Close() { -} - -type picker struct { - err error - sc balancer.SubConn -} - -func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if p.err != nil { - return nil, nil, p.err - } - return p.sc, nil, nil -} - -func init() { - balancer.Register(newPickfirstBuilder()) -} diff --git a/examples/google.golang.org/grpc/pickfirst_test.go b/examples/google.golang.org/grpc/pickfirst_test.go deleted file mode 100755 index 7f8169f..0000000 --- a/examples/google.golang.org/grpc/pickfirst_test.go +++ /dev/null @@ -1,360 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "math" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - "google.golang.org/grpc/status" -) - -func errorDesc(err error) string { - if s, ok := status.FromError(err); ok { - return s.Message() - } - return err.Error() -} - -func TestOneBackendPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - // The second RPC should succeed. - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestBackendsPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestNewAddressWhileBlockingPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until NewAddress is called. - cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - }() - } - time.Sleep(50 * time.Millisecond) - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - wg.Wait() -} - -func TestCloseWithPendingRPCPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - _, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until NewAddress is called. - cc.Invoke(context.Background(), "/foo/bar", &req, &reply) - }() - } - time.Sleep(50 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestOneServerDownPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{}), WithWaitForHandshake()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - - servers[0].stop() - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestAllServersDownPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{}), WithWaitForHandshake()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - - for i := 0; i < numServers; i++ { - servers[i].stop() - } - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); status.Code(err) == codes.Unavailable { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, error with code unavailable", err) -} - -func TestAddressesRemovedPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 3 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := cc.Invoke(ctx, "/foo/bar", &req, &reply); err == nil || status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}, {Addr: servers[2].addr}}) - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[0]. - r.NewAddress([]resolver.Address{{Addr: servers[1].addr}, {Addr: servers[2].addr}}) - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[1].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Append server[0], nothing should change. - r.NewAddress([]resolver.Address{{Addr: servers[1].addr}, {Addr: servers[2].addr}, {Addr: servers[0].addr}}) - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[1]. - r.NewAddress([]resolver.Address{{Addr: servers[2].addr}, {Addr: servers[0].addr}}) - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[2].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[2].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 2, err, servers[2].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[2]. - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - for i := 0; i < 1000; i++ { - if err = cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err != nil && errorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := cc.Invoke(context.Background(), "/foo/bar", &req, &reply); err == nil || errorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} diff --git a/examples/google.golang.org/grpc/proxy.go b/examples/google.golang.org/grpc/proxy.go deleted file mode 100755 index 2d40236..0000000 --- a/examples/google.golang.org/grpc/proxy.go +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "bufio" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/http/httputil" - "net/url" - - "golang.org/x/net/context" -) - -var ( - // errDisabled indicates that proxy is disabled for the address. - errDisabled = errors.New("proxy is disabled for the address") - // The following variable will be overwritten in the tests. - httpProxyFromEnvironment = http.ProxyFromEnvironment -) - -func mapAddress(ctx context.Context, address string) (string, error) { - req := &http.Request{ - URL: &url.URL{ - Scheme: "https", - Host: address, - }, - } - url, err := httpProxyFromEnvironment(req) - if err != nil { - return "", err - } - if url == nil { - return "", errDisabled - } - return url.Host, nil -} - -// To read a response from a net.Conn, http.ReadResponse() takes a bufio.Reader. -// It's possible that this reader reads more than what's need for the response and stores -// those bytes in the buffer. -// bufConn wraps the original net.Conn and the bufio.Reader to make sure we don't lose the -// bytes in the buffer. -type bufConn struct { - net.Conn - r io.Reader -} - -func (c *bufConn) Read(b []byte) (int, error) { - return c.r.Read(b) -} - -func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ net.Conn, err error) { - defer func() { - if err != nil { - conn.Close() - } - }() - - req := (&http.Request{ - Method: http.MethodConnect, - URL: &url.URL{Host: addr}, - Header: map[string][]string{"User-Agent": {grpcUA}}, - }) - - if err := sendHTTPRequest(ctx, req, conn); err != nil { - return nil, fmt.Errorf("failed to write the HTTP request: %v", err) - } - - r := bufio.NewReader(conn) - resp, err := http.ReadResponse(r, req) - if err != nil { - return nil, fmt.Errorf("reading server HTTP response: %v", err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - dump, err := httputil.DumpResponse(resp, true) - if err != nil { - return nil, fmt.Errorf("failed to do connect handshake, status code: %s", resp.Status) - } - return nil, fmt.Errorf("failed to do connect handshake, response: %q", dump) - } - - return &bufConn{Conn: conn, r: r}, nil -} - -// newProxyDialer returns a dialer that connects to proxy first if necessary. -// The returned dialer checks if a proxy is necessary, dial to the proxy with the -// provided dialer, does HTTP CONNECT handshake and returns the connection. -func newProxyDialer(dialer func(context.Context, string) (net.Conn, error)) func(context.Context, string) (net.Conn, error) { - return func(ctx context.Context, addr string) (conn net.Conn, err error) { - var skipHandshake bool - newAddr, err := mapAddress(ctx, addr) - if err != nil { - if err != errDisabled { - return nil, err - } - skipHandshake = true - newAddr = addr - } - - conn, err = dialer(ctx, newAddr) - if err != nil { - return - } - if !skipHandshake { - conn, err = doHTTPConnectHandshake(ctx, conn, addr) - } - return - } -} diff --git a/examples/google.golang.org/grpc/proxy_test.go b/examples/google.golang.org/grpc/proxy_test.go deleted file mode 100755 index 7183ba3..0000000 --- a/examples/google.golang.org/grpc/proxy_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// +build !race - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "bufio" - "io" - "net" - "net/http" - "net/url" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/internal/leakcheck" -) - -const ( - envTestAddr = "1.2.3.4:8080" - envProxyAddr = "2.3.4.5:7687" -) - -// overwriteAndRestore overwrite function httpProxyFromEnvironment and -// returns a function to restore the default values. -func overwrite(hpfe func(req *http.Request) (*url.URL, error)) func() { - backHPFE := httpProxyFromEnvironment - httpProxyFromEnvironment = hpfe - return func() { - httpProxyFromEnvironment = backHPFE - } -} - -type proxyServer struct { - t *testing.T - lis net.Listener - in net.Conn - out net.Conn -} - -func (p *proxyServer) run() { - in, err := p.lis.Accept() - if err != nil { - return - } - p.in = in - - req, err := http.ReadRequest(bufio.NewReader(in)) - if err != nil { - p.t.Errorf("failed to read CONNECT req: %v", err) - return - } - if req.Method != http.MethodConnect || req.UserAgent() != grpcUA { - resp := http.Response{StatusCode: http.StatusMethodNotAllowed} - resp.Write(p.in) - p.in.Close() - p.t.Errorf("get wrong CONNECT req: %+v", req) - return - } - - out, err := net.Dial("tcp", req.URL.Host) - if err != nil { - p.t.Errorf("failed to dial to server: %v", err) - return - } - resp := http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.0"} - resp.Write(p.in) - p.out = out - go io.Copy(p.in, p.out) - go io.Copy(p.out, p.in) -} - -func (p *proxyServer) stop() { - p.lis.Close() - if p.in != nil { - p.in.Close() - } - if p.out != nil { - p.out.Close() - } -} - -func TestHTTPConnect(t *testing.T) { - defer leakcheck.Check(t) - plis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - p := &proxyServer{t: t, lis: plis} - go p.run() - defer p.stop() - - blis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - - msg := []byte{4, 3, 5, 2} - recvBuf := make([]byte, len(msg)) - done := make(chan struct{}) - go func() { - in, err := blis.Accept() - if err != nil { - t.Errorf("failed to accept: %v", err) - return - } - defer in.Close() - in.Read(recvBuf) - close(done) - }() - - // Overwrite the function in the test and restore them in defer. - hpfe := func(req *http.Request) (*url.URL, error) { - return &url.URL{Host: plis.Addr().String()}, nil - } - defer overwrite(hpfe)() - - // Dial to proxy server. - dialer := newProxyDialer(func(ctx context.Context, addr string) (net.Conn, error) { - if deadline, ok := ctx.Deadline(); ok { - return net.DialTimeout("tcp", addr, deadline.Sub(time.Now())) - } - return net.Dial("tcp", addr) - }) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - c, err := dialer(ctx, blis.Addr().String()) - if err != nil { - t.Fatalf("http connect Dial failed: %v", err) - } - defer c.Close() - - // Send msg on the connection. - c.Write(msg) - <-done - - // Check received msg. - if string(recvBuf) != string(msg) { - t.Fatalf("received msg: %v, want %v", recvBuf, msg) - } -} - -func TestMapAddressEnv(t *testing.T) { - defer leakcheck.Check(t) - // Overwrite the function in the test and restore them in defer. - hpfe := func(req *http.Request) (*url.URL, error) { - if req.URL.Host == envTestAddr { - return &url.URL{ - Scheme: "https", - Host: envProxyAddr, - }, nil - } - return nil, nil - } - defer overwrite(hpfe)() - - // envTestAddr should be handled by ProxyFromEnvironment. - got, err := mapAddress(context.Background(), envTestAddr) - if err != nil { - t.Error(err) - } - if got != envProxyAddr { - t.Errorf("want %v, got %v", envProxyAddr, got) - } -} diff --git a/examples/google.golang.org/grpc/reflection/README.md b/examples/google.golang.org/grpc/reflection/README.md deleted file mode 100755 index 04b6371..0000000 --- a/examples/google.golang.org/grpc/reflection/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Reflection - -Package reflection implements server reflection service. - -The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: -```go -import "google.golang.org/grpc/reflection" - -s := grpc.NewServer() -pb.RegisterYourOwnServer(s, &server{}) - -// Register reflection service on gRPC server. -reflection.Register(s) - -s.Serve(lis) -``` diff --git a/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go b/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go deleted file mode 100755 index 4bc5404..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go +++ /dev/null @@ -1,925 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_reflection_v1alpha/reflection.proto - -package grpc_reflection_v1alpha - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The message sent by the client when calling ServerReflectionInfo method. -type ServerReflectionRequest struct { - Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - // - // Types that are valid to be assigned to MessageRequest: - // *ServerReflectionRequest_FileByFilename - // *ServerReflectionRequest_FileContainingSymbol - // *ServerReflectionRequest_FileContainingExtension - // *ServerReflectionRequest_AllExtensionNumbersOfType - // *ServerReflectionRequest_ListServices - MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerReflectionRequest) Reset() { *m = ServerReflectionRequest{} } -func (m *ServerReflectionRequest) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionRequest) ProtoMessage() {} -func (*ServerReflectionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{0} -} -func (m *ServerReflectionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerReflectionRequest.Unmarshal(m, b) -} -func (m *ServerReflectionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerReflectionRequest.Marshal(b, m, deterministic) -} -func (dst *ServerReflectionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerReflectionRequest.Merge(dst, src) -} -func (m *ServerReflectionRequest) XXX_Size() int { - return xxx_messageInfo_ServerReflectionRequest.Size(m) -} -func (m *ServerReflectionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ServerReflectionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerReflectionRequest proto.InternalMessageInfo - -type isServerReflectionRequest_MessageRequest interface { - isServerReflectionRequest_MessageRequest() -} - -type ServerReflectionRequest_FileByFilename struct { - FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,proto3,oneof"` -} -type ServerReflectionRequest_FileContainingSymbol struct { - FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,proto3,oneof"` -} -type ServerReflectionRequest_FileContainingExtension struct { - FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,proto3,oneof"` -} -type ServerReflectionRequest_AllExtensionNumbersOfType struct { - AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,proto3,oneof"` -} -type ServerReflectionRequest_ListServices struct { - ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,proto3,oneof"` -} - -func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() {} -func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {} - -func (m *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest { - if m != nil { - return m.MessageRequest - } - return nil -} - -func (m *ServerReflectionRequest) GetHost() string { - if m != nil { - return m.Host - } - return "" -} - -func (m *ServerReflectionRequest) GetFileByFilename() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileByFilename); ok { - return x.FileByFilename - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingSymbol() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingSymbol); ok { - return x.FileContainingSymbol - } - return "" -} - -func (m *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingExtension); ok { - return x.FileContainingExtension - } - return nil -} - -func (m *ServerReflectionRequest) GetAllExtensionNumbersOfType() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_AllExtensionNumbersOfType); ok { - return x.AllExtensionNumbersOfType - } - return "" -} - -func (m *ServerReflectionRequest) GetListServices() string { - if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_ListServices); ok { - return x.ListServices - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionRequest_OneofMarshaler, _ServerReflectionRequest_OneofUnmarshaler, _ServerReflectionRequest_OneofSizer, []interface{}{ - (*ServerReflectionRequest_FileByFilename)(nil), - (*ServerReflectionRequest_FileContainingSymbol)(nil), - (*ServerReflectionRequest_FileContainingExtension)(nil), - (*ServerReflectionRequest_AllExtensionNumbersOfType)(nil), - (*ServerReflectionRequest_ListServices)(nil), - } -} - -func _ServerReflectionRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - b.EncodeVarint(3<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileContainingExtension); err != nil { - return err - } - case *ServerReflectionRequest_AllExtensionNumbersOfType: - b.EncodeVarint(6<<3 | proto.WireBytes) - b.EncodeStringBytes(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - b.EncodeVarint(7<<3 | proto.WireBytes) - b.EncodeStringBytes(x.ListServices) - case nil: - default: - return fmt.Errorf("ServerReflectionRequest.MessageRequest has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionRequest) - switch tag { - case 3: // message_request.file_by_filename - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileByFilename{x} - return true, err - case 4: // message_request.file_containing_symbol - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_FileContainingSymbol{x} - return true, err - case 5: // message_request.file_containing_extension - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionRequest) - err := b.DecodeMessage(msg) - m.MessageRequest = &ServerReflectionRequest_FileContainingExtension{msg} - return true, err - case 6: // message_request.all_extension_numbers_of_type - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_AllExtensionNumbersOfType{x} - return true, err - case 7: // message_request.list_services - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.MessageRequest = &ServerReflectionRequest_ListServices{x} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionRequest_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionRequest) - // message_request - switch x := m.MessageRequest.(type) { - case *ServerReflectionRequest_FileByFilename: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.FileByFilename))) - n += len(x.FileByFilename) - case *ServerReflectionRequest_FileContainingSymbol: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.FileContainingSymbol))) - n += len(x.FileContainingSymbol) - case *ServerReflectionRequest_FileContainingExtension: - s := proto.Size(x.FileContainingExtension) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionRequest_AllExtensionNumbersOfType: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.AllExtensionNumbersOfType))) - n += len(x.AllExtensionNumbersOfType) - case *ServerReflectionRequest_ListServices: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.ListServices))) - n += len(x.ListServices) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -type ExtensionRequest struct { - // Fully-qualified type name. The format should be . - ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType,proto3" json:"containing_type,omitempty"` - ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRequest) Reset() { *m = ExtensionRequest{} } -func (m *ExtensionRequest) String() string { return proto.CompactTextString(m) } -func (*ExtensionRequest) ProtoMessage() {} -func (*ExtensionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{1} -} -func (m *ExtensionRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRequest.Unmarshal(m, b) -} -func (m *ExtensionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRequest.Marshal(b, m, deterministic) -} -func (dst *ExtensionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRequest.Merge(dst, src) -} -func (m *ExtensionRequest) XXX_Size() int { - return xxx_messageInfo_ExtensionRequest.Size(m) -} -func (m *ExtensionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRequest proto.InternalMessageInfo - -func (m *ExtensionRequest) GetContainingType() string { - if m != nil { - return m.ContainingType - } - return "" -} - -func (m *ExtensionRequest) GetExtensionNumber() int32 { - if m != nil { - return m.ExtensionNumber - } - return 0 -} - -// The message sent by the server to answer ServerReflectionInfo method. -type ServerReflectionResponse struct { - ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost,proto3" json:"valid_host,omitempty"` - OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest,proto3" json:"original_request,omitempty"` - // The server sets one of the following fields according to the - // message_request in the request. - // - // Types that are valid to be assigned to MessageResponse: - // *ServerReflectionResponse_FileDescriptorResponse - // *ServerReflectionResponse_AllExtensionNumbersResponse - // *ServerReflectionResponse_ListServicesResponse - // *ServerReflectionResponse_ErrorResponse - MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServerReflectionResponse) Reset() { *m = ServerReflectionResponse{} } -func (m *ServerReflectionResponse) String() string { return proto.CompactTextString(m) } -func (*ServerReflectionResponse) ProtoMessage() {} -func (*ServerReflectionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{2} -} -func (m *ServerReflectionResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServerReflectionResponse.Unmarshal(m, b) -} -func (m *ServerReflectionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServerReflectionResponse.Marshal(b, m, deterministic) -} -func (dst *ServerReflectionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerReflectionResponse.Merge(dst, src) -} -func (m *ServerReflectionResponse) XXX_Size() int { - return xxx_messageInfo_ServerReflectionResponse.Size(m) -} -func (m *ServerReflectionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ServerReflectionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ServerReflectionResponse proto.InternalMessageInfo - -type isServerReflectionResponse_MessageResponse interface { - isServerReflectionResponse_MessageResponse() -} - -type ServerReflectionResponse_FileDescriptorResponse struct { - FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,proto3,oneof"` -} -type ServerReflectionResponse_AllExtensionNumbersResponse struct { - AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,proto3,oneof"` -} -type ServerReflectionResponse_ListServicesResponse struct { - ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,proto3,oneof"` -} -type ServerReflectionResponse_ErrorResponse struct { - ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,proto3,oneof"` -} - -func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() { -} -func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {} -func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {} - -func (m *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse { - if m != nil { - return m.MessageResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetValidHost() string { - if m != nil { - return m.ValidHost - } - return "" -} - -func (m *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest { - if m != nil { - return m.OriginalRequest - } - return nil -} - -func (m *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_FileDescriptorResponse); ok { - return x.FileDescriptorResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_AllExtensionNumbersResponse); ok { - return x.AllExtensionNumbersResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ListServicesResponse); ok { - return x.ListServicesResponse - } - return nil -} - -func (m *ServerReflectionResponse) GetErrorResponse() *ErrorResponse { - if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ErrorResponse); ok { - return x.ErrorResponse - } - return nil -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*ServerReflectionResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _ServerReflectionResponse_OneofMarshaler, _ServerReflectionResponse_OneofUnmarshaler, _ServerReflectionResponse_OneofSizer, []interface{}{ - (*ServerReflectionResponse_FileDescriptorResponse)(nil), - (*ServerReflectionResponse_AllExtensionNumbersResponse)(nil), - (*ServerReflectionResponse_ListServicesResponse)(nil), - (*ServerReflectionResponse_ErrorResponse)(nil), - } -} - -func _ServerReflectionResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - b.EncodeVarint(4<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.FileDescriptorResponse); err != nil { - return err - } - case *ServerReflectionResponse_AllExtensionNumbersResponse: - b.EncodeVarint(5<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.AllExtensionNumbersResponse); err != nil { - return err - } - case *ServerReflectionResponse_ListServicesResponse: - b.EncodeVarint(6<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ListServicesResponse); err != nil { - return err - } - case *ServerReflectionResponse_ErrorResponse: - b.EncodeVarint(7<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ErrorResponse); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("ServerReflectionResponse.MessageResponse has unexpected type %T", x) - } - return nil -} - -func _ServerReflectionResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*ServerReflectionResponse) - switch tag { - case 4: // message_response.file_descriptor_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(FileDescriptorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_FileDescriptorResponse{msg} - return true, err - case 5: // message_response.all_extension_numbers_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ExtensionNumberResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_AllExtensionNumbersResponse{msg} - return true, err - case 6: // message_response.list_services_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ListServiceResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ListServicesResponse{msg} - return true, err - case 7: // message_response.error_response - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ErrorResponse) - err := b.DecodeMessage(msg) - m.MessageResponse = &ServerReflectionResponse_ErrorResponse{msg} - return true, err - default: - return false, nil - } -} - -func _ServerReflectionResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*ServerReflectionResponse) - // message_response - switch x := m.MessageResponse.(type) { - case *ServerReflectionResponse_FileDescriptorResponse: - s := proto.Size(x.FileDescriptorResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_AllExtensionNumbersResponse: - s := proto.Size(x.AllExtensionNumbersResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ListServicesResponse: - s := proto.Size(x.ListServicesResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *ServerReflectionResponse_ErrorResponse: - s := proto.Size(x.ErrorResponse) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -type FileDescriptorResponse struct { - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorResponse) Reset() { *m = FileDescriptorResponse{} } -func (m *FileDescriptorResponse) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorResponse) ProtoMessage() {} -func (*FileDescriptorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{3} -} -func (m *FileDescriptorResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorResponse.Unmarshal(m, b) -} -func (m *FileDescriptorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorResponse.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorResponse.Merge(dst, src) -} -func (m *FileDescriptorResponse) XXX_Size() int { - return xxx_messageInfo_FileDescriptorResponse.Size(m) -} -func (m *FileDescriptorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorResponse proto.InternalMessageInfo - -func (m *FileDescriptorResponse) GetFileDescriptorProto() [][]byte { - if m != nil { - return m.FileDescriptorProto - } - return nil -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -type ExtensionNumberResponse struct { - // Full name of the base type, including the package name. The format - // is . - BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName,proto3" json:"base_type_name,omitempty"` - ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionNumberResponse) Reset() { *m = ExtensionNumberResponse{} } -func (m *ExtensionNumberResponse) String() string { return proto.CompactTextString(m) } -func (*ExtensionNumberResponse) ProtoMessage() {} -func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{4} -} -func (m *ExtensionNumberResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionNumberResponse.Unmarshal(m, b) -} -func (m *ExtensionNumberResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionNumberResponse.Marshal(b, m, deterministic) -} -func (dst *ExtensionNumberResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionNumberResponse.Merge(dst, src) -} -func (m *ExtensionNumberResponse) XXX_Size() int { - return xxx_messageInfo_ExtensionNumberResponse.Size(m) -} -func (m *ExtensionNumberResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionNumberResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionNumberResponse proto.InternalMessageInfo - -func (m *ExtensionNumberResponse) GetBaseTypeName() string { - if m != nil { - return m.BaseTypeName - } - return "" -} - -func (m *ExtensionNumberResponse) GetExtensionNumber() []int32 { - if m != nil { - return m.ExtensionNumber - } - return nil -} - -// A list of ServiceResponse sent by the server answering list_services request. -type ListServiceResponse struct { - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service,proto3" json:"service,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ListServiceResponse) Reset() { *m = ListServiceResponse{} } -func (m *ListServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ListServiceResponse) ProtoMessage() {} -func (*ListServiceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{5} -} -func (m *ListServiceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ListServiceResponse.Unmarshal(m, b) -} -func (m *ListServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ListServiceResponse.Marshal(b, m, deterministic) -} -func (dst *ListServiceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListServiceResponse.Merge(dst, src) -} -func (m *ListServiceResponse) XXX_Size() int { - return xxx_messageInfo_ListServiceResponse.Size(m) -} -func (m *ListServiceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ListServiceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ListServiceResponse proto.InternalMessageInfo - -func (m *ListServiceResponse) GetService() []*ServiceResponse { - if m != nil { - return m.Service - } - return nil -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -type ServiceResponse struct { - // Full name of a registered service, including its package name. The format - // is . - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceResponse) Reset() { *m = ServiceResponse{} } -func (m *ServiceResponse) String() string { return proto.CompactTextString(m) } -func (*ServiceResponse) ProtoMessage() {} -func (*ServiceResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{6} -} -func (m *ServiceResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceResponse.Unmarshal(m, b) -} -func (m *ServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceResponse.Marshal(b, m, deterministic) -} -func (dst *ServiceResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceResponse.Merge(dst, src) -} -func (m *ServiceResponse) XXX_Size() int { - return xxx_messageInfo_ServiceResponse.Size(m) -} -func (m *ServiceResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceResponse proto.InternalMessageInfo - -func (m *ServiceResponse) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -// The error code and error message sent by the server when an error occurs. -type ErrorResponse struct { - // This field uses the error codes defined in grpc::StatusCode. - ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"` - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ErrorResponse) Reset() { *m = ErrorResponse{} } -func (m *ErrorResponse) String() string { return proto.CompactTextString(m) } -func (*ErrorResponse) ProtoMessage() {} -func (*ErrorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_reflection_178bd1e101bf8b63, []int{7} -} -func (m *ErrorResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ErrorResponse.Unmarshal(m, b) -} -func (m *ErrorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ErrorResponse.Marshal(b, m, deterministic) -} -func (dst *ErrorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_ErrorResponse.Merge(dst, src) -} -func (m *ErrorResponse) XXX_Size() int { - return xxx_messageInfo_ErrorResponse.Size(m) -} -func (m *ErrorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_ErrorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_ErrorResponse proto.InternalMessageInfo - -func (m *ErrorResponse) GetErrorCode() int32 { - if m != nil { - return m.ErrorCode - } - return 0 -} - -func (m *ErrorResponse) GetErrorMessage() string { - if m != nil { - return m.ErrorMessage - } - return "" -} - -func init() { - proto.RegisterType((*ServerReflectionRequest)(nil), "grpc.reflection.v1alpha.ServerReflectionRequest") - proto.RegisterType((*ExtensionRequest)(nil), "grpc.reflection.v1alpha.ExtensionRequest") - proto.RegisterType((*ServerReflectionResponse)(nil), "grpc.reflection.v1alpha.ServerReflectionResponse") - proto.RegisterType((*FileDescriptorResponse)(nil), "grpc.reflection.v1alpha.FileDescriptorResponse") - proto.RegisterType((*ExtensionNumberResponse)(nil), "grpc.reflection.v1alpha.ExtensionNumberResponse") - proto.RegisterType((*ListServiceResponse)(nil), "grpc.reflection.v1alpha.ListServiceResponse") - proto.RegisterType((*ServiceResponse)(nil), "grpc.reflection.v1alpha.ServiceResponse") - proto.RegisterType((*ErrorResponse)(nil), "grpc.reflection.v1alpha.ErrorResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// ServerReflectionClient is the client API for ServerReflection service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type ServerReflectionClient interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) -} - -type serverReflectionClient struct { - cc *grpc.ClientConn -} - -func NewServerReflectionClient(cc *grpc.ClientConn) ServerReflectionClient { - return &serverReflectionClient{cc} -} - -func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { - stream, err := c.cc.NewStream(ctx, &_ServerReflection_serviceDesc.Streams[0], "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) - if err != nil { - return nil, err - } - x := &serverReflectionServerReflectionInfoClient{stream} - return x, nil -} - -type ServerReflection_ServerReflectionInfoClient interface { - Send(*ServerReflectionRequest) error - Recv() (*ServerReflectionResponse, error) - grpc.ClientStream -} - -type serverReflectionServerReflectionInfoClient struct { - grpc.ClientStream -} - -func (x *serverReflectionServerReflectionInfoClient) Send(m *ServerReflectionRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionResponse, error) { - m := new(ServerReflectionResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// ServerReflectionServer is the server API for ServerReflection service. -type ServerReflectionServer interface { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error -} - -func RegisterServerReflectionServer(s *grpc.Server, srv ServerReflectionServer) { - s.RegisterService(&_ServerReflection_serviceDesc, srv) -} - -func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) -} - -type ServerReflection_ServerReflectionInfoServer interface { - Send(*ServerReflectionResponse) error - Recv() (*ServerReflectionRequest, error) - grpc.ServerStream -} - -type serverReflectionServerReflectionInfoServer struct { - grpc.ServerStream -} - -func (x *serverReflectionServerReflectionInfoServer) Send(m *ServerReflectionResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRequest, error) { - m := new(ServerReflectionRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _ServerReflection_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.reflection.v1alpha.ServerReflection", - HandlerType: (*ServerReflectionServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{ - { - StreamName: "ServerReflectionInfo", - Handler: _ServerReflection_ServerReflectionInfo_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_reflection_v1alpha/reflection.proto", -} - -func init() { - proto.RegisterFile("grpc_reflection_v1alpha/reflection.proto", fileDescriptor_reflection_178bd1e101bf8b63) -} - -var fileDescriptor_reflection_178bd1e101bf8b63 = []byte{ - // 656 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x51, 0x73, 0xd2, 0x40, - 0x10, 0x6e, 0x5a, 0x68, 0x87, 0x85, 0x02, 0x5e, 0x2b, 0xa4, 0x3a, 0x75, 0x98, 0x68, 0x35, 0x75, - 0x1c, 0xda, 0xe2, 0x8c, 0x3f, 0x80, 0xaa, 0x83, 0x33, 0xb5, 0x75, 0x0e, 0x5f, 0x1c, 0x1f, 0x6e, - 0x02, 0x2c, 0x34, 0x1a, 0x72, 0xf1, 0x2e, 0x45, 0x79, 0xf2, 0x47, 0xf8, 0xa3, 0xfc, 0x4b, 0x3e, - 0x3a, 0x77, 0x09, 0x21, 0xa4, 0x44, 0xa7, 0x4f, 0x30, 0xdf, 0xee, 0xde, 0xb7, 0xbb, 0xdf, 0xb7, - 0x01, 0x7b, 0x22, 0x82, 0x21, 0x13, 0x38, 0xf6, 0x70, 0x18, 0xba, 0xdc, 0x67, 0xb3, 0x33, 0xc7, - 0x0b, 0xae, 0x9d, 0x93, 0x25, 0xd4, 0x0e, 0x04, 0x0f, 0x39, 0x69, 0xaa, 0xcc, 0x76, 0x0a, 0x8e, - 0x33, 0xad, 0x3f, 0x9b, 0xd0, 0xec, 0xa3, 0x98, 0xa1, 0xa0, 0x49, 0x90, 0xe2, 0xb7, 0x1b, 0x94, - 0x21, 0x21, 0x50, 0xb8, 0xe6, 0x32, 0x34, 0x8d, 0x96, 0x61, 0x97, 0xa8, 0xfe, 0x4f, 0x9e, 0x43, - 0x7d, 0xec, 0x7a, 0xc8, 0x06, 0x73, 0xa6, 0x7e, 0x7d, 0x67, 0x8a, 0xe6, 0x96, 0x8a, 0xf7, 0x36, - 0x68, 0x55, 0x21, 0xdd, 0xf9, 0xdb, 0x18, 0x27, 0xaf, 0xa0, 0xa1, 0x73, 0x87, 0xdc, 0x0f, 0x1d, - 0xd7, 0x77, 0xfd, 0x09, 0x93, 0xf3, 0xe9, 0x80, 0x7b, 0x66, 0x21, 0xae, 0xd8, 0x57, 0xf1, 0xf3, - 0x24, 0xdc, 0xd7, 0x51, 0x32, 0x81, 0x83, 0x6c, 0x1d, 0xfe, 0x08, 0xd1, 0x97, 0x2e, 0xf7, 0xcd, - 0x62, 0xcb, 0xb0, 0xcb, 0x9d, 0xe3, 0x76, 0xce, 0x40, 0xed, 0x37, 0x8b, 0xcc, 0x78, 0x8a, 0xde, - 0x06, 0x6d, 0xae, 0xb2, 0x24, 0x19, 0xa4, 0x0b, 0x87, 0x8e, 0xe7, 0x2d, 0x1f, 0x67, 0xfe, 0xcd, - 0x74, 0x80, 0x42, 0x32, 0x3e, 0x66, 0xe1, 0x3c, 0x40, 0x73, 0x3b, 0xee, 0xf3, 0xc0, 0xf1, 0xbc, - 0xa4, 0xec, 0x32, 0x4a, 0xba, 0x1a, 0x7f, 0x9c, 0x07, 0x48, 0x8e, 0x60, 0xd7, 0x73, 0x65, 0xc8, - 0x24, 0x8a, 0x99, 0x3b, 0x44, 0x69, 0xee, 0xc4, 0x35, 0x15, 0x05, 0xf7, 0x63, 0xb4, 0x7b, 0x0f, - 0x6a, 0x53, 0x94, 0xd2, 0x99, 0x20, 0x13, 0x51, 0x63, 0xd6, 0x18, 0xea, 0xd9, 0x66, 0xc9, 0x33, - 0xa8, 0xa5, 0xa6, 0xd6, 0x3d, 0x44, 0xdb, 0xaf, 0x2e, 0x61, 0x4d, 0x7b, 0x0c, 0xf5, 0x6c, 0xdb, - 0xe6, 0x66, 0xcb, 0xb0, 0x8b, 0xb4, 0x86, 0xab, 0x8d, 0x5a, 0xbf, 0x0b, 0x60, 0xde, 0x96, 0x58, - 0x06, 0xdc, 0x97, 0x48, 0x0e, 0x01, 0x66, 0x8e, 0xe7, 0x8e, 0x58, 0x4a, 0xe9, 0x92, 0x46, 0x7a, - 0x4a, 0xee, 0xcf, 0x50, 0xe7, 0xc2, 0x9d, 0xb8, 0xbe, 0xe3, 0x2d, 0xfa, 0xd6, 0x34, 0xe5, 0xce, - 0x69, 0xae, 0x02, 0x39, 0x76, 0xa2, 0xb5, 0xc5, 0x4b, 0x8b, 0x61, 0xbf, 0x82, 0xa9, 0x75, 0x1e, - 0xa1, 0x1c, 0x0a, 0x37, 0x08, 0xb9, 0x60, 0x22, 0xee, 0x4b, 0x3b, 0xa4, 0xdc, 0x39, 0xc9, 0x25, - 0x51, 0x26, 0x7b, 0x9d, 0xd4, 0x2d, 0xc6, 0xe9, 0x6d, 0x50, 0x6d, 0xb9, 0xdb, 0x11, 0xf2, 0x1d, - 0x1e, 0xad, 0xd7, 0x3a, 0xa1, 0x2c, 0xfe, 0x67, 0xae, 0x8c, 0x01, 0x52, 0x9c, 0x0f, 0xd7, 0xd8, - 0x23, 0x21, 0x1e, 0x41, 0x63, 0xc5, 0x20, 0x4b, 0xc2, 0x6d, 0x4d, 0xf8, 0x22, 0x97, 0xf0, 0x62, - 0x69, 0xa0, 0x14, 0xd9, 0x7e, 0xda, 0x57, 0x09, 0xcb, 0x15, 0x54, 0x51, 0x88, 0xf4, 0x06, 0x77, - 0xf4, 0xeb, 0x4f, 0xf3, 0xc7, 0x51, 0xe9, 0xa9, 0x77, 0x77, 0x31, 0x0d, 0x74, 0x09, 0xd4, 0x97, - 0x86, 0x8d, 0x30, 0xeb, 0x02, 0x1a, 0xeb, 0xf7, 0x4e, 0x3a, 0x70, 0x3f, 0x2b, 0xa5, 0xfe, 0xf0, - 0x98, 0x46, 0x6b, 0xcb, 0xae, 0xd0, 0xbd, 0x55, 0x51, 0x3e, 0xa8, 0x90, 0xf5, 0x05, 0x9a, 0x39, - 0x2b, 0x25, 0x4f, 0xa0, 0x3a, 0x70, 0x24, 0xea, 0x03, 0x60, 0xfa, 0x1b, 0x13, 0x39, 0xb3, 0xa2, - 0x50, 0xe5, 0xff, 0x4b, 0xf5, 0x7d, 0x59, 0x7f, 0x03, 0x5b, 0xeb, 0x6e, 0xe0, 0x13, 0xec, 0xad, - 0xd9, 0x26, 0xe9, 0xc2, 0x4e, 0x2c, 0x8b, 0x6e, 0xb4, 0xdc, 0xb1, 0xff, 0xe9, 0xea, 0x54, 0x29, - 0x5d, 0x14, 0x5a, 0x47, 0x50, 0xcb, 0x3e, 0x4b, 0xa0, 0x90, 0x6a, 0x5a, 0xff, 0xb7, 0xfa, 0xb0, - 0xbb, 0xb2, 0x71, 0x75, 0x79, 0x91, 0x62, 0x43, 0x3e, 0x8a, 0x52, 0x8b, 0xb4, 0xa4, 0x91, 0x73, - 0x3e, 0x42, 0xf2, 0x18, 0x22, 0x41, 0x58, 0xac, 0x82, 0x3e, 0xbb, 0x12, 0xad, 0x68, 0xf0, 0x7d, - 0x84, 0x75, 0x7e, 0x19, 0x50, 0xcf, 0x9e, 0x1b, 0xf9, 0x09, 0xfb, 0x59, 0xec, 0x9d, 0x3f, 0xe6, - 0xe4, 0xce, 0x17, 0xfb, 0xe0, 0xec, 0x0e, 0x15, 0xd1, 0x54, 0xb6, 0x71, 0x6a, 0x0c, 0xb6, 0xb5, - 0xf4, 0x2f, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x85, 0x02, 0x09, 0x9d, 0x9f, 0x06, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto b/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto deleted file mode 100755 index 99b00df..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto +++ /dev/null @@ -1,136 +0,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. - -// Service exported by server reflection - -syntax = "proto3"; - -package grpc.reflection.v1alpha; - -service ServerReflection { - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - rpc ServerReflectionInfo(stream ServerReflectionRequest) - returns (stream ServerReflectionResponse); -} - -// The message sent by the client when calling ServerReflectionInfo method. -message ServerReflectionRequest { - string host = 1; - // To use reflection service, the client should set one of the following - // fields in message_request. The server distinguishes requests by their - // defined field and then handles them using corresponding methods. - oneof message_request { - // Find a proto file by the file name. - string file_by_filename = 3; - - // Find the proto file that declares the given fully-qualified symbol name. - // This field should be a fully-qualified symbol name - // (e.g. .[.] or .). - string file_containing_symbol = 4; - - // Find the proto file which defines an extension extending the given - // message type with the given field number. - ExtensionRequest file_containing_extension = 5; - - // Finds the tag numbers used by all known extensions of extendee_type, and - // appends them to ExtensionNumberResponse in an undefined order. - // Its corresponding method is best-effort: it's not guaranteed that the - // reflection service will implement this method, and it's not guaranteed - // that this method will provide all extensions. Returns - // StatusCode::UNIMPLEMENTED if it's not implemented. - // This field should be a fully-qualified type name. The format is - // . - string all_extension_numbers_of_type = 6; - - // List the full names of registered services. The content will not be - // checked. - string list_services = 7; - } -} - -// The type name and extension number sent by the client when requesting -// file_containing_extension. -message ExtensionRequest { - // Fully-qualified type name. The format should be . - string containing_type = 1; - int32 extension_number = 2; -} - -// The message sent by the server to answer ServerReflectionInfo method. -message ServerReflectionResponse { - string valid_host = 1; - ServerReflectionRequest original_request = 2; - // The server sets one of the following fields according to the - // message_request in the request. - oneof message_response { - // This message is used to answer file_by_filename, file_containing_symbol, - // file_containing_extension requests with transitive dependencies. - // As the repeated label is not allowed in oneof fields, we use a - // FileDescriptorResponse message to encapsulate the repeated fields. - // The reflection service is allowed to avoid sending FileDescriptorProtos - // that were previously sent in response to earlier requests in the stream. - FileDescriptorResponse file_descriptor_response = 4; - - // This message is used to answer all_extension_numbers_of_type requests. - ExtensionNumberResponse all_extension_numbers_response = 5; - - // This message is used to answer list_services requests. - ListServiceResponse list_services_response = 6; - - // This message is used when an error occurs. - ErrorResponse error_response = 7; - } -} - -// Serialized FileDescriptorProto messages sent by the server answering -// a file_by_filename, file_containing_symbol, or file_containing_extension -// request. -message FileDescriptorResponse { - // Serialized FileDescriptorProto messages. We avoid taking a dependency on - // descriptor.proto, which uses proto2 only features, by making them opaque - // bytes instead. - repeated bytes file_descriptor_proto = 1; -} - -// A list of extension numbers sent by the server answering -// all_extension_numbers_of_type request. -message ExtensionNumberResponse { - // Full name of the base type, including the package name. The format - // is . - string base_type_name = 1; - repeated int32 extension_number = 2; -} - -// A list of ServiceResponse sent by the server answering list_services request. -message ListServiceResponse { - // The information of each service may be expanded in the future, so we use - // ServiceResponse message to encapsulate it. - repeated ServiceResponse service = 1; -} - -// The information of a single service used by ListServiceResponse to answer -// list_services request. -message ServiceResponse { - // Full name of a registered service, including its package name. The format - // is . - string name = 1; -} - -// The error code and error message sent by the server when an error occurs. -message ErrorResponse { - // This field uses the error codes defined in grpc::StatusCode. - int32 error_code = 1; - string error_message = 2; -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go deleted file mode 100755 index 4a95d9b..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.pb.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type ToBeExtended struct { - Foo *int32 `protobuf:"varint,1,req,name=foo" json:"foo,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ToBeExtended) Reset() { *m = ToBeExtended{} } -func (m *ToBeExtended) String() string { return proto.CompactTextString(m) } -func (*ToBeExtended) ProtoMessage() {} -func (*ToBeExtended) Descriptor() ([]byte, []int) { - return fileDescriptor_proto2_b16f7a513d0acdc0, []int{0} -} - -var extRange_ToBeExtended = []proto.ExtensionRange{ - {Start: 10, End: 30}, -} - -func (*ToBeExtended) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ToBeExtended -} -func (m *ToBeExtended) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ToBeExtended.Unmarshal(m, b) -} -func (m *ToBeExtended) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ToBeExtended.Marshal(b, m, deterministic) -} -func (dst *ToBeExtended) XXX_Merge(src proto.Message) { - xxx_messageInfo_ToBeExtended.Merge(dst, src) -} -func (m *ToBeExtended) XXX_Size() int { - return xxx_messageInfo_ToBeExtended.Size(m) -} -func (m *ToBeExtended) XXX_DiscardUnknown() { - xxx_messageInfo_ToBeExtended.DiscardUnknown(m) -} - -var xxx_messageInfo_ToBeExtended proto.InternalMessageInfo - -func (m *ToBeExtended) GetFoo() int32 { - if m != nil && m.Foo != nil { - return *m.Foo - } - return 0 -} - -func init() { - proto.RegisterType((*ToBeExtended)(nil), "grpc.testing.ToBeExtended") -} - -func init() { proto.RegisterFile("proto2.proto", fileDescriptor_proto2_b16f7a513d0acdc0) } - -var fileDescriptor_proto2_b16f7a513d0acdc0 = []byte{ - // 86 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0xd2, 0x03, 0x53, 0x42, 0x3c, 0xe9, 0x45, 0x05, 0xc9, 0x7a, 0x25, 0xa9, 0xc5, 0x25, - 0x99, 0x79, 0xe9, 0x4a, 0x6a, 0x5c, 0x3c, 0x21, 0xf9, 0x4e, 0xa9, 0xae, 0x15, 0x25, 0xa9, 0x79, - 0x29, 0xa9, 0x29, 0x42, 0x02, 0x5c, 0xcc, 0x69, 0xf9, 0xf9, 0x12, 0x8c, 0x0a, 0x4c, 0x1a, 0xac, - 0x41, 0x20, 0xa6, 0x16, 0x0b, 0x07, 0x97, 0x80, 0x3c, 0x20, 0x00, 0x00, 0xff, 0xff, 0x74, 0x86, - 0x9c, 0x08, 0x44, 0x00, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.proto b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.proto deleted file mode 100755 index a675d14..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2.proto +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -message ToBeExtended { - required int32 foo = 1; - extensions 10 to 30; -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go deleted file mode 100755 index 25baa1a..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.pb.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2_ext.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Extension struct { - Whatzit *int32 `protobuf:"varint,1,opt,name=whatzit" json:"whatzit,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Extension) Reset() { *m = Extension{} } -func (m *Extension) String() string { return proto.CompactTextString(m) } -func (*Extension) ProtoMessage() {} -func (*Extension) Descriptor() ([]byte, []int) { - return fileDescriptor_proto2_ext_4437118420d604f2, []int{0} -} -func (m *Extension) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Extension.Unmarshal(m, b) -} -func (m *Extension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Extension.Marshal(b, m, deterministic) -} -func (dst *Extension) XXX_Merge(src proto.Message) { - xxx_messageInfo_Extension.Merge(dst, src) -} -func (m *Extension) XXX_Size() int { - return xxx_messageInfo_Extension.Size(m) -} -func (m *Extension) XXX_DiscardUnknown() { - xxx_messageInfo_Extension.DiscardUnknown(m) -} - -var xxx_messageInfo_Extension proto.InternalMessageInfo - -func (m *Extension) GetWhatzit() int32 { - if m != nil && m.Whatzit != nil { - return *m.Whatzit - } - return 0 -} - -var E_Foo = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*int32)(nil), - Field: 13, - Name: "grpc.testing.foo", - Tag: "varint,13,opt,name=foo", - Filename: "proto2_ext.proto", -} - -var E_Bar = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*Extension)(nil), - Field: 17, - Name: "grpc.testing.bar", - Tag: "bytes,17,opt,name=bar", - Filename: "proto2_ext.proto", -} - -var E_Baz = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*SearchRequest)(nil), - Field: 19, - Name: "grpc.testing.baz", - Tag: "bytes,19,opt,name=baz", - Filename: "proto2_ext.proto", -} - -func init() { - proto.RegisterType((*Extension)(nil), "grpc.testing.Extension") - proto.RegisterExtension(E_Foo) - proto.RegisterExtension(E_Bar) - proto.RegisterExtension(E_Baz) -} - -func init() { proto.RegisterFile("proto2_ext.proto", fileDescriptor_proto2_ext_4437118420d604f2) } - -var fileDescriptor_proto2_ext_4437118420d604f2 = []byte{ - // 179 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x28, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0x8a, 0x4f, 0xad, 0x28, 0xd1, 0x03, 0x33, 0x85, 0x78, 0xd2, 0x8b, 0x0a, 0x92, 0xf5, - 0x4a, 0x52, 0x8b, 0x4b, 0x32, 0xf3, 0xd2, 0xa5, 0x78, 0x20, 0xf2, 0x10, 0x39, 0x29, 0x2e, 0x90, - 0x30, 0x84, 0xad, 0xa4, 0xca, 0xc5, 0xe9, 0x5a, 0x51, 0x92, 0x9a, 0x57, 0x9c, 0x99, 0x9f, 0x27, - 0x24, 0xc1, 0xc5, 0x5e, 0x9e, 0x91, 0x58, 0x52, 0x95, 0x59, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, - 0x1a, 0x04, 0xe3, 0x5a, 0xe9, 0x70, 0x31, 0xa7, 0xe5, 0xe7, 0x0b, 0x49, 0xe9, 0x21, 0x1b, 0xab, - 0x17, 0x92, 0xef, 0x94, 0x0a, 0xd6, 0x9d, 0x92, 0x9a, 0x22, 0xc1, 0x0b, 0xd6, 0x01, 0x52, 0x66, - 0xe5, 0xca, 0xc5, 0x9c, 0x94, 0x58, 0x84, 0x57, 0xb5, 0xa0, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x38, - 0xaa, 0x0a, 0xb8, 0x4b, 0x82, 0x40, 0xfa, 0xad, 0x3c, 0x41, 0xc6, 0x54, 0xe1, 0x35, 0x46, 0x18, - 0x6c, 0x8c, 0x34, 0xaa, 0x8a, 0xe0, 0xd4, 0xc4, 0xa2, 0xe4, 0x8c, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, - 0xe2, 0x12, 0x90, 0x51, 0x55, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x71, 0x6b, 0x94, 0x9f, 0x21, - 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto deleted file mode 100755 index a4942e4..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext.proto +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -import "proto2.proto"; -import "test.proto"; - -extend ToBeExtended { - optional int32 foo = 13; - optional Extension bar = 17; - optional SearchRequest baz = 19; -} - -message Extension { - optional int32 whatzit = 1; -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go deleted file mode 100755 index 869a6ba..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.pb.go +++ /dev/null @@ -1,98 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: proto2_ext2.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type AnotherExtension struct { - Whatchamacallit *int32 `protobuf:"varint,1,opt,name=whatchamacallit" json:"whatchamacallit,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *AnotherExtension) Reset() { *m = AnotherExtension{} } -func (m *AnotherExtension) String() string { return proto.CompactTextString(m) } -func (*AnotherExtension) ProtoMessage() {} -func (*AnotherExtension) Descriptor() ([]byte, []int) { - return fileDescriptor_proto2_ext2_039d342873655470, []int{0} -} -func (m *AnotherExtension) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AnotherExtension.Unmarshal(m, b) -} -func (m *AnotherExtension) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AnotherExtension.Marshal(b, m, deterministic) -} -func (dst *AnotherExtension) XXX_Merge(src proto.Message) { - xxx_messageInfo_AnotherExtension.Merge(dst, src) -} -func (m *AnotherExtension) XXX_Size() int { - return xxx_messageInfo_AnotherExtension.Size(m) -} -func (m *AnotherExtension) XXX_DiscardUnknown() { - xxx_messageInfo_AnotherExtension.DiscardUnknown(m) -} - -var xxx_messageInfo_AnotherExtension proto.InternalMessageInfo - -func (m *AnotherExtension) GetWhatchamacallit() int32 { - if m != nil && m.Whatchamacallit != nil { - return *m.Whatchamacallit - } - return 0 -} - -var E_Frob = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*string)(nil), - Field: 23, - Name: "grpc.testing.frob", - Tag: "bytes,23,opt,name=frob", - Filename: "proto2_ext2.proto", -} - -var E_Nitz = &proto.ExtensionDesc{ - ExtendedType: (*ToBeExtended)(nil), - ExtensionType: (*AnotherExtension)(nil), - Field: 29, - Name: "grpc.testing.nitz", - Tag: "bytes,29,opt,name=nitz", - Filename: "proto2_ext2.proto", -} - -func init() { - proto.RegisterType((*AnotherExtension)(nil), "grpc.testing.AnotherExtension") - proto.RegisterExtension(E_Frob) - proto.RegisterExtension(E_Nitz) -} - -func init() { proto.RegisterFile("proto2_ext2.proto", fileDescriptor_proto2_ext2_039d342873655470) } - -var fileDescriptor_proto2_ext2_039d342873655470 = []byte{ - // 165 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2c, 0x28, 0xca, 0x2f, - 0xc9, 0x37, 0x8a, 0x4f, 0xad, 0x28, 0x31, 0xd2, 0x03, 0xb3, 0x85, 0x78, 0xd2, 0x8b, 0x0a, 0x92, - 0xf5, 0x4a, 0x52, 0x8b, 0x4b, 0x32, 0xf3, 0xd2, 0xa5, 0x78, 0x20, 0x0a, 0x20, 0x72, 0x4a, 0x36, - 0x5c, 0x02, 0x8e, 0x79, 0xf9, 0x25, 0x19, 0xa9, 0x45, 0xae, 0x15, 0x25, 0xa9, 0x79, 0xc5, 0x99, - 0xf9, 0x79, 0x42, 0x1a, 0x5c, 0xfc, 0xe5, 0x19, 0x89, 0x25, 0xc9, 0x19, 0x89, 0xb9, 0x89, 0xc9, - 0x89, 0x39, 0x39, 0x99, 0x25, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0xe8, 0xc2, 0x56, 0x7a, - 0x5c, 0x2c, 0x69, 0x45, 0xf9, 0x49, 0x42, 0x52, 0x7a, 0xc8, 0x56, 0xe8, 0x85, 0xe4, 0x3b, 0xa5, - 0x82, 0x8d, 0x4b, 0x49, 0x4d, 0x91, 0x10, 0x57, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xab, 0xb3, 0xf2, - 0xe3, 0x62, 0xc9, 0xcb, 0x2c, 0xa9, 0xc2, 0xab, 0x5e, 0x56, 0x81, 0x51, 0x83, 0xdb, 0x48, 0x0e, - 0x55, 0x05, 0xba, 0x1b, 0x83, 0xc0, 0xe6, 0x00, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf0, 0x7e, 0x0d, - 0x26, 0xed, 0x00, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto b/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto deleted file mode 100755 index d91ba00..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/proto2_ext2.proto +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto2"; - -package grpc.testing; - -import "proto2.proto"; - -extend ToBeExtended { - optional string frob = 23; - optional AnotherExtension nitz = 29; -} - -message AnotherExtension { - optional int32 whatchamacallit = 1; -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/test.pb.go b/examples/google.golang.org/grpc/reflection/grpc_testing/test.pb.go deleted file mode 100755 index 2566a49..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/test.pb.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: test.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SearchResponse struct { - Results []*SearchResponse_Result `protobuf:"bytes,1,rep,name=results,proto3" json:"results,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SearchResponse) Reset() { *m = SearchResponse{} } -func (m *SearchResponse) String() string { return proto.CompactTextString(m) } -func (*SearchResponse) ProtoMessage() {} -func (*SearchResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_a0c753075da50dd4, []int{0} -} -func (m *SearchResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SearchResponse.Unmarshal(m, b) -} -func (m *SearchResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SearchResponse.Marshal(b, m, deterministic) -} -func (dst *SearchResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SearchResponse.Merge(dst, src) -} -func (m *SearchResponse) XXX_Size() int { - return xxx_messageInfo_SearchResponse.Size(m) -} -func (m *SearchResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SearchResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SearchResponse proto.InternalMessageInfo - -func (m *SearchResponse) GetResults() []*SearchResponse_Result { - if m != nil { - return m.Results - } - return nil -} - -type SearchResponse_Result struct { - Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"` - Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` - Snippets []string `protobuf:"bytes,3,rep,name=snippets,proto3" json:"snippets,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SearchResponse_Result) Reset() { *m = SearchResponse_Result{} } -func (m *SearchResponse_Result) String() string { return proto.CompactTextString(m) } -func (*SearchResponse_Result) ProtoMessage() {} -func (*SearchResponse_Result) Descriptor() ([]byte, []int) { - return fileDescriptor_test_a0c753075da50dd4, []int{0, 0} -} -func (m *SearchResponse_Result) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SearchResponse_Result.Unmarshal(m, b) -} -func (m *SearchResponse_Result) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SearchResponse_Result.Marshal(b, m, deterministic) -} -func (dst *SearchResponse_Result) XXX_Merge(src proto.Message) { - xxx_messageInfo_SearchResponse_Result.Merge(dst, src) -} -func (m *SearchResponse_Result) XXX_Size() int { - return xxx_messageInfo_SearchResponse_Result.Size(m) -} -func (m *SearchResponse_Result) XXX_DiscardUnknown() { - xxx_messageInfo_SearchResponse_Result.DiscardUnknown(m) -} - -var xxx_messageInfo_SearchResponse_Result proto.InternalMessageInfo - -func (m *SearchResponse_Result) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -func (m *SearchResponse_Result) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *SearchResponse_Result) GetSnippets() []string { - if m != nil { - return m.Snippets - } - return nil -} - -type SearchRequest struct { - Query string `protobuf:"bytes,1,opt,name=query,proto3" json:"query,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SearchRequest) Reset() { *m = SearchRequest{} } -func (m *SearchRequest) String() string { return proto.CompactTextString(m) } -func (*SearchRequest) ProtoMessage() {} -func (*SearchRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_a0c753075da50dd4, []int{1} -} -func (m *SearchRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SearchRequest.Unmarshal(m, b) -} -func (m *SearchRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SearchRequest.Marshal(b, m, deterministic) -} -func (dst *SearchRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SearchRequest.Merge(dst, src) -} -func (m *SearchRequest) XXX_Size() int { - return xxx_messageInfo_SearchRequest.Size(m) -} -func (m *SearchRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SearchRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SearchRequest proto.InternalMessageInfo - -func (m *SearchRequest) GetQuery() string { - if m != nil { - return m.Query - } - return "" -} - -func init() { - proto.RegisterType((*SearchResponse)(nil), "grpc.testing.SearchResponse") - proto.RegisterType((*SearchResponse_Result)(nil), "grpc.testing.SearchResponse.Result") - proto.RegisterType((*SearchRequest)(nil), "grpc.testing.SearchRequest") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// SearchServiceClient is the client API for SearchService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type SearchServiceClient interface { - Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) - StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) -} - -type searchServiceClient struct { - cc *grpc.ClientConn -} - -func NewSearchServiceClient(cc *grpc.ClientConn) SearchServiceClient { - return &searchServiceClient{cc} -} - -func (c *searchServiceClient) Search(ctx context.Context, in *SearchRequest, opts ...grpc.CallOption) (*SearchResponse, error) { - out := new(SearchResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.SearchService/Search", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *searchServiceClient) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchService_StreamingSearchClient, error) { - stream, err := c.cc.NewStream(ctx, &_SearchService_serviceDesc.Streams[0], "/grpc.testing.SearchService/StreamingSearch", opts...) - if err != nil { - return nil, err - } - x := &searchServiceStreamingSearchClient{stream} - return x, nil -} - -type SearchService_StreamingSearchClient interface { - Send(*SearchRequest) error - Recv() (*SearchResponse, error) - grpc.ClientStream -} - -type searchServiceStreamingSearchClient struct { - grpc.ClientStream -} - -func (x *searchServiceStreamingSearchClient) Send(m *SearchRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *searchServiceStreamingSearchClient) Recv() (*SearchResponse, error) { - m := new(SearchResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// SearchServiceServer is the server API for SearchService service. -type SearchServiceServer interface { - Search(context.Context, *SearchRequest) (*SearchResponse, error) - StreamingSearch(SearchService_StreamingSearchServer) error -} - -func RegisterSearchServiceServer(s *grpc.Server, srv SearchServiceServer) { - s.RegisterService(&_SearchService_serviceDesc, srv) -} - -func _SearchService_Search_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SearchRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SearchServiceServer).Search(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.SearchService/Search", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SearchServiceServer).Search(ctx, req.(*SearchRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _SearchService_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(SearchServiceServer).StreamingSearch(&searchServiceStreamingSearchServer{stream}) -} - -type SearchService_StreamingSearchServer interface { - Send(*SearchResponse) error - Recv() (*SearchRequest, error) - grpc.ServerStream -} - -type searchServiceStreamingSearchServer struct { - grpc.ServerStream -} - -func (x *searchServiceStreamingSearchServer) Send(m *SearchResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *searchServiceStreamingSearchServer) Recv() (*SearchRequest, error) { - m := new(SearchRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _SearchService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.SearchService", - HandlerType: (*SearchServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Search", - Handler: _SearchService_Search_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingSearch", - Handler: _SearchService_StreamingSearch_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "test.proto", -} - -func init() { proto.RegisterFile("test.proto", fileDescriptor_test_a0c753075da50dd4) } - -var fileDescriptor_test_a0c753075da50dd4 = []byte{ - // 231 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x91, 0xbd, 0x4a, 0xc5, 0x40, - 0x10, 0x85, 0x59, 0x83, 0xd1, 0x3b, 0xfe, 0x32, 0x58, 0x84, 0x68, 0x11, 0xae, 0x08, 0xa9, 0x16, - 0xb9, 0xd6, 0x56, 0xb6, 0x16, 0xb2, 0x79, 0x82, 0x6b, 0x18, 0xe2, 0x42, 0x4c, 0x36, 0x33, 0x13, - 0xc1, 0x87, 0xb1, 0xf5, 0x39, 0x25, 0x59, 0x23, 0x0a, 0x62, 0x63, 0xb7, 0xe7, 0xe3, 0xcc, 0xb7, - 0xbb, 0x0c, 0x80, 0x92, 0xa8, 0x0d, 0xdc, 0x6b, 0x8f, 0x87, 0x0d, 0x87, 0xda, 0x4e, 0xc0, 0x77, - 0xcd, 0xfa, 0xcd, 0xc0, 0x71, 0x45, 0x5b, 0xae, 0x9f, 0x1c, 0x49, 0xe8, 0x3b, 0x21, 0xbc, 0x85, - 0x3d, 0x26, 0x19, 0x5b, 0x95, 0xcc, 0x14, 0x49, 0x79, 0xb0, 0xb9, 0xb4, 0xdf, 0x47, 0xec, 0xcf, - 0xba, 0x75, 0x73, 0xd7, 0x2d, 0x33, 0xf9, 0x3d, 0xa4, 0x11, 0xe1, 0x29, 0x24, 0x23, 0xb7, 0x99, - 0x29, 0x4c, 0xb9, 0x72, 0xd3, 0x11, 0xcf, 0x60, 0x57, 0xbd, 0xb6, 0x94, 0xed, 0xcc, 0x2c, 0x06, - 0xcc, 0x61, 0x5f, 0x3a, 0x1f, 0x02, 0xa9, 0x64, 0x49, 0x91, 0x94, 0x2b, 0xf7, 0x95, 0xd7, 0x57, - 0x70, 0xb4, 0xdc, 0x37, 0x8c, 0x24, 0x3a, 0x29, 0x86, 0x91, 0xf8, 0xf5, 0x53, 0x1b, 0xc3, 0xe6, - 0xdd, 0x2c, 0xbd, 0x8a, 0xf8, 0xc5, 0xd7, 0x84, 0x77, 0x90, 0x46, 0x80, 0xe7, 0xbf, 0x3f, 0x7f, - 0xd6, 0xe5, 0x17, 0x7f, 0xfd, 0x0d, 0x1f, 0xe0, 0xa4, 0x52, 0xa6, 0xed, 0xb3, 0xef, 0x9a, 0x7f, - 0xdb, 0x4a, 0x73, 0x6d, 0x1e, 0xd3, 0x79, 0x09, 0x37, 0x1f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x20, - 0xd6, 0x09, 0xb8, 0x92, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testing/test.proto b/examples/google.golang.org/grpc/reflection/grpc_testing/test.proto deleted file mode 100755 index cae3f01..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testing/test.proto +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message SearchResponse { - message Result { - string url = 1; - string title = 2; - repeated string snippets = 3; - } - repeated Result results = 1; -} - -message SearchRequest { - string query = 1; -} - -service SearchService { - rpc Search(SearchRequest) returns (SearchResponse); - rpc StreamingSearch(stream SearchRequest) returns (stream SearchResponse); -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go b/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go deleted file mode 100755 index 767efdd..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.pb.go +++ /dev/null @@ -1,457 +0,0 @@ -// Code generated by protoc-gen-go. -// source: testv3.proto -// DO NOT EDIT! - -/* -Package grpc_testingv3 is a generated protocol buffer package. - -It is generated from these files: - testv3.proto - -It has these top-level messages: - SearchResponseV3 - SearchRequestV3 -*/ -package grpc_testingv3 - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SearchResponseV3_State int32 - -const ( - SearchResponseV3_UNKNOWN SearchResponseV3_State = 0 - SearchResponseV3_FRESH SearchResponseV3_State = 1 - SearchResponseV3_STALE SearchResponseV3_State = 2 -) - -var SearchResponseV3_State_name = map[int32]string{ - 0: "UNKNOWN", - 1: "FRESH", - 2: "STALE", -} -var SearchResponseV3_State_value = map[string]int32{ - "UNKNOWN": 0, - "FRESH": 1, - "STALE": 2, -} - -func (x SearchResponseV3_State) String() string { - return proto.EnumName(SearchResponseV3_State_name, int32(x)) -} -func (SearchResponseV3_State) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } - -type SearchResponseV3 struct { - Results []*SearchResponseV3_Result `protobuf:"bytes,1,rep,name=results" json:"results,omitempty"` - State SearchResponseV3_State `protobuf:"varint,2,opt,name=state,enum=grpc.testingv3.SearchResponseV3_State" json:"state,omitempty"` -} - -func (m *SearchResponseV3) Reset() { *m = SearchResponseV3{} } -func (m *SearchResponseV3) String() string { return proto.CompactTextString(m) } -func (*SearchResponseV3) ProtoMessage() {} -func (*SearchResponseV3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *SearchResponseV3) GetResults() []*SearchResponseV3_Result { - if m != nil { - return m.Results - } - return nil -} - -func (m *SearchResponseV3) GetState() SearchResponseV3_State { - if m != nil { - return m.State - } - return SearchResponseV3_UNKNOWN -} - -type SearchResponseV3_Result struct { - Url string `protobuf:"bytes,1,opt,name=url" json:"url,omitempty"` - Title string `protobuf:"bytes,2,opt,name=title" json:"title,omitempty"` - Snippets []string `protobuf:"bytes,3,rep,name=snippets" json:"snippets,omitempty"` - Metadata map[string]*SearchResponseV3_Result_Value `protobuf:"bytes,4,rep,name=metadata" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` -} - -func (m *SearchResponseV3_Result) Reset() { *m = SearchResponseV3_Result{} } -func (m *SearchResponseV3_Result) String() string { return proto.CompactTextString(m) } -func (*SearchResponseV3_Result) ProtoMessage() {} -func (*SearchResponseV3_Result) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } - -func (m *SearchResponseV3_Result) GetUrl() string { - if m != nil { - return m.Url - } - return "" -} - -func (m *SearchResponseV3_Result) GetTitle() string { - if m != nil { - return m.Title - } - return "" -} - -func (m *SearchResponseV3_Result) GetSnippets() []string { - if m != nil { - return m.Snippets - } - return nil -} - -func (m *SearchResponseV3_Result) GetMetadata() map[string]*SearchResponseV3_Result_Value { - if m != nil { - return m.Metadata - } - return nil -} - -type SearchResponseV3_Result_Value struct { - // Types that are valid to be assigned to Val: - // *SearchResponseV3_Result_Value_Str - // *SearchResponseV3_Result_Value_Int - // *SearchResponseV3_Result_Value_Real - Val isSearchResponseV3_Result_Value_Val `protobuf_oneof:"val"` -} - -func (m *SearchResponseV3_Result_Value) Reset() { *m = SearchResponseV3_Result_Value{} } -func (m *SearchResponseV3_Result_Value) String() string { return proto.CompactTextString(m) } -func (*SearchResponseV3_Result_Value) ProtoMessage() {} -func (*SearchResponseV3_Result_Value) Descriptor() ([]byte, []int) { - return fileDescriptor0, []int{0, 0, 0} -} - -type isSearchResponseV3_Result_Value_Val interface { - isSearchResponseV3_Result_Value_Val() -} - -type SearchResponseV3_Result_Value_Str struct { - Str string `protobuf:"bytes,1,opt,name=str,oneof"` -} -type SearchResponseV3_Result_Value_Int struct { - Int int64 `protobuf:"varint,2,opt,name=int,oneof"` -} -type SearchResponseV3_Result_Value_Real struct { - Real float64 `protobuf:"fixed64,3,opt,name=real,oneof"` -} - -func (*SearchResponseV3_Result_Value_Str) isSearchResponseV3_Result_Value_Val() {} -func (*SearchResponseV3_Result_Value_Int) isSearchResponseV3_Result_Value_Val() {} -func (*SearchResponseV3_Result_Value_Real) isSearchResponseV3_Result_Value_Val() {} - -func (m *SearchResponseV3_Result_Value) GetVal() isSearchResponseV3_Result_Value_Val { - if m != nil { - return m.Val - } - return nil -} - -func (m *SearchResponseV3_Result_Value) GetStr() string { - if x, ok := m.GetVal().(*SearchResponseV3_Result_Value_Str); ok { - return x.Str - } - return "" -} - -func (m *SearchResponseV3_Result_Value) GetInt() int64 { - if x, ok := m.GetVal().(*SearchResponseV3_Result_Value_Int); ok { - return x.Int - } - return 0 -} - -func (m *SearchResponseV3_Result_Value) GetReal() float64 { - if x, ok := m.GetVal().(*SearchResponseV3_Result_Value_Real); ok { - return x.Real - } - return 0 -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*SearchResponseV3_Result_Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _SearchResponseV3_Result_Value_OneofMarshaler, _SearchResponseV3_Result_Value_OneofUnmarshaler, _SearchResponseV3_Result_Value_OneofSizer, []interface{}{ - (*SearchResponseV3_Result_Value_Str)(nil), - (*SearchResponseV3_Result_Value_Int)(nil), - (*SearchResponseV3_Result_Value_Real)(nil), - } -} - -func _SearchResponseV3_Result_Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*SearchResponseV3_Result_Value) - // val - switch x := m.Val.(type) { - case *SearchResponseV3_Result_Value_Str: - b.EncodeVarint(1<<3 | proto.WireBytes) - b.EncodeStringBytes(x.Str) - case *SearchResponseV3_Result_Value_Int: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.Int)) - case *SearchResponseV3_Result_Value_Real: - b.EncodeVarint(3<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.Real)) - case nil: - default: - return fmt.Errorf("SearchResponseV3_Result_Value.Val has unexpected type %T", x) - } - return nil -} - -func _SearchResponseV3_Result_Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*SearchResponseV3_Result_Value) - switch tag { - case 1: // val.str - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Val = &SearchResponseV3_Result_Value_Str{x} - return true, err - case 2: // val.int - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Val = &SearchResponseV3_Result_Value_Int{int64(x)} - return true, err - case 3: // val.real - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Val = &SearchResponseV3_Result_Value_Real{math.Float64frombits(x)} - return true, err - default: - return false, nil - } -} - -func _SearchResponseV3_Result_Value_OneofSizer(msg proto.Message) (n int) { - m := msg.(*SearchResponseV3_Result_Value) - // val - switch x := m.Val.(type) { - case *SearchResponseV3_Result_Value_Str: - n += proto.SizeVarint(1<<3 | proto.WireBytes) - n += proto.SizeVarint(uint64(len(x.Str))) - n += len(x.Str) - case *SearchResponseV3_Result_Value_Int: - n += proto.SizeVarint(2<<3 | proto.WireVarint) - n += proto.SizeVarint(uint64(x.Int)) - case *SearchResponseV3_Result_Value_Real: - n += proto.SizeVarint(3<<3 | proto.WireFixed64) - n += 8 - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -type SearchRequestV3 struct { - Query string `protobuf:"bytes,1,opt,name=query" json:"query,omitempty"` -} - -func (m *SearchRequestV3) Reset() { *m = SearchRequestV3{} } -func (m *SearchRequestV3) String() string { return proto.CompactTextString(m) } -func (*SearchRequestV3) ProtoMessage() {} -func (*SearchRequestV3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *SearchRequestV3) GetQuery() string { - if m != nil { - return m.Query - } - return "" -} - -func init() { - proto.RegisterType((*SearchResponseV3)(nil), "grpc.testingv3.SearchResponseV3") - proto.RegisterType((*SearchResponseV3_Result)(nil), "grpc.testingv3.SearchResponseV3.Result") - proto.RegisterType((*SearchResponseV3_Result_Value)(nil), "grpc.testingv3.SearchResponseV3.Result.Value") - proto.RegisterType((*SearchRequestV3)(nil), "grpc.testingv3.SearchRequestV3") - proto.RegisterEnum("grpc.testingv3.SearchResponseV3_State", SearchResponseV3_State_name, SearchResponseV3_State_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion3 - -// Client API for SearchServiceV3 service - -type SearchServiceV3Client interface { - Search(ctx context.Context, in *SearchRequestV3, opts ...grpc.CallOption) (*SearchResponseV3, error) - StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchServiceV3_StreamingSearchClient, error) -} - -type searchServiceV3Client struct { - cc *grpc.ClientConn -} - -func NewSearchServiceV3Client(cc *grpc.ClientConn) SearchServiceV3Client { - return &searchServiceV3Client{cc} -} - -func (c *searchServiceV3Client) Search(ctx context.Context, in *SearchRequestV3, opts ...grpc.CallOption) (*SearchResponseV3, error) { - out := new(SearchResponseV3) - err := grpc.Invoke(ctx, "/grpc.testingv3.SearchServiceV3/Search", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *searchServiceV3Client) StreamingSearch(ctx context.Context, opts ...grpc.CallOption) (SearchServiceV3_StreamingSearchClient, error) { - stream, err := grpc.NewClientStream(ctx, &_SearchServiceV3_serviceDesc.Streams[0], c.cc, "/grpc.testingv3.SearchServiceV3/StreamingSearch", opts...) - if err != nil { - return nil, err - } - x := &searchServiceV3StreamingSearchClient{stream} - return x, nil -} - -type SearchServiceV3_StreamingSearchClient interface { - Send(*SearchRequestV3) error - Recv() (*SearchResponseV3, error) - grpc.ClientStream -} - -type searchServiceV3StreamingSearchClient struct { - grpc.ClientStream -} - -func (x *searchServiceV3StreamingSearchClient) Send(m *SearchRequestV3) error { - return x.ClientStream.SendMsg(m) -} - -func (x *searchServiceV3StreamingSearchClient) Recv() (*SearchResponseV3, error) { - m := new(SearchResponseV3) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// Server API for SearchServiceV3 service - -type SearchServiceV3Server interface { - Search(context.Context, *SearchRequestV3) (*SearchResponseV3, error) - StreamingSearch(SearchServiceV3_StreamingSearchServer) error -} - -func RegisterSearchServiceV3Server(s *grpc.Server, srv SearchServiceV3Server) { - s.RegisterService(&_SearchServiceV3_serviceDesc, srv) -} - -func _SearchServiceV3_Search_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SearchRequestV3) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SearchServiceV3Server).Search(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testingv3.SearchServiceV3/Search", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SearchServiceV3Server).Search(ctx, req.(*SearchRequestV3)) - } - return interceptor(ctx, in, info, handler) -} - -func _SearchServiceV3_StreamingSearch_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(SearchServiceV3Server).StreamingSearch(&searchServiceV3StreamingSearchServer{stream}) -} - -type SearchServiceV3_StreamingSearchServer interface { - Send(*SearchResponseV3) error - Recv() (*SearchRequestV3, error) - grpc.ServerStream -} - -type searchServiceV3StreamingSearchServer struct { - grpc.ServerStream -} - -func (x *searchServiceV3StreamingSearchServer) Send(m *SearchResponseV3) error { - return x.ServerStream.SendMsg(m) -} - -func (x *searchServiceV3StreamingSearchServer) Recv() (*SearchRequestV3, error) { - m := new(SearchRequestV3) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _SearchServiceV3_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testingv3.SearchServiceV3", - HandlerType: (*SearchServiceV3Server)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Search", - Handler: _SearchServiceV3_Search_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingSearch", - Handler: _SearchServiceV3_StreamingSearch_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: fileDescriptor0, -} - -func init() { proto.RegisterFile("testv3.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 416 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xd1, 0x6a, 0xd4, 0x40, - 0x14, 0x86, 0x77, 0x36, 0x9b, 0x6d, 0xf7, 0xac, 0xb6, 0x61, 0xe8, 0x45, 0xc8, 0x8d, 0x61, 0x2f, - 0x6c, 0x10, 0x0c, 0x92, 0x20, 0x88, 0x78, 0x53, 0x65, 0x65, 0xa1, 0x75, 0xc5, 0x89, 0xae, 0xde, - 0x8e, 0xeb, 0x61, 0x8d, 0x4d, 0xb3, 0xe9, 0xcc, 0x49, 0x60, 0x9f, 0xc5, 0x17, 0xf1, 0x55, 0x7c, - 0x1b, 0x99, 0x99, 0xa6, 0x50, 0x41, 0xba, 0x17, 0xde, 0xcd, 0x7f, 0x38, 0xff, 0x37, 0xff, 0x3f, - 0x24, 0xf0, 0x80, 0x50, 0x53, 0x97, 0xa7, 0x8d, 0xda, 0xd2, 0x96, 0x1f, 0x6d, 0x54, 0xb3, 0x4e, - 0xcd, 0xa8, 0xac, 0x37, 0x5d, 0x3e, 0xfb, 0x39, 0x82, 0xa0, 0x40, 0xa9, 0xd6, 0xdf, 0x05, 0xea, - 0x66, 0x5b, 0x6b, 0x5c, 0xe5, 0xfc, 0x0c, 0x0e, 0x14, 0xea, 0xb6, 0x22, 0x1d, 0xb2, 0xd8, 0x4b, - 0xa6, 0xd9, 0x69, 0x7a, 0xd7, 0x96, 0xfe, 0x6d, 0x49, 0x85, 0xdd, 0x17, 0xbd, 0x8f, 0xbf, 0x02, - 0x5f, 0x93, 0x24, 0x0c, 0x87, 0x31, 0x4b, 0x8e, 0xb2, 0xc7, 0xf7, 0x02, 0x0a, 0xb3, 0x2d, 0x9c, - 0x29, 0xfa, 0x3d, 0x84, 0xb1, 0x23, 0xf2, 0x00, 0xbc, 0x56, 0x55, 0x21, 0x8b, 0x59, 0x32, 0x11, - 0xe6, 0xc8, 0x4f, 0xc0, 0xa7, 0x92, 0x2a, 0x87, 0x9e, 0x08, 0x27, 0x78, 0x04, 0x87, 0xba, 0x2e, - 0x9b, 0x06, 0x49, 0x87, 0x5e, 0xec, 0x25, 0x13, 0x71, 0xab, 0xf9, 0x07, 0x38, 0xbc, 0x42, 0x92, - 0xdf, 0x24, 0xc9, 0x70, 0x64, 0x0b, 0x3d, 0xdf, 0xb3, 0x50, 0xfa, 0xee, 0xc6, 0x37, 0xaf, 0x49, - 0xed, 0xc4, 0x2d, 0x26, 0xba, 0x00, 0x7f, 0x25, 0xab, 0x16, 0x39, 0x07, 0x4f, 0x93, 0x72, 0xf9, - 0x16, 0x03, 0x61, 0x84, 0x99, 0x95, 0x35, 0xd9, 0x7c, 0x9e, 0x99, 0x95, 0x35, 0xf1, 0x13, 0x18, - 0x29, 0x94, 0x55, 0xe8, 0xc5, 0x2c, 0x61, 0x8b, 0x81, 0xb0, 0xea, 0xb5, 0x0f, 0x5e, 0x27, 0xab, - 0xe8, 0x07, 0x3c, 0xbc, 0x73, 0x91, 0x69, 0x7d, 0x89, 0xbb, 0xbe, 0xf5, 0x25, 0xee, 0xf8, 0x1b, - 0xf0, 0x3b, 0x73, 0xa1, 0xa5, 0x4e, 0xb3, 0xa7, 0xfb, 0x16, 0xb0, 0x29, 0x85, 0xf3, 0xbe, 0x1c, - 0xbe, 0x60, 0xb3, 0x27, 0xe0, 0xdb, 0xb7, 0xe6, 0x53, 0x38, 0xf8, 0xb4, 0x3c, 0x5f, 0xbe, 0xff, - 0xbc, 0x0c, 0x06, 0x7c, 0x02, 0xfe, 0x5b, 0x31, 0x2f, 0x16, 0x01, 0x33, 0xc7, 0xe2, 0xe3, 0xd9, - 0xc5, 0x3c, 0x18, 0xce, 0x4e, 0xe1, 0xb8, 0xe7, 0x5e, 0xb7, 0xa8, 0x69, 0x95, 0x9b, 0xd7, 0xbf, - 0x6e, 0x51, 0xf5, 0xd9, 0x9c, 0xc8, 0x7e, 0xb1, 0x7e, 0xb3, 0x40, 0xd5, 0x95, 0x6b, 0xf3, 0x15, - 0x9d, 0xc3, 0xd8, 0x8d, 0xf8, 0xa3, 0x7f, 0x85, 0xbd, 0x81, 0x46, 0xf1, 0x7d, 0x6d, 0xf8, 0x17, - 0x38, 0x2e, 0x48, 0xa1, 0xbc, 0x2a, 0xeb, 0xcd, 0x7f, 0xa3, 0x26, 0xec, 0x19, 0xfb, 0x3a, 0xb6, - 0x3f, 0x46, 0xfe, 0x27, 0x00, 0x00, 0xff, 0xff, 0xed, 0xa2, 0x8d, 0x75, 0x28, 0x03, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto b/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto deleted file mode 100755 index ee4966b..0000000 --- a/examples/google.golang.org/grpc/reflection/grpc_testingv3/testv3.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; - -package grpc.testingv3; - -message SearchResponseV3 { - message Result { - string url = 1; - string title = 2; - repeated string snippets = 3; - message Value { - oneof val { - string str = 1; - int64 int = 2; - double real = 3; - } - } - map metadata = 4; - } - enum State { - UNKNOWN = 0; - FRESH = 1; - STALE = 2; - } - repeated Result results = 1; - State state = 2; -} - -message SearchRequestV3 { - string query = 1; -} - -service SearchServiceV3 { - rpc Search(SearchRequestV3) returns (SearchResponseV3); - rpc StreamingSearch(stream SearchRequestV3) returns (stream SearchResponseV3); -} diff --git a/examples/google.golang.org/grpc/reflection/serverreflection.go b/examples/google.golang.org/grpc/reflection/serverreflection.go deleted file mode 100755 index dd22a2d..0000000 --- a/examples/google.golang.org/grpc/reflection/serverreflection.go +++ /dev/null @@ -1,454 +0,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. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_reflection_v1alpha/reflection.proto - -/* -Package reflection implements server reflection service. - -The service implemented is defined in: -https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. - -To register server reflection on a gRPC server: - import "google.golang.org/grpc/reflection" - - s := grpc.NewServer() - pb.RegisterYourOwnServer(s, &server{}) - - // Register reflection service on gRPC server. - reflection.Register(s) - - s.Serve(lis) - -*/ -package reflection // import "google.golang.org/grpc/reflection" - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "reflect" - "sort" - "sync" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" - "google.golang.org/grpc/status" -) - -type serverReflectionServer struct { - s *grpc.Server - - initSymbols sync.Once - serviceNames []string - symbols map[string]*dpb.FileDescriptorProto // map of fully-qualified names to files -} - -// Register registers the server reflection service on the given gRPC server. -func Register(s *grpc.Server) { - rpb.RegisterServerReflectionServer(s, &serverReflectionServer{ - s: s, - }) -} - -// protoMessage is used for type assertion on proto messages. -// Generated proto message implements function Descriptor(), but Descriptor() -// is not part of interface proto.Message. This interface is needed to -// call Descriptor(). -type protoMessage interface { - Descriptor() ([]byte, []int) -} - -func (s *serverReflectionServer) getSymbols() (svcNames []string, symbolIndex map[string]*dpb.FileDescriptorProto) { - s.initSymbols.Do(func() { - serviceInfo := s.s.GetServiceInfo() - - s.symbols = map[string]*dpb.FileDescriptorProto{} - s.serviceNames = make([]string, 0, len(serviceInfo)) - processed := map[string]struct{}{} - for svc, info := range serviceInfo { - s.serviceNames = append(s.serviceNames, svc) - fdenc, ok := parseMetadata(info.Metadata) - if !ok { - continue - } - fd, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fd, processed) - } - sort.Strings(s.serviceNames) - }) - - return s.serviceNames, s.symbols -} - -func (s *serverReflectionServer) processFile(fd *dpb.FileDescriptorProto, processed map[string]struct{}) { - filename := fd.GetName() - if _, ok := processed[filename]; ok { - return - } - processed[filename] = struct{}{} - - prefix := fd.GetPackage() - - for _, msg := range fd.MessageType { - s.processMessage(fd, prefix, msg) - } - for _, en := range fd.EnumType { - s.processEnum(fd, prefix, en) - } - for _, ext := range fd.Extension { - s.processField(fd, prefix, ext) - } - for _, svc := range fd.Service { - svcName := fqn(prefix, svc.GetName()) - s.symbols[svcName] = fd - for _, meth := range svc.Method { - name := fqn(svcName, meth.GetName()) - s.symbols[name] = fd - } - } - - for _, dep := range fd.Dependency { - fdenc := proto.FileDescriptor(dep) - fdDep, err := decodeFileDesc(fdenc) - if err != nil { - continue - } - s.processFile(fdDep, processed) - } -} - -func (s *serverReflectionServer) processMessage(fd *dpb.FileDescriptorProto, prefix string, msg *dpb.DescriptorProto) { - msgName := fqn(prefix, msg.GetName()) - s.symbols[msgName] = fd - - for _, nested := range msg.NestedType { - s.processMessage(fd, msgName, nested) - } - for _, en := range msg.EnumType { - s.processEnum(fd, msgName, en) - } - for _, ext := range msg.Extension { - s.processField(fd, msgName, ext) - } - for _, fld := range msg.Field { - s.processField(fd, msgName, fld) - } - for _, oneof := range msg.OneofDecl { - oneofName := fqn(msgName, oneof.GetName()) - s.symbols[oneofName] = fd - } -} - -func (s *serverReflectionServer) processEnum(fd *dpb.FileDescriptorProto, prefix string, en *dpb.EnumDescriptorProto) { - enName := fqn(prefix, en.GetName()) - s.symbols[enName] = fd - - for _, val := range en.Value { - valName := fqn(enName, val.GetName()) - s.symbols[valName] = fd - } -} - -func (s *serverReflectionServer) processField(fd *dpb.FileDescriptorProto, prefix string, fld *dpb.FieldDescriptorProto) { - fldName := fqn(prefix, fld.GetName()) - s.symbols[fldName] = fd -} - -func fqn(prefix, name string) string { - if prefix == "" { - return name - } - return prefix + "." + name -} - -// fileDescForType gets the file descriptor for the given type. -// The given type should be a proto message. -func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - enc, _ := m.Descriptor() - - return decodeFileDesc(enc) -} - -// decodeFileDesc does decompression and unmarshalling on the given -// file descriptor byte slice. -func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { - raw, err := decompress(enc) - if err != nil { - return nil, fmt.Errorf("failed to decompress enc: %v", err) - } - - fd := new(dpb.FileDescriptorProto) - if err := proto.Unmarshal(raw, fd); err != nil { - return nil, fmt.Errorf("bad descriptor: %v", err) - } - return fd, nil -} - -// decompress does gzip decompression. -func decompress(b []byte) ([]byte, error) { - r, err := gzip.NewReader(bytes.NewReader(b)) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - out, err := ioutil.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("bad gzipped descriptor: %v", err) - } - return out, nil -} - -func typeForName(name string) (reflect.Type, error) { - pt := proto.MessageType(name) - if pt == nil { - return nil, fmt.Errorf("unknown type: %q", name) - } - st := pt.Elem() - - return st, nil -} - -func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - var extDesc *proto.ExtensionDesc - for id, desc := range proto.RegisteredExtensions(m) { - if id == ext { - extDesc = desc - break - } - } - - if extDesc == nil { - return nil, fmt.Errorf("failed to find registered extension for extension number %v", ext) - } - - return decodeFileDesc(proto.FileDescriptor(extDesc.Filename)) -} - -func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { - m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) - if !ok { - return nil, fmt.Errorf("failed to create message from type: %v", st) - } - - exts := proto.RegisteredExtensions(m) - out := make([]int32, 0, len(exts)) - for id := range exts { - out = append(out, id) - } - return out, nil -} - -// fileDescEncodingByFilename finds the file descriptor for given filename, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingByFilename(name string) ([]byte, error) { - enc := proto.FileDescriptor(name) - if enc == nil { - return nil, fmt.Errorf("unknown file: %v", name) - } - fd, err := decodeFileDesc(enc) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// parseMetadata finds the file descriptor bytes specified meta. -// For SupportPackageIsVersion4, m is the name of the proto file, we -// call proto.FileDescriptor to get the byte slice. -// For SupportPackageIsVersion3, m is a byte slice itself. -func parseMetadata(meta interface{}) ([]byte, bool) { - // Check if meta is the file name. - if fileNameForMeta, ok := meta.(string); ok { - return proto.FileDescriptor(fileNameForMeta), true - } - - // Check if meta is the byte slice. - if enc, ok := meta.([]byte); ok { - return enc, true - } - - return nil, false -} - -// fileDescEncodingContainingSymbol finds the file descriptor containing the given symbol, -// does marshalling on it and returns the marshalled result. -// The given symbol can be a type, a service or a method. -func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string) ([]byte, error) { - _, symbols := s.getSymbols() - fd := symbols[name] - if fd == nil { - // Check if it's a type name that was not present in the - // transitive dependencies of the registered services. - if st, err := typeForName(name); err == nil { - fd, err = s.fileDescForType(st) - if err != nil { - return nil, err - } - } - } - - if fd == nil { - return nil, fmt.Errorf("unknown symbol: %v", name) - } - - return proto.Marshal(fd) -} - -// fileDescEncodingContainingExtension finds the file descriptor containing given extension, -// does marshalling on it and returns the marshalled result. -func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32) ([]byte, error) { - st, err := typeForName(typeName) - if err != nil { - return nil, err - } - fd, err := fileDescContainingExtension(st, extNum) - if err != nil { - return nil, err - } - return proto.Marshal(fd) -} - -// allExtensionNumbersForTypeName returns all extension numbers for the given type. -func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { - st, err := typeForName(name) - if err != nil { - return nil, err - } - extNums, err := s.allExtensionNumbersForType(st) - if err != nil { - return nil, err - } - return extNums, nil -} - -// ServerReflectionInfo is the reflection service handler. -func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflection_ServerReflectionInfoServer) error { - for { - in, err := stream.Recv() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - out := &rpb.ServerReflectionResponse{ - ValidHost: in.Host, - OriginalRequest: in, - } - switch req := in.MessageRequest.(type) { - case *rpb.ServerReflectionRequest_FileByFilename: - b, err := s.fileDescEncodingByFilename(req.FileByFilename) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingSymbol: - b, err := s.fileDescEncodingContainingSymbol(req.FileContainingSymbol) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_FileContainingExtension: - typeName := req.FileContainingExtension.ContainingType - extNum := req.FileContainingExtension.ExtensionNumber - b, err := s.fileDescEncodingContainingExtension(typeName, extNum) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ - FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, - } - } - case *rpb.ServerReflectionRequest_AllExtensionNumbersOfType: - extNums, err := s.allExtensionNumbersForTypeName(req.AllExtensionNumbersOfType) - if err != nil { - out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ - ErrorResponse: &rpb.ErrorResponse{ - ErrorCode: int32(codes.NotFound), - ErrorMessage: err.Error(), - }, - } - } else { - out.MessageResponse = &rpb.ServerReflectionResponse_AllExtensionNumbersResponse{ - AllExtensionNumbersResponse: &rpb.ExtensionNumberResponse{ - BaseTypeName: req.AllExtensionNumbersOfType, - ExtensionNumber: extNums, - }, - } - } - case *rpb.ServerReflectionRequest_ListServices: - svcNames, _ := s.getSymbols() - serviceResponses := make([]*rpb.ServiceResponse, len(svcNames)) - for i, n := range svcNames { - serviceResponses[i] = &rpb.ServiceResponse{ - Name: n, - } - } - out.MessageResponse = &rpb.ServerReflectionResponse_ListServicesResponse{ - ListServicesResponse: &rpb.ListServiceResponse{ - Service: serviceResponses, - }, - } - default: - return status.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest) - } - - if err := stream.Send(out); err != nil { - return err - } - } -} diff --git a/examples/google.golang.org/grpc/reflection/serverreflection_test.go b/examples/google.golang.org/grpc/reflection/serverreflection_test.go deleted file mode 100755 index e2c7416..0000000 --- a/examples/google.golang.org/grpc/reflection/serverreflection_test.go +++ /dev/null @@ -1,526 +0,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. - * - */ - -//go:generate protoc -I grpc_testing --go_out=plugins=grpc:grpc_testing/ grpc_testing/proto2.proto grpc_testing/proto2_ext.proto grpc_testing/proto2_ext2.proto grpc_testing/test.proto - -// Note: grpc_testingv3/testv3.pb.go is not re-generated because it was -// intentionally generated by an older version of protoc-gen-go. - -package reflection - -import ( - "fmt" - "net" - "reflect" - "sort" - "testing" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "golang.org/x/net/context" - "google.golang.org/grpc" - rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" - pb "google.golang.org/grpc/reflection/grpc_testing" - pbv3 "google.golang.org/grpc/reflection/grpc_testingv3" -) - -var ( - s = &serverReflectionServer{} - // fileDescriptor of each test proto file. - fdTest *dpb.FileDescriptorProto - fdTestv3 *dpb.FileDescriptorProto - fdProto2 *dpb.FileDescriptorProto - fdProto2Ext *dpb.FileDescriptorProto - fdProto2Ext2 *dpb.FileDescriptorProto - // fileDescriptor marshalled. - fdTestByte []byte - fdTestv3Byte []byte - fdProto2Byte []byte - fdProto2ExtByte []byte - fdProto2Ext2Byte []byte -) - -func loadFileDesc(filename string) (*dpb.FileDescriptorProto, []byte) { - enc := proto.FileDescriptor(filename) - if enc == nil { - panic(fmt.Sprintf("failed to find fd for file: %v", filename)) - } - fd, err := decodeFileDesc(enc) - if err != nil { - panic(fmt.Sprintf("failed to decode enc: %v", err)) - } - b, err := proto.Marshal(fd) - if err != nil { - panic(fmt.Sprintf("failed to marshal fd: %v", err)) - } - return fd, b -} - -func init() { - fdTest, fdTestByte = loadFileDesc("test.proto") - fdTestv3, fdTestv3Byte = loadFileDesc("testv3.proto") - fdProto2, fdProto2Byte = loadFileDesc("proto2.proto") - fdProto2Ext, fdProto2ExtByte = loadFileDesc("proto2_ext.proto") - fdProto2Ext2, fdProto2Ext2Byte = loadFileDesc("proto2_ext2.proto") -} - -func TestFileDescForType(t *testing.T) { - for _, test := range []struct { - st reflect.Type - wantFd *dpb.FileDescriptorProto - }{ - {reflect.TypeOf(pb.SearchResponse_Result{}), fdTest}, - {reflect.TypeOf(pb.ToBeExtended{}), fdProto2}, - } { - fd, err := s.fileDescForType(test.st) - if err != nil || !proto.Equal(fd, test.wantFd) { - t.Errorf("fileDescForType(%q) = %q, %v, want %q, ", test.st, fd, err, test.wantFd) - } - } -} - -func TestTypeForName(t *testing.T) { - for _, test := range []struct { - name string - want reflect.Type - }{ - {"grpc.testing.SearchResponse", reflect.TypeOf(pb.SearchResponse{})}, - } { - r, err := typeForName(test.name) - if err != nil || r != test.want { - t.Errorf("typeForName(%q) = %q, %v, want %q, ", test.name, r, err, test.want) - } - } -} - -func TestTypeForNameNotFound(t *testing.T) { - for _, test := range []string{ - "grpc.testing.not_exiting", - } { - _, err := typeForName(test) - if err == nil { - t.Errorf("typeForName(%q) = _, %v, want _, ", test, err) - } - } -} - -func TestFileDescContainingExtension(t *testing.T) { - for _, test := range []struct { - st reflect.Type - extNum int32 - want *dpb.FileDescriptorProto - }{ - {reflect.TypeOf(pb.ToBeExtended{}), 13, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 17, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 19, fdProto2Ext}, - {reflect.TypeOf(pb.ToBeExtended{}), 23, fdProto2Ext2}, - {reflect.TypeOf(pb.ToBeExtended{}), 29, fdProto2Ext2}, - } { - fd, err := fileDescContainingExtension(test.st, test.extNum) - if err != nil || !proto.Equal(fd, test.want) { - t.Errorf("fileDescContainingExtension(%q) = %q, %v, want %q, ", test.st, fd, err, test.want) - } - } -} - -// intArray is used to sort []int32 -type intArray []int32 - -func (s intArray) Len() int { return len(s) } -func (s intArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s intArray) Less(i, j int) bool { return s[i] < s[j] } - -func TestAllExtensionNumbersForType(t *testing.T) { - for _, test := range []struct { - st reflect.Type - want []int32 - }{ - {reflect.TypeOf(pb.ToBeExtended{}), []int32{13, 17, 19, 23, 29}}, - } { - r, err := s.allExtensionNumbersForType(test.st) - sort.Sort(intArray(r)) - if err != nil || !reflect.DeepEqual(r, test.want) { - t.Errorf("allExtensionNumbersForType(%q) = %v, %v, want %v, ", test.st, r, err, test.want) - } - } -} - -// Do end2end tests. - -type server struct{} - -func (s *server) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResponse, error) { - return &pb.SearchResponse{}, nil -} - -func (s *server) StreamingSearch(stream pb.SearchService_StreamingSearchServer) error { - return nil -} - -type serverV3 struct{} - -func (s *serverV3) Search(ctx context.Context, in *pbv3.SearchRequestV3) (*pbv3.SearchResponseV3, error) { - return &pbv3.SearchResponseV3{}, nil -} - -func (s *serverV3) StreamingSearch(stream pbv3.SearchServiceV3_StreamingSearchServer) error { - return nil -} - -func TestReflectionEnd2end(t *testing.T) { - // Start server. - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - s := grpc.NewServer() - pb.RegisterSearchServiceServer(s, &server{}) - pbv3.RegisterSearchServiceV3Server(s, &serverV3{}) - // Register reflection service on s. - Register(s) - go s.Serve(lis) - - // Create client. - conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure()) - if err != nil { - t.Fatalf("cannot connect to server: %v", err) - } - defer conn.Close() - - c := rpb.NewServerReflectionClient(conn) - stream, err := c.ServerReflectionInfo(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("cannot get ServerReflectionInfo: %v", err) - } - - testFileByFilename(t, stream) - testFileByFilenameError(t, stream) - testFileContainingSymbol(t, stream) - testFileContainingSymbolError(t, stream) - testFileContainingExtension(t, stream) - testFileContainingExtensionError(t, stream) - testAllExtensionNumbersOfType(t, stream) - testAllExtensionNumbersOfTypeError(t, stream) - testListServices(t, stream) - - s.Stop() -} - -func testFileByFilename(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - filename string - want []byte - }{ - {"test.proto", fdTestByte}, - {"proto2.proto", fdProto2Byte}, - {"proto2_ext.proto", fdProto2ExtByte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileByFilename{ - FileByFilename: test.filename, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileByFilename(%v)\nreceived: %q,\nwant: %q", test.filename, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileByFilename(%v) = %v, want type ", test.filename, r.MessageResponse) - } - } -} - -func testFileByFilenameError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "test.poto", - "proo2.proto", - "proto2_et.proto", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileByFilename{ - FileByFilename: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileByFilename(%v) = %v, want type ", test, r.MessageResponse) - } - } -} - -func testFileContainingSymbol(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - symbol string - want []byte - }{ - {"grpc.testing.SearchService", fdTestByte}, - {"grpc.testing.SearchService.Search", fdTestByte}, - {"grpc.testing.SearchService.StreamingSearch", fdTestByte}, - {"grpc.testing.SearchResponse", fdTestByte}, - {"grpc.testing.ToBeExtended", fdProto2Byte}, - // Test support package v3. - {"grpc.testingv3.SearchServiceV3", fdTestv3Byte}, - {"grpc.testingv3.SearchServiceV3.Search", fdTestv3Byte}, - {"grpc.testingv3.SearchServiceV3.StreamingSearch", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3", fdTestv3Byte}, - // search for field, oneof, enum, and enum value symbols, too - {"grpc.testingv3.SearchResponseV3.Result.snippets", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3.Result.Value.val", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3.Result.Value.str", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3.State", fdTestv3Byte}, - {"grpc.testingv3.SearchResponseV3.State.FRESH", fdTestv3Byte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingSymbol{ - FileContainingSymbol: test.symbol, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileContainingSymbol(%v)\nreceived: %q,\nwant: %q", test.symbol, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileContainingSymbol(%v) = %v, want type ", test.symbol, r.MessageResponse) - } - } -} - -func testFileContainingSymbolError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "grpc.testing.SerchService", - "grpc.testing.SearchService.SearchE", - "grpc.tesing.SearchResponse", - "gpc.testing.ToBeExtended", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingSymbol{ - FileContainingSymbol: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileContainingSymbol(%v) = %v, want type ", test, r.MessageResponse) - } - } -} - -func testFileContainingExtension(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - extNum int32 - want []byte - }{ - {"grpc.testing.ToBeExtended", 13, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 17, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 19, fdProto2ExtByte}, - {"grpc.testing.ToBeExtended", 23, fdProto2Ext2Byte}, - {"grpc.testing.ToBeExtended", 29, fdProto2Ext2Byte}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingExtension{ - FileContainingExtension: &rpb.ExtensionRequest{ - ContainingType: test.typeName, - ExtensionNumber: test.extNum, - }, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_FileDescriptorResponse: - if !reflect.DeepEqual(r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) { - t.Errorf("FileContainingExtension(%v, %v)\nreceived: %q,\nwant: %q", test.typeName, test.extNum, r.GetFileDescriptorResponse().FileDescriptorProto[0], test.want) - } - default: - t.Errorf("FileContainingExtension(%v, %v) = %v, want type ", test.typeName, test.extNum, r.MessageResponse) - } - } -} - -func testFileContainingExtensionError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - extNum int32 - }{ - {"grpc.testing.ToBExtended", 17}, - {"grpc.testing.ToBeExtended", 15}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_FileContainingExtension{ - FileContainingExtension: &rpb.ExtensionRequest{ - ContainingType: test.typeName, - ExtensionNumber: test.extNum, - }, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("FileContainingExtension(%v, %v) = %v, want type ", test.typeName, test.extNum, r.MessageResponse) - } - } -} - -func testAllExtensionNumbersOfType(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []struct { - typeName string - want []int32 - }{ - {"grpc.testing.ToBeExtended", []int32{13, 17, 19, 23, 29}}, - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_AllExtensionNumbersOfType{ - AllExtensionNumbersOfType: test.typeName, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_AllExtensionNumbersResponse: - extNum := r.GetAllExtensionNumbersResponse().ExtensionNumber - sort.Sort(intArray(extNum)) - if r.GetAllExtensionNumbersResponse().BaseTypeName != test.typeName || - !reflect.DeepEqual(extNum, test.want) { - t.Errorf("AllExtensionNumbersOfType(%v)\nreceived: %v,\nwant: {%q %v}", r.GetAllExtensionNumbersResponse(), test.typeName, test.typeName, test.want) - } - default: - t.Errorf("AllExtensionNumbersOfType(%v) = %v, want type ", test.typeName, r.MessageResponse) - } - } -} - -func testAllExtensionNumbersOfTypeError(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - for _, test := range []string{ - "grpc.testing.ToBeExtendedE", - } { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_AllExtensionNumbersOfType{ - AllExtensionNumbersOfType: test, - }, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ErrorResponse: - default: - t.Errorf("AllExtensionNumbersOfType(%v) = %v, want type ", test, r.MessageResponse) - } - } -} - -func testListServices(t *testing.T, stream rpb.ServerReflection_ServerReflectionInfoClient) { - if err := stream.Send(&rpb.ServerReflectionRequest{ - MessageRequest: &rpb.ServerReflectionRequest_ListServices{}, - }); err != nil { - t.Fatalf("failed to send request: %v", err) - } - r, err := stream.Recv() - if err != nil { - // io.EOF is not ok. - t.Fatalf("failed to recv response: %v", err) - } - - switch r.MessageResponse.(type) { - case *rpb.ServerReflectionResponse_ListServicesResponse: - services := r.GetListServicesResponse().Service - want := []string{ - "grpc.testingv3.SearchServiceV3", - "grpc.testing.SearchService", - "grpc.reflection.v1alpha.ServerReflection", - } - // Compare service names in response with want. - if len(services) != len(want) { - t.Errorf("= %v, want service names: %v", services, want) - } - m := make(map[string]int) - for _, e := range services { - m[e.Name]++ - } - for _, e := range want { - if m[e] > 0 { - m[e]-- - continue - } - t.Errorf("ListService\nreceived: %v,\nwant: %q", services, want) - } - default: - t.Errorf("ListServices = %v, want type ", r.MessageResponse) - } -} diff --git a/examples/google.golang.org/grpc/resolver/dns/dns_resolver.go b/examples/google.golang.org/grpc/resolver/dns/dns_resolver.go deleted file mode 100755 index 048fde6..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/dns_resolver.go +++ /dev/null @@ -1,381 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package dns implements a dns resolver to be installed as the default resolver -// in grpc. -package dns - -import ( - "encoding/json" - "errors" - "fmt" - "net" - "os" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/grpcrand" - "google.golang.org/grpc/resolver" -) - -func init() { - resolver.Register(NewBuilder()) -} - -const ( - defaultPort = "443" - defaultFreq = time.Minute * 30 - golang = "GO" - // In DNS, service config is encoded in a TXT record via the mechanism - // described in RFC-1464 using the attribute name grpc_config. - txtAttribute = "grpc_config=" -) - -var ( - errMissingAddr = errors.New("missing address") -) - -// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. -func NewBuilder() resolver.Builder { - return &dnsBuilder{freq: defaultFreq} -} - -type dnsBuilder struct { - // frequency of polling the DNS server. - freq time.Duration -} - -// Build creates and starts a DNS resolver that watches the name resolution of the target. -func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - if target.Authority != "" { - return nil, fmt.Errorf("Default DNS resolver does not support custom DNS server") - } - host, port, err := parseTarget(target.Endpoint) - if err != nil { - return nil, err - } - - // IP address. - if net.ParseIP(host) != nil { - host, _ = formatIP(host) - addr := []resolver.Address{{Addr: host + ":" + port}} - i := &ipResolver{ - cc: cc, - ip: addr, - rn: make(chan struct{}, 1), - q: make(chan struct{}), - } - cc.NewAddress(addr) - go i.watcher() - return i, nil - } - - // DNS address (non-IP). - ctx, cancel := context.WithCancel(context.Background()) - d := &dnsResolver{ - freq: b.freq, - host: host, - port: port, - ctx: ctx, - cancel: cancel, - cc: cc, - t: time.NewTimer(0), - rn: make(chan struct{}, 1), - disableServiceConfig: opts.DisableServiceConfig, - } - - d.wg.Add(1) - go d.watcher() - return d, nil -} - -// Scheme returns the naming scheme of this resolver builder, which is "dns". -func (b *dnsBuilder) Scheme() string { - return "dns" -} - -// ipResolver watches for the name resolution update for an IP address. -type ipResolver struct { - cc resolver.ClientConn - ip []resolver.Address - // rn channel is used by ResolveNow() to force an immediate resolution of the target. - rn chan struct{} - q chan struct{} -} - -// ResolveNow resend the address it stores, no resolution is needed. -func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) { - select { - case i.rn <- struct{}{}: - default: - } -} - -// Close closes the ipResolver. -func (i *ipResolver) Close() { - close(i.q) -} - -func (i *ipResolver) watcher() { - for { - select { - case <-i.rn: - i.cc.NewAddress(i.ip) - case <-i.q: - return - } - } -} - -// dnsResolver watches for the name resolution update for a non-IP target. -type dnsResolver struct { - freq time.Duration - host string - port string - ctx context.Context - cancel context.CancelFunc - cc resolver.ClientConn - // rn channel is used by ResolveNow() to force an immediate resolution of the target. - rn chan struct{} - t *time.Timer - // wg is used to enforce Close() to return after the watcher() goroutine has finished. - // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we - // replace the real lookup functions with mocked ones to facilitate testing. - // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes - // will warns lookup (READ the lookup function pointers) inside watcher() goroutine - // has data race with replaceNetFunc (WRITE the lookup function pointers). - wg sync.WaitGroup - disableServiceConfig bool -} - -// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches. -func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) { - select { - case d.rn <- struct{}{}: - default: - } -} - -// Close closes the dnsResolver. -func (d *dnsResolver) Close() { - d.cancel() - d.wg.Wait() - d.t.Stop() -} - -func (d *dnsResolver) watcher() { - defer d.wg.Done() - for { - select { - case <-d.ctx.Done(): - return - case <-d.t.C: - case <-d.rn: - } - result, sc := d.lookup() - // Next lookup should happen after an interval defined by d.freq. - d.t.Reset(d.freq) - d.cc.NewServiceConfig(sc) - d.cc.NewAddress(result) - } -} - -func (d *dnsResolver) lookupSRV() []resolver.Address { - var newAddrs []resolver.Address - _, srvs, err := lookupSRV(d.ctx, "grpclb", "tcp", d.host) - if err != nil { - grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) - return nil - } - for _, s := range srvs { - lbAddrs, err := lookupHost(d.ctx, s.Target) - if err != nil { - grpclog.Infof("grpc: failed load balancer address dns lookup due to %v.\n", err) - continue - } - for _, a := range lbAddrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + strconv.Itoa(int(s.Port)) - newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target}) - } - } - return newAddrs -} - -func (d *dnsResolver) lookupTXT() string { - ss, err := lookupTXT(d.ctx, d.host) - if err != nil { - grpclog.Infof("grpc: failed dns TXT record lookup due to %v.\n", err) - return "" - } - var res string - for _, s := range ss { - res += s - } - - // TXT record must have "grpc_config=" attribute in order to be used as service config. - if !strings.HasPrefix(res, txtAttribute) { - grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute) - return "" - } - return strings.TrimPrefix(res, txtAttribute) -} - -func (d *dnsResolver) lookupHost() []resolver.Address { - var newAddrs []resolver.Address - addrs, err := lookupHost(d.ctx, d.host) - if err != nil { - grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) - return nil - } - for _, a := range addrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + d.port - newAddrs = append(newAddrs, resolver.Address{Addr: addr}) - } - return newAddrs -} - -func (d *dnsResolver) lookup() ([]resolver.Address, string) { - newAddrs := d.lookupSRV() - // Support fallback to non-balancer address. - newAddrs = append(newAddrs, d.lookupHost()...) - if d.disableServiceConfig { - return newAddrs, "" - } - sc := d.lookupTXT() - return newAddrs, canaryingSC(sc) -} - -// formatIP returns ok = false if addr is not a valid textual representation of an IP address. -// If addr is an IPv4 address, return the addr and ok = true. -// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. -func formatIP(addr string) (addrIP string, ok bool) { - ip := net.ParseIP(addr) - if ip == nil { - return "", false - } - if ip.To4() != nil { - return addr, true - } - return "[" + addr + "]", true -} - -// parseTarget takes the user input target string, returns formatted host and port info. -// If target doesn't specify a port, set the port to be the defaultPort. -// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets -// are strippd when setting the host. -// examples: -// target: "www.google.com" returns host: "www.google.com", port: "443" -// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" -// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" -// target: ":80" returns host: "localhost", port: "80" -// target: ":" returns host: "localhost", port: "443" -func parseTarget(target string) (host, port string, err error) { - if target == "" { - return "", "", errMissingAddr - } - if ip := net.ParseIP(target); ip != nil { - // target is an IPv4 or IPv6(without brackets) address - return target, defaultPort, nil - } - if host, port, err = net.SplitHostPort(target); err == nil { - // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port - if host == "" { - // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. - host = "localhost" - } - if port == "" { - // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. - port = defaultPort - } - return host, port, nil - } - if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil { - // target doesn't have port - return host, port, nil - } - return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err) -} - -type rawChoice struct { - ClientLanguage *[]string `json:"clientLanguage,omitempty"` - Percentage *int `json:"percentage,omitempty"` - ClientHostName *[]string `json:"clientHostName,omitempty"` - ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"` -} - -func containsString(a *[]string, b string) bool { - if a == nil { - return true - } - for _, c := range *a { - if c == b { - return true - } - } - return false -} - -func chosenByPercentage(a *int) bool { - if a == nil { - return true - } - return grpcrand.Intn(100)+1 <= *a -} - -func canaryingSC(js string) string { - if js == "" { - return "" - } - var rcs []rawChoice - err := json.Unmarshal([]byte(js), &rcs) - if err != nil { - grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err) - return "" - } - cliHostname, err := os.Hostname() - if err != nil { - grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err) - return "" - } - var sc string - for _, c := range rcs { - if !containsString(c.ClientLanguage, golang) || - !chosenByPercentage(c.Percentage) || - !containsString(c.ClientHostName, cliHostname) || - c.ServiceConfig == nil { - continue - } - sc = string(*c.ServiceConfig) - break - } - return sc -} diff --git a/examples/google.golang.org/grpc/resolver/dns/dns_resolver_test.go b/examples/google.golang.org/grpc/resolver/dns/dns_resolver_test.go deleted file mode 100755 index 66c9735..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/dns_resolver_test.go +++ /dev/null @@ -1,936 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import ( - "fmt" - "net" - "os" - "reflect" - "sync" - "testing" - "time" - - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/resolver" -) - -func TestMain(m *testing.M) { - cleanup := replaceNetFunc() - code := m.Run() - cleanup() - os.Exit(code) -} - -const ( - txtBytesLimit = 255 -) - -type testClientConn struct { - target string - m1 sync.Mutex - addrs []resolver.Address - a int - m2 sync.Mutex - sc string - s int -} - -func (t *testClientConn) NewAddress(addresses []resolver.Address) { - t.m1.Lock() - defer t.m1.Unlock() - t.addrs = addresses - t.a++ -} - -func (t *testClientConn) getAddress() ([]resolver.Address, int) { - t.m1.Lock() - defer t.m1.Unlock() - return t.addrs, t.a -} - -func (t *testClientConn) NewServiceConfig(serviceConfig string) { - t.m2.Lock() - defer t.m2.Unlock() - t.sc = serviceConfig - t.s++ -} - -func (t *testClientConn) getSc() (string, int) { - t.m2.Lock() - defer t.m2.Unlock() - return t.sc, t.s -} - -var hostLookupTbl = struct { - sync.Mutex - tbl map[string][]string -}{ - tbl: map[string][]string{ - "foo.bar.com": {"1.2.3.4", "5.6.7.8"}, - "ipv4.single.fake": {"1.2.3.4"}, - "srv.ipv4.single.fake": {"2.4.6.8"}, - "ipv4.multi.fake": {"1.2.3.4", "5.6.7.8", "9.10.11.12"}, - "ipv6.single.fake": {"2607:f8b0:400a:801::1001"}, - "ipv6.multi.fake": {"2607:f8b0:400a:801::1001", "2607:f8b0:400a:801::1002", "2607:f8b0:400a:801::1003"}, - }, -} - -func hostLookup(host string) ([]string, error) { - hostLookupTbl.Lock() - defer hostLookupTbl.Unlock() - if addrs, cnt := hostLookupTbl.tbl[host]; cnt { - return addrs, nil - } - return nil, fmt.Errorf("failed to lookup host:%s resolution in hostLookupTbl", host) -} - -var srvLookupTbl = struct { - sync.Mutex - tbl map[string][]*net.SRV -}{ - tbl: map[string][]*net.SRV{ - "_grpclb._tcp.srv.ipv4.single.fake": {&net.SRV{Target: "ipv4.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv4.multi.fake": {&net.SRV{Target: "ipv4.multi.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.single.fake": {&net.SRV{Target: "ipv6.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.multi.fake": {&net.SRV{Target: "ipv6.multi.fake", Port: 1234}}, - }, -} - -func srvLookup(service, proto, name string) (string, []*net.SRV, error) { - cname := "_" + service + "._" + proto + "." + name - srvLookupTbl.Lock() - defer srvLookupTbl.Unlock() - if srvs, cnt := srvLookupTbl.tbl[cname]; cnt { - return cname, srvs, nil - } - return "", nil, fmt.Errorf("failed to lookup srv record for %s in srvLookupTbl", cname) -} - -// div divides a byte slice into a slice of strings, each of which is of maximum -// 255 bytes length, which is the length limit per TXT record in DNS. -func div(b []byte) []string { - var r []string - for i := 0; i < len(b); i += txtBytesLimit { - if i+txtBytesLimit > len(b) { - r = append(r, string(b[i:])) - } else { - r = append(r, string(b[i:i+txtBytesLimit])) - } - } - return r -} - -// scfs contains an array of service config file string in JSON format. -// Notes about the scfs contents and usage: -// scfs contains 4 service config file JSON strings for testing. Inside each -// service config file, there are multiple choices. scfs[0:3] each contains 5 -// choices, and first 3 choices are nonmatching choices based on canarying rule, -// while the last two are matched choices. scfs[3] only contains 3 choices, and -// all of them are nonmatching based on canarying rule. For each of scfs[0:3], -// the eventually returned service config, which is from the first of the two -// matched choices, is stored in the corresponding scs element (e.g. -// scfs[0]->scs[0]). scfs and scs elements are used in pair to test the dns -// resolver functionality, with scfs as the input and scs used for validation of -// the output. For scfs[3], it corresponds to empty service config, since there -// isn't a matched choice. -var scfs = []string{ - `[ - { - "clientLanguage": [ - "CPP", - "JAVA" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "percentage": 0, - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientHostName": [ - "localhost" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientLanguage": [ - "GO" - ], - "percentage": 100, - "serviceConfig": { - "methodConfig": [ - { - "name": [ - { - "method": "bar" - } - ], - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 1024 - } - ] - } - }, - { - "serviceConfig": { - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "bar" - } - ], - "waitForReady": true - } - ] - } - } -]`, - `[ - { - "clientLanguage": [ - "CPP", - "JAVA" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "percentage": 0, - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientHostName": [ - "localhost" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientLanguage": [ - "GO" - ], - "percentage": 100, - "serviceConfig": { - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "bar" - } - ], - "waitForReady": true, - "timeout": "1s", - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 1024 - } - ] - } - }, - { - "serviceConfig": { - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "bar" - } - ], - "waitForReady": true - } - ] - } - } -]`, - `[ - { - "clientLanguage": [ - "CPP", - "JAVA" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "percentage": 0, - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientHostName": [ - "localhost" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientLanguage": [ - "GO" - ], - "percentage": 100, - "serviceConfig": { - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo" - } - ], - "waitForReady": true, - "timeout": "1s" - }, - { - "name": [ - { - "service": "bar" - } - ], - "waitForReady": false - } - ] - } - }, - { - "serviceConfig": { - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "bar" - } - ], - "waitForReady": true - } - ] - } - } -]`, - `[ - { - "clientLanguage": [ - "CPP", - "JAVA" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "percentage": 0, - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - }, - { - "clientHostName": [ - "localhost" - ], - "serviceConfig": { - "loadBalancingPolicy": "grpclb", - "methodConfig": [ - { - "name": [ - { - "service": "all" - } - ], - "timeout": "1s" - } - ] - } - } -]`, -} - -// scs contains an array of service config string in JSON format. -var scs = []string{ - `{ - "methodConfig": [ - { - "name": [ - { - "method": "bar" - } - ], - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 1024 - } - ] - }`, - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "bar" - } - ], - "waitForReady": true, - "timeout": "1s", - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 1024 - } - ] - }`, - `{ - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo" - } - ], - "waitForReady": true, - "timeout": "1s" - }, - { - "name": [ - { - "service": "bar" - } - ], - "waitForReady": false - } - ] - }`, -} - -// scLookupTbl is a set, which contains targets that have service config. Target -// not in this set should not have service config. -var scLookupTbl = map[string]bool{ - "foo.bar.com": true, - "srv.ipv4.single.fake": true, - "srv.ipv4.multi.fake": true, - "no.attribute": true, -} - -// generateSCF generates a slice of strings (aggregately representing a single -// service config file) for the input name, which mocks the result from a real -// DNS TXT record lookup. -func generateSCF(name string) []string { - var b []byte - switch name { - case "foo.bar.com": - b = []byte(scfs[0]) - case "srv.ipv4.single.fake": - b = []byte(scfs[1]) - case "srv.ipv4.multi.fake": - b = []byte(scfs[2]) - default: - b = []byte(scfs[3]) - } - if name == "no.attribute" { - return div(b) - } - return div(append([]byte(txtAttribute), b...)) -} - -// generateSC returns a service config string in JSON format for the input name. -func generateSC(name string) string { - _, cnt := scLookupTbl[name] - if !cnt || name == "no.attribute" { - return "" - } - switch name { - case "foo.bar.com": - return scs[0] - case "srv.ipv4.single.fake": - return scs[1] - case "srv.ipv4.multi.fake": - return scs[2] - default: - return "" - } -} - -var txtLookupTbl = struct { - sync.Mutex - tbl map[string][]string -}{ - tbl: map[string][]string{ - "foo.bar.com": generateSCF("foo.bar.com"), - "srv.ipv4.single.fake": generateSCF("srv.ipv4.single.fake"), - "srv.ipv4.multi.fake": generateSCF("srv.ipv4.multi.fake"), - "srv.ipv6.single.fake": generateSCF("srv.ipv6.single.fake"), - "srv.ipv6.multi.fake": generateSCF("srv.ipv6.multi.fake"), - "no.attribute": generateSCF("no.attribute"), - }, -} - -func txtLookup(host string) ([]string, error) { - txtLookupTbl.Lock() - defer txtLookupTbl.Unlock() - if scs, cnt := txtLookupTbl.tbl[host]; cnt { - return scs, nil - } - return nil, fmt.Errorf("failed to lookup TXT:%s resolution in txtLookupTbl", host) -} - -func TestResolve(t *testing.T) { - testDNSResolver(t) - testDNSResolveNow(t) - testIPResolver(t) -} - -func testDNSResolver(t *testing.T) { - defer leakcheck.Check(t) - tests := []struct { - target string - addrWant []resolver.Address - scWant string - }{ - { - "foo.bar.com", - []resolver.Address{{Addr: "1.2.3.4" + colonDefaultPort}, {Addr: "5.6.7.8" + colonDefaultPort}}, - generateSC("foo.bar.com"), - }, - { - "foo.bar.com:1234", - []resolver.Address{{Addr: "1.2.3.4:1234"}, {Addr: "5.6.7.8:1234"}}, - generateSC("foo.bar.com"), - }, - { - "srv.ipv4.single.fake", - []resolver.Address{{Addr: "1.2.3.4:1234", Type: resolver.GRPCLB, ServerName: "ipv4.single.fake"}, {Addr: "2.4.6.8" + colonDefaultPort}}, - generateSC("srv.ipv4.single.fake"), - }, - { - "srv.ipv4.multi.fake", - []resolver.Address{ - {Addr: "1.2.3.4:1234", Type: resolver.GRPCLB, ServerName: "ipv4.multi.fake"}, - {Addr: "5.6.7.8:1234", Type: resolver.GRPCLB, ServerName: "ipv4.multi.fake"}, - {Addr: "9.10.11.12:1234", Type: resolver.GRPCLB, ServerName: "ipv4.multi.fake"}, - }, - generateSC("srv.ipv4.multi.fake"), - }, - { - "srv.ipv6.single.fake", - []resolver.Address{{Addr: "[2607:f8b0:400a:801::1001]:1234", Type: resolver.GRPCLB, ServerName: "ipv6.single.fake"}}, - generateSC("srv.ipv6.single.fake"), - }, - { - "srv.ipv6.multi.fake", - []resolver.Address{ - {Addr: "[2607:f8b0:400a:801::1001]:1234", Type: resolver.GRPCLB, ServerName: "ipv6.multi.fake"}, - {Addr: "[2607:f8b0:400a:801::1002]:1234", Type: resolver.GRPCLB, ServerName: "ipv6.multi.fake"}, - {Addr: "[2607:f8b0:400a:801::1003]:1234", Type: resolver.GRPCLB, ServerName: "ipv6.multi.fake"}, - }, - generateSC("srv.ipv6.multi.fake"), - }, - { - "no.attribute", - nil, - generateSC("no.attribute"), - }, - } - - for _, a := range tests { - b := NewBuilder() - cc := &testClientConn{target: a.target} - r, err := b.Build(resolver.Target{Endpoint: a.target}, cc, resolver.BuildOption{}) - if err != nil { - t.Fatalf("%v\n", err) - } - var addrs []resolver.Address - var cnt int - for { - addrs, cnt = cc.getAddress() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - var sc string - for { - sc, cnt = cc.getSc() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(a.addrWant, addrs) { - t.Errorf("Resolved addresses of target: %q = %+v, want %+v\n", a.target, addrs, a.addrWant) - } - if !reflect.DeepEqual(a.scWant, sc) { - t.Errorf("Resolved service config of target: %q = %+v, want %+v\n", a.target, sc, a.scWant) - } - r.Close() - } -} - -func mutateTbl(target string) func() { - hostLookupTbl.Lock() - oldHostTblEntry := hostLookupTbl.tbl[target] - hostLookupTbl.tbl[target] = hostLookupTbl.tbl[target][:len(oldHostTblEntry)-1] - hostLookupTbl.Unlock() - txtLookupTbl.Lock() - oldTxtTblEntry := txtLookupTbl.tbl[target] - txtLookupTbl.tbl[target] = []string{""} - txtLookupTbl.Unlock() - - return func() { - hostLookupTbl.Lock() - hostLookupTbl.tbl[target] = oldHostTblEntry - hostLookupTbl.Unlock() - txtLookupTbl.Lock() - txtLookupTbl.tbl[target] = oldTxtTblEntry - txtLookupTbl.Unlock() - } -} - -func testDNSResolveNow(t *testing.T) { - defer leakcheck.Check(t) - tests := []struct { - target string - addrWant []resolver.Address - addrNext []resolver.Address - scWant string - scNext string - }{ - { - "foo.bar.com", - []resolver.Address{{Addr: "1.2.3.4" + colonDefaultPort}, {Addr: "5.6.7.8" + colonDefaultPort}}, - []resolver.Address{{Addr: "1.2.3.4" + colonDefaultPort}}, - generateSC("foo.bar.com"), - "", - }, - } - - for _, a := range tests { - b := NewBuilder() - cc := &testClientConn{target: a.target} - r, err := b.Build(resolver.Target{Endpoint: a.target}, cc, resolver.BuildOption{}) - if err != nil { - t.Fatalf("%v\n", err) - } - var addrs []resolver.Address - var cnt int - for { - addrs, cnt = cc.getAddress() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - var sc string - for { - sc, cnt = cc.getSc() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(a.addrWant, addrs) { - t.Errorf("Resolved addresses of target: %q = %+v, want %+v\n", a.target, addrs, a.addrWant) - } - if !reflect.DeepEqual(a.scWant, sc) { - t.Errorf("Resolved service config of target: %q = %+v, want %+v\n", a.target, sc, a.scWant) - } - revertTbl := mutateTbl(a.target) - r.ResolveNow(resolver.ResolveNowOption{}) - for { - addrs, cnt = cc.getAddress() - if cnt == 2 { - break - } - time.Sleep(time.Millisecond) - } - for { - sc, cnt = cc.getSc() - if cnt == 2 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(a.addrNext, addrs) { - t.Errorf("Resolved addresses of target: %q = %+v, want %+v\n", a.target, addrs, a.addrNext) - } - if !reflect.DeepEqual(a.scNext, sc) { - t.Errorf("Resolved service config of target: %q = %+v, want %+v\n", a.target, sc, a.scNext) - } - revertTbl() - r.Close() - } -} - -const colonDefaultPort = ":" + defaultPort - -func testIPResolver(t *testing.T) { - defer leakcheck.Check(t) - tests := []struct { - target string - want []resolver.Address - }{ - {"127.0.0.1", []resolver.Address{{Addr: "127.0.0.1" + colonDefaultPort}}}, - {"127.0.0.1:12345", []resolver.Address{{Addr: "127.0.0.1:12345"}}}, - {"::1", []resolver.Address{{Addr: "[::1]" + colonDefaultPort}}}, - {"[::1]:12345", []resolver.Address{{Addr: "[::1]:12345"}}}, - {"[::1]:", []resolver.Address{{Addr: "[::1]:443"}}}, - {"2001:db8:85a3::8a2e:370:7334", []resolver.Address{{Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]", []resolver.Address{{Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]:12345", []resolver.Address{{Addr: "[2001:db8:85a3::8a2e:370:7334]:12345"}}}, - {"[2001:db8::1]:http", []resolver.Address{{Addr: "[2001:db8::1]:http"}}}, - // TODO(yuxuanli): zone support? - } - - for _, v := range tests { - b := NewBuilder() - cc := &testClientConn{target: v.target} - r, err := b.Build(resolver.Target{Endpoint: v.target}, cc, resolver.BuildOption{}) - if err != nil { - t.Fatalf("%v\n", err) - } - var addrs []resolver.Address - var cnt int - for { - addrs, cnt = cc.getAddress() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(v.want, addrs) { - t.Errorf("Resolved addresses of target: %q = %+v, want %+v\n", v.target, addrs, v.want) - } - r.ResolveNow(resolver.ResolveNowOption{}) - for { - addrs, cnt = cc.getAddress() - if cnt == 2 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(v.want, addrs) { - t.Errorf("Resolved addresses of target: %q = %+v, want %+v\n", v.target, addrs, v.want) - } - r.Close() - } -} - -func TestResolveFunc(t *testing.T) { - defer leakcheck.Check(t) - tests := []struct { - addr string - want error - }{ - // TODO(yuxuanli): More false cases? - {"www.google.com", nil}, - {"foo.bar:12345", nil}, - {"127.0.0.1", nil}, - {"127.0.0.1:12345", nil}, - {"[::1]:80", nil}, - {"[2001:db8:a0b:12f0::1]:21", nil}, - {":80", nil}, - {"127.0.0...1:12345", nil}, - {"[fe80::1%lo0]:80", nil}, - {"golang.org:http", nil}, - {"[2001:db8::1]:http", nil}, - {":", nil}, - {"", errMissingAddr}, - {"[2001:db8:a0b:12f0::1", errForInvalidTarget}, - } - - b := NewBuilder() - for _, v := range tests { - cc := &testClientConn{target: v.addr} - r, err := b.Build(resolver.Target{Endpoint: v.addr}, cc, resolver.BuildOption{}) - if err == nil { - r.Close() - } - if !reflect.DeepEqual(err, v.want) { - t.Errorf("Build(%q, cc, resolver.BuildOption{}) = %v, want %v", v.addr, err, v.want) - } - } -} - -func TestDisableServiceConfig(t *testing.T) { - defer leakcheck.Check(t) - tests := []struct { - target string - scWant string - disableServiceConfig bool - }{ - { - "foo.bar.com", - generateSC("foo.bar.com"), - false, - }, - { - "foo.bar.com", - "", - true, - }, - } - - for _, a := range tests { - b := NewBuilder() - cc := &testClientConn{target: a.target} - r, err := b.Build(resolver.Target{Endpoint: a.target}, cc, resolver.BuildOption{DisableServiceConfig: a.disableServiceConfig}) - if err != nil { - t.Fatalf("%v\n", err) - } - var cnt int - var sc string - for { - sc, cnt = cc.getSc() - if cnt > 0 { - break - } - time.Sleep(time.Millisecond) - } - if !reflect.DeepEqual(a.scWant, sc) { - t.Errorf("Resolved service config of target: %q = %+v, want %+v\n", a.target, sc, a.scWant) - } - r.Close() - } -} diff --git a/examples/google.golang.org/grpc/resolver/dns/go17.go b/examples/google.golang.org/grpc/resolver/dns/go17.go deleted file mode 100755 index b466bc8..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/go17.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build go1.6, !go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import ( - "net" - - "golang.org/x/net/context" -) - -var ( - lookupHost = func(ctx context.Context, host string) ([]string, error) { return net.LookupHost(host) } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return net.LookupSRV(service, proto, name) - } - lookupTXT = func(ctx context.Context, name string) ([]string, error) { return net.LookupTXT(name) } -) diff --git a/examples/google.golang.org/grpc/resolver/dns/go17_test.go b/examples/google.golang.org/grpc/resolver/dns/go17_test.go deleted file mode 100755 index 21eaa88..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/go17_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build go1.6, !go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import ( - "fmt" - "net" - - "golang.org/x/net/context" -) - -var errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: missing ']' in address [2001:db8:a0b:12f0::1:443") - -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - oldLookupTXT := lookupTXT - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) - } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - lookupTXT = func(ctx context.Context, host string) ([]string, error) { - return txtLookup(host) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - lookupTXT = oldLookupTXT - } -} diff --git a/examples/google.golang.org/grpc/resolver/dns/go18.go b/examples/google.golang.org/grpc/resolver/dns/go18.go deleted file mode 100755 index fa34f14..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/go18.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import "net" - -var ( - lookupHost = net.DefaultResolver.LookupHost - lookupSRV = net.DefaultResolver.LookupSRV - lookupTXT = net.DefaultResolver.LookupTXT -) diff --git a/examples/google.golang.org/grpc/resolver/dns/go18_test.go b/examples/google.golang.org/grpc/resolver/dns/go18_test.go deleted file mode 100755 index b0149c8..0000000 --- a/examples/google.golang.org/grpc/resolver/dns/go18_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// +build go1.8 - -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package dns - -import ( - "context" - "fmt" - "net" -) - -var errForInvalidTarget = fmt.Errorf("invalid target address [2001:db8:a0b:12f0::1, error info: address [2001:db8:a0b:12f0::1:443: missing ']' in address") - -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - oldLookupTXT := lookupTXT - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) - } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - lookupTXT = func(ctx context.Context, host string) ([]string, error) { - return txtLookup(host) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - lookupTXT = oldLookupTXT - } -} diff --git a/examples/google.golang.org/grpc/resolver/manual/manual.go b/examples/google.golang.org/grpc/resolver/manual/manual.go deleted file mode 100755 index aeb7aed..0000000 --- a/examples/google.golang.org/grpc/resolver/manual/manual.go +++ /dev/null @@ -1,91 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package manual defines a resolver that can be used to manually send resolved -// addresses to ClientConn. -package manual - -import ( - "strconv" - "time" - - "google.golang.org/grpc/resolver" -) - -// NewBuilderWithScheme creates a new test resolver builder with the given scheme. -func NewBuilderWithScheme(scheme string) *Resolver { - return &Resolver{ - scheme: scheme, - } -} - -// Resolver is also a resolver builder. -// It's build() function always returns itself. -type Resolver struct { - scheme string - - // Fields actually belong to the resolver. - cc resolver.ClientConn - bootstrapAddrs []resolver.Address -} - -// InitialAddrs adds resolved addresses to the resolver so that -// NewAddress doesn't need to be explicitly called after Dial. -func (r *Resolver) InitialAddrs(addrs []resolver.Address) { - r.bootstrapAddrs = addrs -} - -// Build returns itself for Resolver, because it's both a builder and a resolver. -func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - r.cc = cc - if r.bootstrapAddrs != nil { - r.NewAddress(r.bootstrapAddrs) - } - return r, nil -} - -// Scheme returns the test scheme. -func (r *Resolver) Scheme() string { - return r.scheme -} - -// ResolveNow is a noop for Resolver. -func (*Resolver) ResolveNow(o resolver.ResolveNowOption) {} - -// Close is a noop for Resolver. -func (*Resolver) Close() {} - -// NewAddress calls cc.NewAddress. -func (r *Resolver) NewAddress(addrs []resolver.Address) { - r.cc.NewAddress(addrs) -} - -// NewServiceConfig calls cc.NewServiceConfig. -func (r *Resolver) NewServiceConfig(sc string) { - r.cc.NewServiceConfig(sc) -} - -// GenerateAndRegisterManualResolver generates a random scheme and a Resolver -// with it. It also registers this Resolver. -// It returns the Resolver and a cleanup function to unregister it. -func GenerateAndRegisterManualResolver() (*Resolver, func()) { - scheme := strconv.FormatInt(time.Now().UnixNano(), 36) - r := NewBuilderWithScheme(scheme) - resolver.Register(r) - return r, func() { resolver.UnregisterForTesting(scheme) } -} diff --git a/examples/google.golang.org/grpc/resolver/passthrough/passthrough.go b/examples/google.golang.org/grpc/resolver/passthrough/passthrough.go deleted file mode 100755 index b76010d..0000000 --- a/examples/google.golang.org/grpc/resolver/passthrough/passthrough.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package passthrough implements a pass-through resolver. It sends the target -// name without scheme back to gRPC as resolved address. -package passthrough - -import "google.golang.org/grpc/resolver" - -const scheme = "passthrough" - -type passthroughBuilder struct{} - -func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { - r := &passthroughResolver{ - target: target, - cc: cc, - } - r.start() - return r, nil -} - -func (*passthroughBuilder) Scheme() string { - return scheme -} - -type passthroughResolver struct { - target resolver.Target - cc resolver.ClientConn -} - -func (r *passthroughResolver) start() { - r.cc.NewAddress([]resolver.Address{{Addr: r.target.Endpoint}}) -} - -func (*passthroughResolver) ResolveNow(o resolver.ResolveNowOption) {} - -func (*passthroughResolver) Close() {} - -func init() { - resolver.Register(&passthroughBuilder{}) -} diff --git a/examples/google.golang.org/grpc/resolver/resolver.go b/examples/google.golang.org/grpc/resolver/resolver.go deleted file mode 100755 index 506afac..0000000 --- a/examples/google.golang.org/grpc/resolver/resolver.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package resolver defines APIs for name resolution in gRPC. -// All APIs in this package are experimental. -package resolver - -var ( - // m is a map from scheme to resolver builder. - m = make(map[string]Builder) - // defaultScheme is the default scheme to use. - defaultScheme = "passthrough" -) - -// TODO(bar) install dns resolver in init(){}. - -// Register registers the resolver builder to the resolver map. b.Scheme will be -// used as the scheme registered with this builder. -// -// NOTE: this function must only be called during initialization time (i.e. in -// an init() function), and is not thread-safe. If multiple Resolvers are -// registered with the same name, the one registered last will take effect. -func Register(b Builder) { - m[b.Scheme()] = b -} - -// Get returns the resolver builder registered with the given scheme. -// -// If no builder is register with the scheme, nil will be returned. -func Get(scheme string) Builder { - if b, ok := m[scheme]; ok { - return b - } - return nil -} - -// SetDefaultScheme sets the default scheme that will be used. -// The default default scheme is "passthrough". -func SetDefaultScheme(scheme string) { - defaultScheme = scheme -} - -// GetDefaultScheme gets the default scheme that will be used. -func GetDefaultScheme() string { - return defaultScheme -} - -// AddressType indicates the address type returned by name resolution. -type AddressType uint8 - -const ( - // Backend indicates the address is for a backend server. - Backend AddressType = iota - // GRPCLB indicates the address is for a grpclb load balancer. - GRPCLB -) - -// Address represents a server the client connects to. -// This is the EXPERIMENTAL API and may be changed or extended in the future. -type Address struct { - // Addr is the server address on which a connection will be established. - Addr string - // Type is the type of this address. - Type AddressType - // ServerName is the name of this address. - // - // e.g. if Type is GRPCLB, ServerName should be the name of the remote load - // balancer, not the name of the backend. - ServerName string - // Metadata is the information associated with Addr, which may be used - // to make load balancing decision. - Metadata interface{} -} - -// BuildOption includes additional information for the builder to create -// the resolver. -type BuildOption struct { - // DisableServiceConfig indicates whether resolver should fetch service config data. - DisableServiceConfig bool -} - -// ClientConn contains the callbacks for resolver to notify any updates -// to the gRPC ClientConn. -// -// This interface is to be implemented by gRPC. Users should not need a -// brand new implementation of this interface. For the situations like -// testing, the new implementation should embed this interface. This allows -// gRPC to add new methods to this interface. -type ClientConn interface { - // NewAddress is called by resolver to notify ClientConn a new list - // of resolved addresses. - // The address list should be the complete list of resolved addresses. - NewAddress(addresses []Address) - // NewServiceConfig is called by resolver to notify ClientConn a new - // service config. The service config should be provided as a json string. - NewServiceConfig(serviceConfig string) -} - -// Target represents a target for gRPC, as specified in: -// https://github.com/grpc/grpc/blob/master/doc/naming.md. -type Target struct { - Scheme string - Authority string - Endpoint string -} - -// Builder creates a resolver that will be used to watch name resolution updates. -type Builder interface { - // Build creates a new resolver for the given target. - // - // gRPC dial calls Build synchronously, and fails if the returned error is - // not nil. - Build(target Target, cc ClientConn, opts BuildOption) (Resolver, error) - // Scheme returns the scheme supported by this resolver. - // Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md. - Scheme() string -} - -// ResolveNowOption includes additional information for ResolveNow. -type ResolveNowOption struct{} - -// Resolver watches for the updates on the specified target. -// Updates include address updates and service config updates. -type Resolver interface { - // ResolveNow will be called by gRPC to try to resolve the target name - // again. It's just a hint, resolver can ignore this if it's not necessary. - // - // It could be called multiple times concurrently. - ResolveNow(ResolveNowOption) - // Close closes the resolver. - Close() -} - -// UnregisterForTesting removes the resolver builder with the given scheme from the -// resolver map. -// This function is for testing only. -func UnregisterForTesting(scheme string) { - delete(m, scheme) -} diff --git a/examples/google.golang.org/grpc/resolver_conn_wrapper.go b/examples/google.golang.org/grpc/resolver_conn_wrapper.go deleted file mode 100755 index 494d693..0000000 --- a/examples/google.golang.org/grpc/resolver_conn_wrapper.go +++ /dev/null @@ -1,158 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "strings" - - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -// ccResolverWrapper is a wrapper on top of cc for resolvers. -// It implements resolver.ClientConnection interface. -type ccResolverWrapper struct { - cc *ClientConn - resolver resolver.Resolver - addrCh chan []resolver.Address - scCh chan string - done chan struct{} -} - -// split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns ("", s, false) instead. -func split2(s, sep string) (string, string, bool) { - spl := strings.SplitN(s, sep, 2) - if len(spl) < 2 { - return "", "", false - } - return spl[0], spl[1], true -} - -// parseTarget splits target into a struct containing scheme, authority and -// endpoint. -// -// If target is not a valid scheme://authority/endpoint, it returns {Endpoint: -// target}. -func parseTarget(target string) (ret resolver.Target) { - var ok bool - ret.Scheme, ret.Endpoint, ok = split2(target, "://") - if !ok { - return resolver.Target{Endpoint: target} - } - ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") - if !ok { - return resolver.Target{Endpoint: target} - } - return ret -} - -// newCCResolverWrapper parses cc.target for scheme and gets the resolver -// builder for this scheme and builds the resolver. The monitoring goroutine -// for it is not started yet and can be created by calling start(). -// -// If withResolverBuilder dial option is set, the specified resolver will be -// used instead. -func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { - rb := cc.dopts.resolverBuilder - if rb == nil { - return nil, fmt.Errorf("could not get resolver for scheme: %q", cc.parsedTarget.Scheme) - } - - ccr := &ccResolverWrapper{ - cc: cc, - addrCh: make(chan []resolver.Address, 1), - scCh: make(chan string, 1), - done: make(chan struct{}), - } - - var err error - ccr.resolver, err = rb.Build(cc.parsedTarget, ccr, resolver.BuildOption{DisableServiceConfig: cc.dopts.disableServiceConfig}) - if err != nil { - return nil, err - } - return ccr, nil -} - -func (ccr *ccResolverWrapper) start() { - go ccr.watcher() -} - -// watcher processes address updates and service config updates sequentially. -// Otherwise, we need to resolve possible races between address and service -// config (e.g. they specify different balancer types). -func (ccr *ccResolverWrapper) watcher() { - for { - select { - case <-ccr.done: - return - default: - } - - select { - case addrs := <-ccr.addrCh: - select { - case <-ccr.done: - return - default: - } - grpclog.Infof("ccResolverWrapper: sending new addresses to cc: %v", addrs) - ccr.cc.handleResolvedAddrs(addrs, nil) - case sc := <-ccr.scCh: - select { - case <-ccr.done: - return - default: - } - grpclog.Infof("ccResolverWrapper: got new service config: %v", sc) - ccr.cc.handleServiceConfig(sc) - case <-ccr.done: - return - } - } -} - -func (ccr *ccResolverWrapper) resolveNow(o resolver.ResolveNowOption) { - ccr.resolver.ResolveNow(o) -} - -func (ccr *ccResolverWrapper) close() { - ccr.resolver.Close() - close(ccr.done) -} - -// NewAddress is called by the resolver implemenetion to send addresses to gRPC. -func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { - select { - case <-ccr.addrCh: - default: - } - ccr.addrCh <- addrs -} - -// NewServiceConfig is called by the resolver implemenetion to send service -// configs to gRPC. -func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { - select { - case <-ccr.scCh: - default: - } - ccr.scCh <- sc -} diff --git a/examples/google.golang.org/grpc/resolver_conn_wrapper_test.go b/examples/google.golang.org/grpc/resolver_conn_wrapper_test.go deleted file mode 100755 index 6f1367a..0000000 --- a/examples/google.golang.org/grpc/resolver_conn_wrapper_test.go +++ /dev/null @@ -1,113 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "net" - "testing" - "time" - - "google.golang.org/grpc/resolver" -) - -func TestParseTarget(t *testing.T) { - for _, test := range []resolver.Target{ - {Scheme: "dns", Authority: "", Endpoint: "google.com"}, - {Scheme: "dns", Authority: "a.server.com", Endpoint: "google.com"}, - {Scheme: "dns", Authority: "a.server.com", Endpoint: "google.com/?a=b"}, - {Scheme: "passthrough", Authority: "", Endpoint: "/unix/socket/address"}, - } { - str := test.Scheme + "://" + test.Authority + "/" + test.Endpoint - got := parseTarget(str) - if got != test { - t.Errorf("parseTarget(%q) = %+v, want %+v", str, got, test) - } - } -} - -func TestParseTargetString(t *testing.T) { - for _, test := range []struct { - targetStr string - want resolver.Target - }{ - {targetStr: "", want: resolver.Target{Scheme: "", Authority: "", Endpoint: ""}}, - {targetStr: ":///", want: resolver.Target{Scheme: "", Authority: "", Endpoint: ""}}, - {targetStr: "a:///", want: resolver.Target{Scheme: "a", Authority: "", Endpoint: ""}}, - {targetStr: "://a/", want: resolver.Target{Scheme: "", Authority: "a", Endpoint: ""}}, - {targetStr: ":///a", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a"}}, - {targetStr: "a://b/", want: resolver.Target{Scheme: "a", Authority: "b", Endpoint: ""}}, - {targetStr: "a:///b", want: resolver.Target{Scheme: "a", Authority: "", Endpoint: "b"}}, - {targetStr: "://a/b", want: resolver.Target{Scheme: "", Authority: "a", Endpoint: "b"}}, - {targetStr: "a://b/c", want: resolver.Target{Scheme: "a", Authority: "b", Endpoint: "c"}}, - {targetStr: "dns:///google.com", want: resolver.Target{Scheme: "dns", Authority: "", Endpoint: "google.com"}}, - {targetStr: "dns://a.server.com/google.com", want: resolver.Target{Scheme: "dns", Authority: "a.server.com", Endpoint: "google.com"}}, - {targetStr: "dns://a.server.com/google.com/?a=b", want: resolver.Target{Scheme: "dns", Authority: "a.server.com", Endpoint: "google.com/?a=b"}}, - - {targetStr: "/", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "/"}}, - {targetStr: "google.com", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "google.com"}}, - {targetStr: "google.com/?a=b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "google.com/?a=b"}}, - {targetStr: "/unix/socket/address", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "/unix/socket/address"}}, - - // If we can only parse part of the target. - {targetStr: "://", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "://"}}, - {targetStr: "unix://domain", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "unix://domain"}}, - {targetStr: "a:b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a:b"}}, - {targetStr: "a/b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a/b"}}, - {targetStr: "a:/b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a:/b"}}, - {targetStr: "a//b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a//b"}}, - {targetStr: "a://b", want: resolver.Target{Scheme: "", Authority: "", Endpoint: "a://b"}}, - } { - got := parseTarget(test.targetStr) - if got != test.want { - t.Errorf("parseTarget(%q) = %+v, want %+v", test.targetStr, got, test.want) - } - } -} - -// The target string with unknown scheme should be kept unchanged and passed to -// the dialer. -func TestDialParseTargetUnknownScheme(t *testing.T) { - for _, test := range []struct { - targetStr string - want string - }{ - {"/unix/socket/address", "/unix/socket/address"}, - - // Special test for "unix:///". - {"unix:///unix/socket/address", "unix:///unix/socket/address"}, - - // For known scheme. - {"passthrough://a.server.com/google.com", "google.com"}, - } { - dialStrCh := make(chan string, 1) - cc, err := Dial(test.targetStr, WithInsecure(), WithDialer(func(t string, _ time.Duration) (net.Conn, error) { - dialStrCh <- t - return nil, fmt.Errorf("test dialer, always error") - })) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - got := <-dialStrCh - cc.Close() - if got != test.want { - t.Errorf("Dial(%q), dialer got %q, want %q", test.targetStr, got, test.want) - } - } -} diff --git a/examples/google.golang.org/grpc/rpc_util.go b/examples/google.golang.org/grpc/rpc_util.go deleted file mode 100755 index 033801f..0000000 --- a/examples/google.golang.org/grpc/rpc_util.go +++ /dev/null @@ -1,741 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "bytes" - "compress/gzip" - "encoding/binary" - "fmt" - "io" - "io/ioutil" - "math" - "net/url" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/encoding/proto" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// Compressor defines the interface gRPC uses to compress a message. -// -// Deprecated: use package encoding. -type Compressor interface { - // Do compresses p into w. - Do(w io.Writer, p []byte) error - // Type returns the compression algorithm the Compressor uses. - Type() string -} - -type gzipCompressor struct { - pool sync.Pool -} - -// NewGZIPCompressor creates a Compressor based on GZIP. -// -// Deprecated: use package encoding/gzip. -func NewGZIPCompressor() Compressor { - c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression) - return c -} - -// NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead -// of assuming DefaultCompression. -// -// The error returned will be nil if the level is valid. -// -// Deprecated: use package encoding/gzip. -func NewGZIPCompressorWithLevel(level int) (Compressor, error) { - if level < gzip.DefaultCompression || level > gzip.BestCompression { - return nil, fmt.Errorf("grpc: invalid compression level: %d", level) - } - return &gzipCompressor{ - pool: sync.Pool{ - New: func() interface{} { - w, err := gzip.NewWriterLevel(ioutil.Discard, level) - if err != nil { - panic(err) - } - return w - }, - }, - }, nil -} - -func (c *gzipCompressor) Do(w io.Writer, p []byte) error { - z := c.pool.Get().(*gzip.Writer) - defer c.pool.Put(z) - z.Reset(w) - if _, err := z.Write(p); err != nil { - return err - } - return z.Close() -} - -func (c *gzipCompressor) Type() string { - return "gzip" -} - -// Decompressor defines the interface gRPC uses to decompress a message. -// -// Deprecated: use package encoding. -type Decompressor interface { - // Do reads the data from r and uncompress them. - Do(r io.Reader) ([]byte, error) - // Type returns the compression algorithm the Decompressor uses. - Type() string -} - -type gzipDecompressor struct { - pool sync.Pool -} - -// NewGZIPDecompressor creates a Decompressor based on GZIP. -// -// Deprecated: use package encoding/gzip. -func NewGZIPDecompressor() Decompressor { - return &gzipDecompressor{} -} - -func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { - var z *gzip.Reader - switch maybeZ := d.pool.Get().(type) { - case nil: - newZ, err := gzip.NewReader(r) - if err != nil { - return nil, err - } - z = newZ - case *gzip.Reader: - z = maybeZ - if err := z.Reset(r); err != nil { - d.pool.Put(z) - return nil, err - } - } - - defer func() { - z.Close() - d.pool.Put(z) - }() - return ioutil.ReadAll(z) -} - -func (d *gzipDecompressor) Type() string { - return "gzip" -} - -// callInfo contains all related configuration and information about an RPC. -type callInfo struct { - compressorType string - failFast bool - stream *clientStream - traceInfo traceInfo // in trace.go - maxReceiveMessageSize *int - maxSendMessageSize *int - creds credentials.PerRPCCredentials - contentSubtype string - codec baseCodec -} - -func defaultCallInfo() *callInfo { - return &callInfo{failFast: true} -} - -// CallOption configures a Call before it starts or extracts information from -// a Call after it completes. -type CallOption interface { - // before is called before the call is sent to any server. If before - // returns a non-nil error, the RPC fails with that error. - before(*callInfo) error - - // after is called after the call has completed. after cannot return an - // error, so any failures should be reported via output parameters. - after(*callInfo) -} - -// EmptyCallOption does not alter the Call configuration. -// It can be embedded in another structure to carry satellite data for use -// by interceptors. -type EmptyCallOption struct{} - -func (EmptyCallOption) before(*callInfo) error { return nil } -func (EmptyCallOption) after(*callInfo) {} - -// Header returns a CallOptions that retrieves the header metadata -// for a unary RPC. -func Header(md *metadata.MD) CallOption { - return HeaderCallOption{HeaderAddr: md} -} - -// HeaderCallOption is a CallOption for collecting response header metadata. -// The metadata field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type HeaderCallOption struct { - HeaderAddr *metadata.MD -} - -func (o HeaderCallOption) before(c *callInfo) error { return nil } -func (o HeaderCallOption) after(c *callInfo) { - if c.stream != nil { - *o.HeaderAddr, _ = c.stream.Header() - } -} - -// Trailer returns a CallOptions that retrieves the trailer metadata -// for a unary RPC. -func Trailer(md *metadata.MD) CallOption { - return TrailerCallOption{TrailerAddr: md} -} - -// TrailerCallOption is a CallOption for collecting response trailer metadata. -// The metadata field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type TrailerCallOption struct { - TrailerAddr *metadata.MD -} - -func (o TrailerCallOption) before(c *callInfo) error { return nil } -func (o TrailerCallOption) after(c *callInfo) { - if c.stream != nil { - *o.TrailerAddr = c.stream.Trailer() - } -} - -// Peer returns a CallOption that retrieves peer information for a unary RPC. -// The peer field will be populated *after* the RPC completes. -func Peer(p *peer.Peer) CallOption { - return PeerCallOption{PeerAddr: p} -} - -// PeerCallOption is a CallOption for collecting the identity of the remote -// peer. The peer field will be populated *after* the RPC completes. -// This is an EXPERIMENTAL API. -type PeerCallOption struct { - PeerAddr *peer.Peer -} - -func (o PeerCallOption) before(c *callInfo) error { return nil } -func (o PeerCallOption) after(c *callInfo) { - if c.stream != nil { - if x, ok := peer.FromContext(c.stream.Context()); ok { - *o.PeerAddr = *x - } - } -} - -// FailFast configures the action to take when an RPC is attempted on broken -// connections or unreachable servers. If failFast is true, the RPC will fail -// immediately. Otherwise, the RPC client will block the call until a -// connection is available (or the call is canceled or times out) and will -// retry the call if it fails due to a transient error. gRPC will not retry if -// data was written to the wire unless the server indicates it did not process -// the data. Please refer to -// https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md. -// -// By default, RPCs are "Fail Fast". -func FailFast(failFast bool) CallOption { - return FailFastCallOption{FailFast: failFast} -} - -// FailFastCallOption is a CallOption for indicating whether an RPC should fail -// fast or not. -// This is an EXPERIMENTAL API. -type FailFastCallOption struct { - FailFast bool -} - -func (o FailFastCallOption) before(c *callInfo) error { - c.failFast = o.FailFast - return nil -} -func (o FailFastCallOption) after(c *callInfo) {} - -// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive. -func MaxCallRecvMsgSize(s int) CallOption { - return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s} -} - -// MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can receive. -// This is an EXPERIMENTAL API. -type MaxRecvMsgSizeCallOption struct { - MaxRecvMsgSize int -} - -func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { - c.maxReceiveMessageSize = &o.MaxRecvMsgSize - return nil -} -func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {} - -// MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send. -func MaxCallSendMsgSize(s int) CallOption { - return MaxSendMsgSizeCallOption{MaxSendMsgSize: s} -} - -// MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can send. -// This is an EXPERIMENTAL API. -type MaxSendMsgSizeCallOption struct { - MaxSendMsgSize int -} - -func (o MaxSendMsgSizeCallOption) before(c *callInfo) error { - c.maxSendMessageSize = &o.MaxSendMsgSize - return nil -} -func (o MaxSendMsgSizeCallOption) after(c *callInfo) {} - -// PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials -// for a call. -func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { - return PerRPCCredsCallOption{Creds: creds} -} - -// PerRPCCredsCallOption is a CallOption that indicates the per-RPC -// credentials to use for the call. -// This is an EXPERIMENTAL API. -type PerRPCCredsCallOption struct { - Creds credentials.PerRPCCredentials -} - -func (o PerRPCCredsCallOption) before(c *callInfo) error { - c.creds = o.Creds - return nil -} -func (o PerRPCCredsCallOption) after(c *callInfo) {} - -// UseCompressor returns a CallOption which sets the compressor used when -// sending the request. If WithCompressor is also set, UseCompressor has -// higher priority. -// -// This API is EXPERIMENTAL. -func UseCompressor(name string) CallOption { - return CompressorCallOption{CompressorType: name} -} - -// CompressorCallOption is a CallOption that indicates the compressor to use. -// This is an EXPERIMENTAL API. -type CompressorCallOption struct { - CompressorType string -} - -func (o CompressorCallOption) before(c *callInfo) error { - c.compressorType = o.CompressorType - return nil -} -func (o CompressorCallOption) after(c *callInfo) {} - -// CallContentSubtype returns a CallOption that will set the content-subtype -// for a call. For example, if content-subtype is "json", the Content-Type over -// the wire will be "application/grpc+json". The content-subtype is converted -// to lowercase before being included in Content-Type. See Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// If CallCustomCodec is not also used, the content-subtype will be used to -// look up the Codec to use in the registry controlled by RegisterCodec. See -// the documentation on RegisterCodec for details on registration. The lookup -// of content-subtype is case-insensitive. If no such Codec is found, the call -// will result in an error with code codes.Internal. -// -// If CallCustomCodec is also used, that Codec will be used for all request and -// response messages, with the content-subtype set to the given contentSubtype -// here for requests. -func CallContentSubtype(contentSubtype string) CallOption { - return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)} -} - -// ContentSubtypeCallOption is a CallOption that indicates the content-subtype -// used for marshaling messages. -// This is an EXPERIMENTAL API. -type ContentSubtypeCallOption struct { - ContentSubtype string -} - -func (o ContentSubtypeCallOption) before(c *callInfo) error { - c.contentSubtype = o.ContentSubtype - return nil -} -func (o ContentSubtypeCallOption) after(c *callInfo) {} - -// CallCustomCodec returns a CallOption that will set the given Codec to be -// used for all request and response messages for a call. The result of calling -// String() will be used as the content-subtype in a case-insensitive manner. -// -// See Content-Type on -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. Also see the documentation on RegisterCodec and -// CallContentSubtype for more details on the interaction between Codec and -// content-subtype. -// -// This function is provided for advanced users; prefer to use only -// CallContentSubtype to select a registered codec instead. -func CallCustomCodec(codec Codec) CallOption { - return CustomCodecCallOption{Codec: codec} -} - -// CustomCodecCallOption is a CallOption that indicates the codec used for -// marshaling messages. -// This is an EXPERIMENTAL API. -type CustomCodecCallOption struct { - Codec Codec -} - -func (o CustomCodecCallOption) before(c *callInfo) error { - c.codec = o.Codec - return nil -} -func (o CustomCodecCallOption) after(c *callInfo) {} - -// The format of the payload: compressed or not? -type payloadFormat uint8 - -const ( - compressionNone payloadFormat = 0 // no compression - compressionMade payloadFormat = 1 // compressed -) - -// parser reads complete gRPC messages from the underlying reader. -type parser struct { - // r is the underlying reader. - // See the comment on recvMsg for the permissible - // error types. - r io.Reader - - // The header of a gRPC message. Find more detail at - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md - header [5]byte -} - -// recvMsg reads a complete gRPC message from the stream. -// -// It returns the message and its payload (compression/encoding) -// format. The caller owns the returned msg memory. -// -// If there is an error, possible values are: -// * io.EOF, when no messages remain -// * io.ErrUnexpectedEOF -// * of type transport.ConnectionError -// * of type transport.StreamError -// No other error values or types must be returned, which also means -// that the underlying io.Reader must not return an incompatible -// error. -func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byte, err error) { - if _, err := p.r.Read(p.header[:]); err != nil { - return 0, nil, err - } - - pf = payloadFormat(p.header[0]) - length := binary.BigEndian.Uint32(p.header[1:]) - - if length == 0 { - return pf, nil, nil - } - if int64(length) > int64(maxInt) { - return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt) - } - if int(length) > maxReceiveMessageSize { - return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) - } - // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead - // of making it for each message: - msg = make([]byte, int(length)) - if _, err := p.r.Read(msg); err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return 0, nil, err - } - return pf, msg, nil -} - -// encode serializes msg and returns a buffer containing the message, or an -// error if it is too large to be transmitted by grpc. If msg is nil, it -// generates an empty message. -func encode(c baseCodec, msg interface{}) ([]byte, error) { - if msg == nil { // NOTE: typed nils will not be caught by this check - return nil, nil - } - b, err := c.Marshal(msg) - if err != nil { - return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) - } - if uint(len(b)) > math.MaxUint32 { - return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) - } - return b, nil -} - -// compress returns the input bytes compressed by compressor or cp. If both -// compressors are nil, returns nil. -// -// TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor. -func compress(in []byte, cp Compressor, compressor encoding.Compressor) ([]byte, error) { - if compressor == nil && cp == nil { - return nil, nil - } - wrapErr := func(err error) error { - return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) - } - cbuf := &bytes.Buffer{} - if compressor != nil { - z, _ := compressor.Compress(cbuf) - if _, err := z.Write(in); err != nil { - return nil, wrapErr(err) - } - if err := z.Close(); err != nil { - return nil, wrapErr(err) - } - } else { - if err := cp.Do(cbuf, in); err != nil { - return nil, wrapErr(err) - } - } - return cbuf.Bytes(), nil -} - -const ( - payloadLen = 1 - sizeLen = 4 - headerLen = payloadLen + sizeLen -) - -// msgHeader returns a 5-byte header for the message being transmitted and the -// payload, which is compData if non-nil or data otherwise. -func msgHeader(data, compData []byte) (hdr []byte, payload []byte) { - hdr = make([]byte, headerLen) - if compData != nil { - hdr[0] = byte(compressionMade) - data = compData - } else { - hdr[0] = byte(compressionNone) - } - - // Write length of payload into buf - binary.BigEndian.PutUint32(hdr[payloadLen:], uint32(len(data))) - return hdr, data -} - -func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload { - return &stats.OutPayload{ - Client: client, - Payload: msg, - Data: data, - Length: len(data), - WireLength: len(payload) + headerLen, - SentTime: t, - } -} - -func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status { - switch pf { - case compressionNone: - case compressionMade: - if recvCompress == "" || recvCompress == encoding.Identity { - return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding") - } - if !haveCompressor { - return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) - } - default: - return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf) - } - return nil -} - -// For the two compressor parameters, both should not be set, but if they are, -// dc takes precedence over compressor. -// TODO(dfawley): wrap the old compressor/decompressor using the new API? -func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload, compressor encoding.Compressor) error { - pf, d, err := p.recvMsg(maxReceiveMessageSize) - if err != nil { - return err - } - if inPayload != nil { - inPayload.WireLength = len(d) - } - - if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil { - return st.Err() - } - - if pf == compressionMade { - // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor, - // use this decompressor as the default. - if dc != nil { - d, err = dc.Do(bytes.NewReader(d)) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } else { - dcReader, err := compressor.Decompress(bytes.NewReader(d)) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - d, err = ioutil.ReadAll(dcReader) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } - } - if len(d) > maxReceiveMessageSize { - // TODO: Revisit the error code. Currently keep it consistent with java - // implementation. - return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize) - } - if err := c.Unmarshal(d, m); err != nil { - return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err) - } - if inPayload != nil { - inPayload.RecvTime = time.Now() - inPayload.Payload = m - // TODO truncate large payload. - inPayload.Data = d - inPayload.Length = len(d) - } - return nil -} - -type rpcInfo struct { - failfast bool -} - -type rpcInfoContextKey struct{} - -func newContextWithRPCInfo(ctx context.Context, failfast bool) context.Context { - return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{failfast: failfast}) -} - -func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) { - s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo) - return -} - -// Code returns the error code for err if it was produced by the rpc system. -// Otherwise, it returns codes.Unknown. -// -// Deprecated: use status.FromError and Code method instead. -func Code(err error) codes.Code { - if s, ok := status.FromError(err); ok { - return s.Code() - } - return codes.Unknown -} - -// ErrorDesc returns the error description of err if it was produced by the rpc system. -// Otherwise, it returns err.Error() or empty string when err is nil. -// -// Deprecated: use status.FromError and Message method instead. -func ErrorDesc(err error) string { - if s, ok := status.FromError(err); ok { - return s.Message() - } - return err.Error() -} - -// Errorf returns an error containing an error code and a description; -// Errorf returns nil if c is OK. -// -// Deprecated: use status.Errorf instead. -func Errorf(c codes.Code, format string, a ...interface{}) error { - return status.Errorf(c, format, a...) -} - -// setCallInfoCodec should only be called after CallOptions have been applied. -func setCallInfoCodec(c *callInfo) error { - if c.codec != nil { - // codec was already set by a CallOption; use it. - return nil - } - - if c.contentSubtype == "" { - // No codec specified in CallOptions; use proto by default. - c.codec = encoding.GetCodec(proto.Name) - return nil - } - - // c.contentSubtype is already lowercased in CallContentSubtype - c.codec = encoding.GetCodec(c.contentSubtype) - if c.codec == nil { - return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype) - } - return nil -} - -// parseDialTarget returns the network and address to pass to dialer -func parseDialTarget(target string) (net string, addr string) { - net = "tcp" - - m1 := strings.Index(target, ":") - m2 := strings.Index(target, ":/") - - // handle unix:addr which will fail with url.Parse - if m1 >= 0 && m2 < 0 { - if n := target[0:m1]; n == "unix" { - net = n - addr = target[m1+1:] - return net, addr - } - } - if m2 >= 0 { - t, err := url.Parse(target) - if err != nil { - return net, target - } - scheme := t.Scheme - addr = t.Path - if scheme == "unix" { - net = scheme - if addr == "" { - addr = t.Host - } - return net, addr - } - } - - return net, target -} - -// The SupportPackageIsVersion variables are referenced from generated protocol -// buffer files to ensure compatibility with the gRPC version used. The latest -// support package version is 5. -// -// Older versions are kept for compatibility. They may be removed if -// compatibility cannot be maintained. -// -// These constants should not be referenced from any other code. -const ( - SupportPackageIsVersion3 = true - SupportPackageIsVersion4 = true - SupportPackageIsVersion5 = true -) - -const grpcUA = "grpc-go/" + Version diff --git a/examples/google.golang.org/grpc/rpc_util_test.go b/examples/google.golang.org/grpc/rpc_util_test.go deleted file mode 100755 index f28cff2..0000000 --- a/examples/google.golang.org/grpc/rpc_util_test.go +++ /dev/null @@ -1,288 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "bytes" - "compress/gzip" - "io" - "math" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/encoding" - protoenc "google.golang.org/grpc/encoding/proto" - "google.golang.org/grpc/status" - perfpb "google.golang.org/grpc/test/codec_perf" - "google.golang.org/grpc/transport" -) - -type fullReader struct { - reader io.Reader -} - -func (f fullReader) Read(p []byte) (int, error) { - return io.ReadFull(f.reader, p) -} - -var _ CallOption = EmptyCallOption{} // ensure EmptyCallOption implements the interface - -func TestSimpleParsing(t *testing.T) { - bigMsg := bytes.Repeat([]byte{'x'}, 1<<24) - for _, test := range []struct { - // input - p []byte - // outputs - err error - b []byte - pt payloadFormat - }{ - {nil, io.EOF, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 0}, nil, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 1, 'a'}, nil, []byte{'a'}, compressionNone}, - {[]byte{1, 0}, io.ErrUnexpectedEOF, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 10, 'a'}, io.ErrUnexpectedEOF, nil, compressionNone}, - // Check that messages with length >= 2^24 are parsed. - {append([]byte{0, 1, 0, 0, 0}, bigMsg...), nil, bigMsg, compressionNone}, - } { - buf := fullReader{bytes.NewReader(test.p)} - parser := &parser{r: buf} - pt, b, err := parser.recvMsg(math.MaxInt32) - if err != test.err || !bytes.Equal(b, test.b) || pt != test.pt { - t.Fatalf("parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, %v", test.p, pt, b, err, test.pt, test.b, test.err) - } - } -} - -func TestMultipleParsing(t *testing.T) { - // Set a byte stream consists of 3 messages with their headers. - p := []byte{0, 0, 0, 0, 1, 'a', 0, 0, 0, 0, 2, 'b', 'c', 0, 0, 0, 0, 1, 'd'} - b := fullReader{bytes.NewReader(p)} - parser := &parser{r: b} - - wantRecvs := []struct { - pt payloadFormat - data []byte - }{ - {compressionNone, []byte("a")}, - {compressionNone, []byte("bc")}, - {compressionNone, []byte("d")}, - } - for i, want := range wantRecvs { - pt, data, err := parser.recvMsg(math.MaxInt32) - if err != nil || pt != want.pt || !reflect.DeepEqual(data, want.data) { - t.Fatalf("after %d calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, ", - i, p, pt, data, err, want.pt, want.data) - } - } - - pt, data, err := parser.recvMsg(math.MaxInt32) - if err != io.EOF { - t.Fatalf("after %d recvMsgs calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant _, _, %v", - len(wantRecvs), p, pt, data, err, io.EOF) - } -} - -func TestEncode(t *testing.T) { - for _, test := range []struct { - // input - msg proto.Message - // outputs - hdr []byte - data []byte - err error - }{ - {nil, []byte{0, 0, 0, 0, 0}, []byte{}, nil}, - } { - data, err := encode(encoding.GetCodec(protoenc.Name), test.msg) - if err != test.err || !bytes.Equal(data, test.data) { - t.Errorf("encode(_, %v) = %v, %v; want %v, %v", test.msg, data, err, test.data, test.err) - continue - } - if hdr, _ := msgHeader(data, nil); !bytes.Equal(hdr, test.hdr) { - t.Errorf("msgHeader(%v, false) = %v; want %v", data, hdr, test.hdr) - } - } -} - -func TestCompress(t *testing.T) { - bestCompressor, err := NewGZIPCompressorWithLevel(gzip.BestCompression) - if err != nil { - t.Fatalf("Could not initialize gzip compressor with best compression.") - } - bestSpeedCompressor, err := NewGZIPCompressorWithLevel(gzip.BestSpeed) - if err != nil { - t.Fatalf("Could not initialize gzip compressor with best speed compression.") - } - - defaultCompressor, err := NewGZIPCompressorWithLevel(gzip.BestSpeed) - if err != nil { - t.Fatalf("Could not initialize gzip compressor with default compression.") - } - - level5, err := NewGZIPCompressorWithLevel(5) - if err != nil { - t.Fatalf("Could not initialize gzip compressor with level 5 compression.") - } - - for _, test := range []struct { - // input - data []byte - cp Compressor - dc Decompressor - // outputs - err error - }{ - {make([]byte, 1024), NewGZIPCompressor(), NewGZIPDecompressor(), nil}, - {make([]byte, 1024), bestCompressor, NewGZIPDecompressor(), nil}, - {make([]byte, 1024), bestSpeedCompressor, NewGZIPDecompressor(), nil}, - {make([]byte, 1024), defaultCompressor, NewGZIPDecompressor(), nil}, - {make([]byte, 1024), level5, NewGZIPDecompressor(), nil}, - } { - b := new(bytes.Buffer) - if err := test.cp.Do(b, test.data); err != test.err { - t.Fatalf("Compressor.Do(_, %v) = %v, want %v", test.data, err, test.err) - } - if b.Len() >= len(test.data) { - t.Fatalf("The compressor fails to compress data.") - } - if p, err := test.dc.Do(b); err != nil || !bytes.Equal(test.data, p) { - t.Fatalf("Decompressor.Do(%v) = %v, %v, want %v, ", b, p, err, test.data) - } - } -} - -func TestToRPCErr(t *testing.T) { - for _, test := range []struct { - // input - errIn error - // outputs - errOut error - }{ - {transport.StreamError{Code: codes.Unknown, Desc: ""}, status.Error(codes.Unknown, "")}, - {transport.ErrConnClosing, status.Error(codes.Unavailable, transport.ErrConnClosing.Desc)}, - } { - err := toRPCErr(test.errIn) - if _, ok := status.FromError(err); !ok { - t.Fatalf("toRPCErr{%v} returned type %T, want %T", test.errIn, err, status.Error(codes.Unknown, "")) - } - if !reflect.DeepEqual(err, test.errOut) { - t.Fatalf("toRPCErr{%v} = %v \nwant %v", test.errIn, err, test.errOut) - } - } -} - -func TestParseDialTarget(t *testing.T) { - for _, test := range []struct { - target, wantNet, wantAddr string - }{ - {"unix:etcd:0", "unix", "etcd:0"}, - {"unix:///tmp/unix-3", "unix", "/tmp/unix-3"}, - {"unix://domain", "unix", "domain"}, - {"unix://etcd:0", "unix", "etcd:0"}, - {"unix:///etcd:0", "unix", "/etcd:0"}, - {"passthrough://unix://domain", "tcp", "passthrough://unix://domain"}, - {"https://google.com:443", "tcp", "https://google.com:443"}, - {"dns:///google.com", "tcp", "dns:///google.com"}, - {"/unix/socket/address", "tcp", "/unix/socket/address"}, - } { - gotNet, gotAddr := parseDialTarget(test.target) - if gotNet != test.wantNet || gotAddr != test.wantAddr { - t.Errorf("parseDialTarget(%q) = %s, %s want %s, %s", test.target, gotNet, gotAddr, test.wantNet, test.wantAddr) - } - } -} - -// bmEncode benchmarks encoding a Protocol Buffer message containing mSize -// bytes. -func bmEncode(b *testing.B, mSize int) { - cdc := encoding.GetCodec(protoenc.Name) - msg := &perfpb.Buffer{Body: make([]byte, mSize)} - encodeData, _ := encode(cdc, msg) - encodedSz := int64(len(encodeData)) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - encode(cdc, msg) - } - b.SetBytes(encodedSz) -} - -func BenchmarkEncode1B(b *testing.B) { - bmEncode(b, 1) -} - -func BenchmarkEncode1KiB(b *testing.B) { - bmEncode(b, 1024) -} - -func BenchmarkEncode8KiB(b *testing.B) { - bmEncode(b, 8*1024) -} - -func BenchmarkEncode64KiB(b *testing.B) { - bmEncode(b, 64*1024) -} - -func BenchmarkEncode512KiB(b *testing.B) { - bmEncode(b, 512*1024) -} - -func BenchmarkEncode1MiB(b *testing.B) { - bmEncode(b, 1024*1024) -} - -// bmCompressor benchmarks a compressor of a Protocol Buffer message containing -// mSize bytes. -func bmCompressor(b *testing.B, mSize int, cp Compressor) { - payload := make([]byte, mSize) - cBuf := bytes.NewBuffer(make([]byte, mSize)) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - cp.Do(cBuf, payload) - cBuf.Reset() - } -} - -func BenchmarkGZIPCompressor1B(b *testing.B) { - bmCompressor(b, 1, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor1KiB(b *testing.B) { - bmCompressor(b, 1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor8KiB(b *testing.B) { - bmCompressor(b, 8*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor64KiB(b *testing.B) { - bmCompressor(b, 64*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor512KiB(b *testing.B) { - bmCompressor(b, 512*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor1MiB(b *testing.B) { - bmCompressor(b, 1024*1024, NewGZIPCompressor()) -} diff --git a/examples/google.golang.org/grpc/server.go b/examples/google.golang.org/grpc/server.go deleted file mode 100755 index 014c72b..0000000 --- a/examples/google.golang.org/grpc/server.go +++ /dev/null @@ -1,1486 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "net" - "net/http" - "reflect" - "runtime" - "strings" - "sync" - "time" - - "io/ioutil" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/trace" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/encoding/proto" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" - "google.golang.org/grpc/transport" -) - -const ( - defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4 - defaultServerMaxSendMessageSize = math.MaxInt32 -) - -type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error) - -// MethodDesc represents an RPC service's method specification. -type MethodDesc struct { - MethodName string - Handler methodHandler -} - -// ServiceDesc represents an RPC service's specification. -type ServiceDesc struct { - ServiceName string - // The pointer to the service interface. Used to check whether the user - // provided implementation satisfies the interface requirements. - HandlerType interface{} - Methods []MethodDesc - Streams []StreamDesc - Metadata interface{} -} - -// service consists of the information of the server serving this service and -// the methods in this service. -type service struct { - server interface{} // the server for service methods - md map[string]*MethodDesc - sd map[string]*StreamDesc - mdata interface{} -} - -// Server is a gRPC server to serve RPC requests. -type Server struct { - opts options - - mu sync.Mutex // guards following - lis map[net.Listener]bool - conns map[io.Closer]bool - serve bool - drain bool - cv *sync.Cond // signaled when connections close for GracefulStop - m map[string]*service // service name -> service info - events trace.EventLog - - quit chan struct{} - done chan struct{} - quitOnce sync.Once - doneOnce sync.Once - channelzRemoveOnce sync.Once - serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop - - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - callsStarted int64 - callsFailed int64 - callsSucceeded int64 - lastCallStartedTime time.Time -} - -type options struct { - creds credentials.TransportCredentials - codec baseCodec - cp Compressor - dc Decompressor - unaryInt UnaryServerInterceptor - streamInt StreamServerInterceptor - inTapHandle tap.ServerInHandle - statsHandler stats.Handler - maxConcurrentStreams uint32 - maxReceiveMessageSize int - maxSendMessageSize int - useHandlerImpl bool // use http.Handler-based server - unknownStreamDesc *StreamDesc - keepaliveParams keepalive.ServerParameters - keepalivePolicy keepalive.EnforcementPolicy - initialWindowSize int32 - initialConnWindowSize int32 - writeBufferSize int - readBufferSize int - connectionTimeout time.Duration -} - -var defaultServerOptions = options{ - maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, - maxSendMessageSize: defaultServerMaxSendMessageSize, - connectionTimeout: 120 * time.Second, -} - -// A ServerOption sets options such as credentials, codec and keepalive parameters, etc. -type ServerOption func(*options) - -// WriteBufferSize lets you set the size of write buffer, this determines how much data can be batched -// before doing a write on the wire. -func WriteBufferSize(s int) ServerOption { - return func(o *options) { - o.writeBufferSize = s - } -} - -// ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most -// for one read syscall. -func ReadBufferSize(s int) ServerOption { - return func(o *options) { - o.readBufferSize = s - } -} - -// InitialWindowSize returns a ServerOption that sets window size for stream. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func InitialWindowSize(s int32) ServerOption { - return func(o *options) { - o.initialWindowSize = s - } -} - -// InitialConnWindowSize returns a ServerOption that sets window size for a connection. -// The lower bound for window size is 64K and any value smaller than that will be ignored. -func InitialConnWindowSize(s int32) ServerOption { - return func(o *options) { - o.initialConnWindowSize = s - } -} - -// KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server. -func KeepaliveParams(kp keepalive.ServerParameters) ServerOption { - return func(o *options) { - o.keepaliveParams = kp - } -} - -// KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server. -func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption { - return func(o *options) { - o.keepalivePolicy = kep - } -} - -// CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling. -// -// This will override any lookups by content-subtype for Codecs registered with RegisterCodec. -func CustomCodec(codec Codec) ServerOption { - return func(o *options) { - o.codec = codec - } -} - -// RPCCompressor returns a ServerOption that sets a compressor for outbound -// messages. For backward compatibility, all outbound messages will be sent -// using this compressor, regardless of incoming message compression. By -// default, server messages will be sent using the same compressor with which -// request messages were sent. -// -// Deprecated: use encoding.RegisterCompressor instead. -func RPCCompressor(cp Compressor) ServerOption { - return func(o *options) { - o.cp = cp - } -} - -// RPCDecompressor returns a ServerOption that sets a decompressor for inbound -// messages. It has higher priority than decompressors registered via -// encoding.RegisterCompressor. -// -// Deprecated: use encoding.RegisterCompressor instead. -func RPCDecompressor(dc Decompressor) ServerOption { - return func(o *options) { - o.dc = dc - } -} - -// MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive. -// If this is not set, gRPC uses the default limit. -// -// Deprecated: use MaxRecvMsgSize instead. -func MaxMsgSize(m int) ServerOption { - return MaxRecvMsgSize(m) -} - -// MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive. -// If this is not set, gRPC uses the default 4MB. -func MaxRecvMsgSize(m int) ServerOption { - return func(o *options) { - o.maxReceiveMessageSize = m - } -} - -// MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send. -// If this is not set, gRPC uses the default 4MB. -func MaxSendMsgSize(m int) ServerOption { - return func(o *options) { - o.maxSendMessageSize = m - } -} - -// MaxConcurrentStreams returns a ServerOption that will apply a limit on the number -// of concurrent streams to each ServerTransport. -func MaxConcurrentStreams(n uint32) ServerOption { - return func(o *options) { - o.maxConcurrentStreams = n - } -} - -// Creds returns a ServerOption that sets credentials for server connections. -func Creds(c credentials.TransportCredentials) ServerOption { - return func(o *options) { - o.creds = c - } -} - -// UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the -// server. Only one unary interceptor can be installed. The construction of multiple -// interceptors (e.g., chaining) can be implemented at the caller. -func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { - return func(o *options) { - if o.unaryInt != nil { - panic("The unary server interceptor was already set and may not be reset.") - } - o.unaryInt = i - } -} - -// StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the -// server. Only one stream interceptor can be installed. -func StreamInterceptor(i StreamServerInterceptor) ServerOption { - return func(o *options) { - if o.streamInt != nil { - panic("The stream server interceptor was already set and may not be reset.") - } - o.streamInt = i - } -} - -// InTapHandle returns a ServerOption that sets the tap handle for all the server -// transport to be created. Only one can be installed. -func InTapHandle(h tap.ServerInHandle) ServerOption { - return func(o *options) { - if o.inTapHandle != nil { - panic("The tap handle was already set and may not be reset.") - } - o.inTapHandle = h - } -} - -// StatsHandler returns a ServerOption that sets the stats handler for the server. -func StatsHandler(h stats.Handler) ServerOption { - return func(o *options) { - o.statsHandler = h - } -} - -// UnknownServiceHandler returns a ServerOption that allows for adding a custom -// unknown service handler. The provided method is a bidi-streaming RPC service -// handler that will be invoked instead of returning the "unimplemented" gRPC -// error whenever a request is received for an unregistered service or method. -// The handling function has full access to the Context of the request and the -// stream, and the invocation bypasses interceptors. -func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { - return func(o *options) { - o.unknownStreamDesc = &StreamDesc{ - StreamName: "unknown_service_handler", - Handler: streamHandler, - // We need to assume that the users of the streamHandler will want to use both. - ClientStreams: true, - ServerStreams: true, - } - } -} - -// ConnectionTimeout returns a ServerOption that sets the timeout for -// connection establishment (up to and including HTTP/2 handshaking) for all -// new connections. If this is not set, the default is 120 seconds. A zero or -// negative value will result in an immediate timeout. -// -// This API is EXPERIMENTAL. -func ConnectionTimeout(d time.Duration) ServerOption { - return func(o *options) { - o.connectionTimeout = d - } -} - -// NewServer creates a gRPC server which has no service registered and has not -// started to accept requests yet. -func NewServer(opt ...ServerOption) *Server { - opts := defaultServerOptions - for _, o := range opt { - o(&opts) - } - s := &Server{ - lis: make(map[net.Listener]bool), - opts: opts, - conns: make(map[io.Closer]bool), - m: make(map[string]*service), - quit: make(chan struct{}), - done: make(chan struct{}), - } - s.cv = sync.NewCond(&s.mu) - if EnableTracing { - _, file, line, _ := runtime.Caller(1) - s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) - } - - if channelz.IsOn() { - s.channelzID = channelz.RegisterServer(s, "") - } - return s -} - -// printf records an event in s's event log, unless s has been stopped. -// REQUIRES s.mu is held. -func (s *Server) printf(format string, a ...interface{}) { - if s.events != nil { - s.events.Printf(format, a...) - } -} - -// errorf records an error in s's event log, unless s has been stopped. -// REQUIRES s.mu is held. -func (s *Server) errorf(format string, a ...interface{}) { - if s.events != nil { - s.events.Errorf(format, a...) - } -} - -// RegisterService registers a service and its implementation to the gRPC -// server. It is called from the IDL generated code. This must be called before -// invoking Serve. -func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { - ht := reflect.TypeOf(sd.HandlerType).Elem() - st := reflect.TypeOf(ss) - if !st.Implements(ht) { - grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht) - } - s.register(sd, ss) -} - -func (s *Server) register(sd *ServiceDesc, ss interface{}) { - s.mu.Lock() - defer s.mu.Unlock() - s.printf("RegisterService(%q)", sd.ServiceName) - if s.serve { - grpclog.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName) - } - if _, ok := s.m[sd.ServiceName]; ok { - grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName) - } - srv := &service{ - server: ss, - md: make(map[string]*MethodDesc), - sd: make(map[string]*StreamDesc), - mdata: sd.Metadata, - } - for i := range sd.Methods { - d := &sd.Methods[i] - srv.md[d.MethodName] = d - } - for i := range sd.Streams { - d := &sd.Streams[i] - srv.sd[d.StreamName] = d - } - s.m[sd.ServiceName] = srv -} - -// MethodInfo contains the information of an RPC including its method name and type. -type MethodInfo struct { - // Name is the method name only, without the service name or package name. - Name string - // IsClientStream indicates whether the RPC is a client streaming RPC. - IsClientStream bool - // IsServerStream indicates whether the RPC is a server streaming RPC. - IsServerStream bool -} - -// ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service. -type ServiceInfo struct { - Methods []MethodInfo - // Metadata is the metadata specified in ServiceDesc when registering service. - Metadata interface{} -} - -// GetServiceInfo returns a map from service names to ServiceInfo. -// Service names include the package names, in the form of .. -func (s *Server) GetServiceInfo() map[string]ServiceInfo { - ret := make(map[string]ServiceInfo) - for n, srv := range s.m { - methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd)) - for m := range srv.md { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: false, - IsServerStream: false, - }) - } - for m, d := range srv.sd { - methods = append(methods, MethodInfo{ - Name: m, - IsClientStream: d.ClientStreams, - IsServerStream: d.ServerStreams, - }) - } - - ret[n] = ServiceInfo{ - Methods: methods, - Metadata: srv.mdata, - } - } - return ret -} - -// ErrServerStopped indicates that the operation is now illegal because of -// the server being stopped. -var ErrServerStopped = errors.New("grpc: the server has been stopped") - -func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if s.opts.creds == nil { - return rawConn, nil, nil - } - return s.opts.creds.ServerHandshake(rawConn) -} - -type listenSocket struct { - net.Listener - channelzID int64 -} - -func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { - return &channelz.SocketInternalMetric{ - LocalAddr: l.Listener.Addr(), - } -} - -func (l *listenSocket) Close() error { - err := l.Listener.Close() - if channelz.IsOn() { - channelz.RemoveEntry(l.channelzID) - } - return err -} - -// Serve accepts incoming connections on the listener lis, creating a new -// ServerTransport and service goroutine for each. The service goroutines -// read gRPC requests and then call the registered handlers to reply to them. -// Serve returns when lis.Accept fails with fatal errors. lis will be closed when -// this method returns. -// Serve will return a non-nil error unless Stop or GracefulStop is called. -func (s *Server) Serve(lis net.Listener) error { - s.mu.Lock() - s.printf("serving") - s.serve = true - if s.lis == nil { - // Serve called after Stop or GracefulStop. - s.mu.Unlock() - lis.Close() - return ErrServerStopped - } - - s.serveWG.Add(1) - defer func() { - s.serveWG.Done() - select { - // Stop or GracefulStop called; block until done and return nil. - case <-s.quit: - <-s.done - default: - } - }() - - ls := &listenSocket{Listener: lis} - s.lis[ls] = true - - if channelz.IsOn() { - ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, "") - } - s.mu.Unlock() - - defer func() { - s.mu.Lock() - if s.lis != nil && s.lis[ls] { - ls.Close() - delete(s.lis, ls) - } - s.mu.Unlock() - }() - - var tempDelay time.Duration // how long to sleep on accept failure - - for { - rawConn, err := lis.Accept() - if err != nil { - if ne, ok := err.(interface { - Temporary() bool - }); ok && ne.Temporary() { - if tempDelay == 0 { - tempDelay = 5 * time.Millisecond - } else { - tempDelay *= 2 - } - if max := 1 * time.Second; tempDelay > max { - tempDelay = max - } - s.mu.Lock() - s.printf("Accept error: %v; retrying in %v", err, tempDelay) - s.mu.Unlock() - timer := time.NewTimer(tempDelay) - select { - case <-timer.C: - case <-s.quit: - timer.Stop() - return nil - } - continue - } - s.mu.Lock() - s.printf("done serving; Accept = %v", err) - s.mu.Unlock() - - select { - case <-s.quit: - return nil - default: - } - return err - } - tempDelay = 0 - // Start a new goroutine to deal with rawConn so we don't stall this Accept - // loop goroutine. - // - // Make sure we account for the goroutine so GracefulStop doesn't nil out - // s.conns before this conn can be added. - s.serveWG.Add(1) - go func() { - s.handleRawConn(rawConn) - s.serveWG.Done() - }() - } -} - -// handleRawConn forks a goroutine to handle a just-accepted connection that -// has not had any I/O performed on it yet. -func (s *Server) handleRawConn(rawConn net.Conn) { - rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) - conn, authInfo, err := s.useTransportAuthenticator(rawConn) - if err != nil { - s.mu.Lock() - s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) - s.mu.Unlock() - grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) - // If serverHandshake returns ErrConnDispatched, keep rawConn open. - if err != credentials.ErrConnDispatched { - rawConn.Close() - } - rawConn.SetDeadline(time.Time{}) - return - } - - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - conn.Close() - return - } - s.mu.Unlock() - - var serve func() - c := conn.(io.Closer) - if s.opts.useHandlerImpl { - serve = func() { s.serveUsingHandler(conn) } - } else { - // Finish handshaking (HTTP2) - st := s.newHTTP2Transport(conn, authInfo) - if st == nil { - return - } - c = st - serve = func() { s.serveStreams(st) } - } - - rawConn.SetDeadline(time.Time{}) - if !s.addConn(c) { - return - } - go func() { - serve() - s.removeConn(c) - }() -} - -// newHTTP2Transport sets up a http/2 transport (using the -// gRPC http2 server transport in transport/http2_server.go). -func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport { - config := &transport.ServerConfig{ - MaxStreams: s.opts.maxConcurrentStreams, - AuthInfo: authInfo, - InTapHandle: s.opts.inTapHandle, - StatsHandler: s.opts.statsHandler, - KeepaliveParams: s.opts.keepaliveParams, - KeepalivePolicy: s.opts.keepalivePolicy, - InitialWindowSize: s.opts.initialWindowSize, - InitialConnWindowSize: s.opts.initialConnWindowSize, - WriteBufferSize: s.opts.writeBufferSize, - ReadBufferSize: s.opts.readBufferSize, - ChannelzParentID: s.channelzID, - } - st, err := transport.NewServerTransport("http2", c, config) - if err != nil { - s.mu.Lock() - s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err) - s.mu.Unlock() - c.Close() - grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err) - return nil - } - - return st -} - -func (s *Server) serveStreams(st transport.ServerTransport) { - defer st.Close() - var wg sync.WaitGroup - st.HandleStreams(func(stream *transport.Stream) { - wg.Add(1) - go func() { - defer wg.Done() - s.handleStream(st, stream, s.traceInfo(st, stream)) - }() - }, func(ctx context.Context, method string) context.Context { - if !EnableTracing { - return ctx - } - tr := trace.New("grpc.Recv."+methodFamily(method), method) - return trace.NewContext(ctx, tr) - }) - wg.Wait() -} - -var _ http.Handler = (*Server)(nil) - -// serveUsingHandler is called from handleRawConn when s is configured -// to handle requests via the http.Handler interface. It sets up a -// net/http.Server to handle the just-accepted conn. The http.Server -// is configured to route all incoming requests (all HTTP/2 streams) -// to ServeHTTP, which creates a new ServerTransport for each stream. -// serveUsingHandler blocks until conn closes. -// -// This codepath is only used when Server.TestingUseHandlerImpl has -// been configured. This lets the end2end tests exercise the ServeHTTP -// method as one of the environment types. -// -// conn is the *tls.Conn that's already been authenticated. -func (s *Server) serveUsingHandler(conn net.Conn) { - h2s := &http2.Server{ - MaxConcurrentStreams: s.opts.maxConcurrentStreams, - } - h2s.ServeConn(conn, &http2.ServeConnOpts{ - Handler: s, - }) -} - -// ServeHTTP implements the Go standard library's http.Handler -// interface by responding to the gRPC request r, by looking up -// the requested gRPC method in the gRPC server s. -// -// The provided HTTP request must have arrived on an HTTP/2 -// connection. When using the Go standard library's server, -// practically this means that the Request must also have arrived -// over TLS. -// -// To share one port (such as 443 for https) between gRPC and an -// existing http.Handler, use a root http.Handler such as: -// -// if r.ProtoMajor == 2 && strings.HasPrefix( -// r.Header.Get("Content-Type"), "application/grpc") { -// grpcServer.ServeHTTP(w, r) -// } else { -// yourMux.ServeHTTP(w, r) -// } -// -// Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally -// separate from grpc-go's HTTP/2 server. Performance and features may vary -// between the two paths. ServeHTTP does not support some gRPC features -// available through grpc-go's HTTP/2 server, and it is currently EXPERIMENTAL -// and subject to change. -func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandler) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if !s.addConn(st) { - return - } - defer s.removeConn(st) - s.serveStreams(st) -} - -// traceInfo returns a traceInfo and associates it with stream, if tracing is enabled. -// If tracing is not enabled, it returns nil. -func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) { - tr, ok := trace.FromContext(stream.Context()) - if !ok { - return nil - } - - trInfo = &traceInfo{ - tr: tr, - } - trInfo.firstLine.client = false - trInfo.firstLine.remoteAddr = st.RemoteAddr() - - if dl, ok := stream.Context().Deadline(); ok { - trInfo.firstLine.deadline = dl.Sub(time.Now()) - } - return trInfo -} - -func (s *Server) addConn(c io.Closer) bool { - s.mu.Lock() - defer s.mu.Unlock() - if s.conns == nil { - c.Close() - return false - } - if s.drain { - // Transport added after we drained our existing conns: drain it - // immediately. - c.(transport.ServerTransport).Drain() - } - s.conns[c] = true - return true -} - -func (s *Server) removeConn(c io.Closer) { - s.mu.Lock() - defer s.mu.Unlock() - if s.conns != nil { - delete(s.conns, c) - s.cv.Broadcast() - } -} - -// ChannelzMetric returns ServerInternalMetric of current server. -// This is an EXPERIMENTAL API. -func (s *Server) ChannelzMetric() *channelz.ServerInternalMetric { - s.czmu.RLock() - defer s.czmu.RUnlock() - return &channelz.ServerInternalMetric{ - CallsStarted: s.callsStarted, - CallsSucceeded: s.callsSucceeded, - CallsFailed: s.callsFailed, - LastCallStartedTimestamp: s.lastCallStartedTime, - } -} - -func (s *Server) incrCallsStarted() { - s.czmu.Lock() - s.callsStarted++ - s.lastCallStartedTime = time.Now() - s.czmu.Unlock() -} - -func (s *Server) incrCallsSucceeded() { - s.czmu.Lock() - s.callsSucceeded++ - s.czmu.Unlock() -} - -func (s *Server) incrCallsFailed() { - s.czmu.Lock() - s.callsFailed++ - s.czmu.Unlock() -} - -func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { - data, err := encode(s.getCodec(stream.ContentSubtype()), msg) - if err != nil { - grpclog.Errorln("grpc: server failed to encode response: ", err) - return err - } - compData, err := compress(data, cp, comp) - if err != nil { - grpclog.Errorln("grpc: server failed to compress response: ", err) - return err - } - hdr, payload := msgHeader(data, compData) - // TODO(dfawley): should we be checking len(data) instead? - if len(payload) > s.opts.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize) - } - err = t.Write(stream, hdr, payload, opts) - if err == nil && s.opts.statsHandler != nil { - s.opts.statsHandler.HandleRPC(stream.Context(), outPayload(false, msg, data, payload, time.Now())) - } - return err -} - -func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) { - if channelz.IsOn() { - s.incrCallsStarted() - defer func() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - }() - } - sh := s.opts.statsHandler - if sh != nil { - beginTime := time.Now() - begin := &stats.Begin{ - BeginTime: beginTime, - } - sh.HandleRPC(stream.Context(), begin) - defer func() { - end := &stats.End{ - BeginTime: beginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(stream.Context(), end) - }() - } - if trInfo != nil { - defer trInfo.tr.Finish() - trInfo.firstLine.client = false - trInfo.tr.LazyLog(&trInfo.firstLine, false) - defer func() { - if err != nil && err != io.EOF { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - }() - } - - // comp and cp are used for compression. decomp and dc are used for - // decompression. If comp and decomp are both set, they are the same; - // however they are kept separate to ensure that at most one of the - // compressor/decompressor variable pairs are set for use later. - var comp, decomp encoding.Compressor - var cp Compressor - var dc Decompressor - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - decomp = encoding.GetCompressor(rc) - if decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - t.WriteStatus(stream, st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - cp = s.opts.cp - stream.SetSendCompress(cp.Type()) - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - comp = encoding.GetCompressor(rc) - if comp != nil { - stream.SetSendCompress(rc) - } - } - - p := &parser{r: stream} - pf, req, err := p.recvMsg(s.opts.maxReceiveMessageSize) - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if err == io.ErrUnexpectedEOF { - err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) - } - if err != nil { - if st, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - case transport.StreamError: - if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", st, st)) - } - } - return err - } - if channelz.IsOn() { - t.IncrMsgRecv() - } - if st := checkRecvPayload(pf, stream.RecvCompress(), dc != nil || decomp != nil); st != nil { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - return st.Err() - } - var inPayload *stats.InPayload - if sh != nil { - inPayload = &stats.InPayload{ - RecvTime: time.Now(), - } - } - df := func(v interface{}) error { - if inPayload != nil { - inPayload.WireLength = len(req) - } - if pf == compressionMade { - var err error - if dc != nil { - req, err = dc.Do(bytes.NewReader(req)) - if err != nil { - return status.Errorf(codes.Internal, err.Error()) - } - } else { - tmp, _ := decomp.Decompress(bytes.NewReader(req)) - req, err = ioutil.ReadAll(tmp) - if err != nil { - return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) - } - } - } - if len(req) > s.opts.maxReceiveMessageSize { - // TODO: Revisit the error code. Currently keep it consistent with - // java implementation. - return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(req), s.opts.maxReceiveMessageSize) - } - if err := s.getCodec(stream.ContentSubtype()).Unmarshal(req, v); err != nil { - return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) - } - if inPayload != nil { - inPayload.Payload = v - inPayload.Data = req - inPayload.Length = len(req) - sh.HandleRPC(stream.Context(), inPayload) - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true) - } - return nil - } - ctx := NewContextWithServerTransportStream(stream.Context(), stream) - reply, appErr := md.Handler(srv.server, ctx, df, s.opts.unaryInt) - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - // Convert appErr if it is not a grpc status error. - appErr = status.Error(codes.Unknown, appErr.Error()) - appStatus, _ = status.FromError(appErr) - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - trInfo.tr.SetError() - } - if e := t.WriteStatus(stream, appStatus); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) - } - return appErr - } - if trInfo != nil { - trInfo.tr.LazyLog(stringer("OK"), false) - } - opts := &transport.Options{ - Last: true, - Delay: false, - } - - if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil { - if err == io.EOF { - // The entire stream is done (for unary RPC only). - return err - } - if s, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, s); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) - } - } else { - switch st := err.(type) { - case transport.ConnectionError: - // Nothing to do here. - case transport.StreamError: - if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - default: - panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st)) - } - } - return err - } - if channelz.IsOn() { - t.IncrMsgSent() - } - if trInfo != nil { - trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true) - } - // TODO: Should we be logging if writing status failed here, like above? - // Should the logging be in WriteStatus? Should we ignore the WriteStatus - // error or allow the stats handler to see it? - return t.WriteStatus(stream, status.New(codes.OK, "")) -} - -func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) { - if channelz.IsOn() { - s.incrCallsStarted() - defer func() { - if err != nil && err != io.EOF { - s.incrCallsFailed() - } else { - s.incrCallsSucceeded() - } - }() - } - sh := s.opts.statsHandler - if sh != nil { - beginTime := time.Now() - begin := &stats.Begin{ - BeginTime: beginTime, - } - sh.HandleRPC(stream.Context(), begin) - defer func() { - end := &stats.End{ - BeginTime: beginTime, - EndTime: time.Now(), - } - if err != nil && err != io.EOF { - end.Error = toRPCErr(err) - } - sh.HandleRPC(stream.Context(), end) - }() - } - ctx := NewContextWithServerTransportStream(stream.Context(), stream) - ss := &serverStream{ - ctx: ctx, - t: t, - s: stream, - p: &parser{r: stream}, - codec: s.getCodec(stream.ContentSubtype()), - maxReceiveMessageSize: s.opts.maxReceiveMessageSize, - maxSendMessageSize: s.opts.maxSendMessageSize, - trInfo: trInfo, - statsHandler: sh, - } - - // If dc is set and matches the stream's compression, use it. Otherwise, try - // to find a matching registered compressor for decomp. - if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { - ss.dc = s.opts.dc - } else if rc != "" && rc != encoding.Identity { - ss.decomp = encoding.GetCompressor(rc) - if ss.decomp == nil { - st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) - t.WriteStatus(ss.s, st) - return st.Err() - } - } - - // If cp is set, use it. Otherwise, attempt to compress the response using - // the incoming message compression method. - // - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - if s.opts.cp != nil { - ss.cp = s.opts.cp - stream.SetSendCompress(s.opts.cp.Type()) - } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { - // Legacy compressor not specified; attempt to respond with same encoding. - ss.comp = encoding.GetCompressor(rc) - if ss.comp != nil { - stream.SetSendCompress(rc) - } - } - - if trInfo != nil { - trInfo.tr.LazyLog(&trInfo.firstLine, false) - defer func() { - ss.mu.Lock() - if err != nil && err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - ss.trInfo.tr.Finish() - ss.trInfo.tr = nil - ss.mu.Unlock() - }() - } - var appErr error - var server interface{} - if srv != nil { - server = srv.server - } - if s.opts.streamInt == nil { - appErr = sd.Handler(server, ss) - } else { - info := &StreamServerInfo{ - FullMethod: stream.Method(), - IsClientStream: sd.ClientStreams, - IsServerStream: sd.ServerStreams, - } - appErr = s.opts.streamInt(server, ss, info, sd.Handler) - } - if appErr != nil { - appStatus, ok := status.FromError(appErr) - if !ok { - switch err := appErr.(type) { - case transport.StreamError: - appStatus = status.New(err.Code, err.Desc) - default: - appStatus = status.New(codes.Unknown, appErr.Error()) - } - appErr = appStatus.Err() - } - if trInfo != nil { - ss.mu.Lock() - ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true) - ss.trInfo.tr.SetError() - ss.mu.Unlock() - } - t.WriteStatus(ss.s, appStatus) - // TODO: Should we log an error from WriteStatus here and below? - return appErr - } - if trInfo != nil { - ss.mu.Lock() - ss.trInfo.tr.LazyLog(stringer("OK"), false) - ss.mu.Unlock() - } - return t.WriteStatus(ss.s, status.New(codes.OK, "")) -} - -func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) { - sm := stream.Method() - if sm != "" && sm[0] == '/' { - sm = sm[1:] - } - pos := strings.LastIndex(sm, "/") - if pos == -1 { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true) - trInfo.tr.SetError() - } - errDesc := fmt.Sprintf("malformed method name: %q", stream.Method()) - if err := t.WriteStatus(stream, status.New(codes.ResourceExhausted, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } - return - } - service := sm[:pos] - method := sm[pos+1:] - srv, ok := s.m[service] - if !ok { - if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo) - return - } - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true) - trInfo.tr.SetError() - } - errDesc := fmt.Sprintf("unknown service %v", service) - if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } - return - } - // Unary RPC or Streaming RPC? - if md, ok := srv.md[method]; ok { - s.processUnaryRPC(t, stream, srv, md, trInfo) - return - } - if sd, ok := srv.sd[method]; ok { - s.processStreamingRPC(t, stream, srv, sd, trInfo) - return - } - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true) - trInfo.tr.SetError() - } - if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil { - s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo) - return - } - errDesc := fmt.Sprintf("unknown method %v", method) - if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil { - if trInfo != nil { - trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - trInfo.tr.SetError() - } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) - } - if trInfo != nil { - trInfo.tr.Finish() - } -} - -// The key to save ServerTransportStream in the context. -type streamKey struct{} - -// NewContextWithServerTransportStream creates a new context from ctx and -// attaches stream to it. -// -// This API is EXPERIMENTAL. -func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context { - return context.WithValue(ctx, streamKey{}, stream) -} - -// ServerTransportStream is a minimal interface that a transport stream must -// implement. This can be used to mock an actual transport stream for tests of -// handler code that use, for example, grpc.SetHeader (which requires some -// stream to be in context). -// -// See also NewContextWithServerTransportStream. -// -// This API is EXPERIMENTAL. -type ServerTransportStream interface { - Method() string - SetHeader(md metadata.MD) error - SendHeader(md metadata.MD) error - SetTrailer(md metadata.MD) error -} - -// ServerTransportStreamFromContext returns the ServerTransportStream saved in -// ctx. Returns nil if the given context has no stream associated with it -// (which implies it is not an RPC invocation context). -// -// This API is EXPERIMENTAL. -func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream { - s, _ := ctx.Value(streamKey{}).(ServerTransportStream) - return s -} - -// Stop stops the gRPC server. It immediately closes all open -// connections and listeners. -// It cancels all active RPCs on the server side and the corresponding -// pending RPCs on the client side will get notified by connection -// errors. -func (s *Server) Stop() { - s.quitOnce.Do(func() { - close(s.quit) - }) - - defer func() { - s.serveWG.Wait() - s.doneOnce.Do(func() { - close(s.done) - }) - }() - - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) - - s.mu.Lock() - listeners := s.lis - s.lis = nil - st := s.conns - s.conns = nil - // interrupt GracefulStop if Stop and GracefulStop are called concurrently. - s.cv.Broadcast() - s.mu.Unlock() - - for lis := range listeners { - lis.Close() - } - for c := range st { - c.Close() - } - - s.mu.Lock() - if s.events != nil { - s.events.Finish() - s.events = nil - } - s.mu.Unlock() -} - -// GracefulStop stops the gRPC server gracefully. It stops the server from -// accepting new connections and RPCs and blocks until all the pending RPCs are -// finished. -func (s *Server) GracefulStop() { - s.quitOnce.Do(func() { - close(s.quit) - }) - - defer func() { - s.doneOnce.Do(func() { - close(s.done) - }) - }() - - s.channelzRemoveOnce.Do(func() { - if channelz.IsOn() { - channelz.RemoveEntry(s.channelzID) - } - }) - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - return - } - - for lis := range s.lis { - lis.Close() - } - s.lis = nil - if !s.drain { - for c := range s.conns { - c.(transport.ServerTransport).Drain() - } - s.drain = true - } - - // Wait for serving threads to be ready to exit. Only then can we be sure no - // new conns will be created. - s.mu.Unlock() - s.serveWG.Wait() - s.mu.Lock() - - for len(s.conns) != 0 { - s.cv.Wait() - } - s.conns = nil - if s.events != nil { - s.events.Finish() - s.events = nil - } - s.mu.Unlock() -} - -func init() { - internal.TestingUseHandlerImpl = func(arg interface{}) { - arg.(*Server).opts.useHandlerImpl = true - } -} - -// contentSubtype must be lowercase -// cannot return nil -func (s *Server) getCodec(contentSubtype string) baseCodec { - if s.opts.codec != nil { - return s.opts.codec - } - if contentSubtype == "" { - return encoding.GetCodec(proto.Name) - } - codec := encoding.GetCodec(contentSubtype) - if codec == nil { - return encoding.GetCodec(proto.Name) - } - return codec -} - -// SetHeader sets the header metadata. -// When called multiple times, all the provided metadata will be merged. -// All the metadata will be sent out when one of the following happens: -// - grpc.SendHeader() is called; -// - The first response is sent out; -// - An RPC status is sent out (error or success). -func SetHeader(ctx context.Context, md metadata.MD) error { - if md.Len() == 0 { - return nil - } - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - return stream.SetHeader(md) -} - -// SendHeader sends header metadata. It may be called at most once. -// The provided md and headers set by SetHeader() will be sent. -func SendHeader(ctx context.Context, md metadata.MD) error { - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - if err := stream.SendHeader(md); err != nil { - return toRPCErr(err) - } - return nil -} - -// SetTrailer sets the trailer metadata that will be sent when an RPC returns. -// When called more than once, all the provided metadata will be merged. -func SetTrailer(ctx context.Context, md metadata.MD) error { - if md.Len() == 0 { - return nil - } - stream := ServerTransportStreamFromContext(ctx) - if stream == nil { - return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) - } - return stream.SetTrailer(md) -} - -// Method returns the method string for the server context. The returned -// string is in the format of "/service/method". -func Method(ctx context.Context) (string, bool) { - s := ServerTransportStreamFromContext(ctx) - if s == nil { - return "", false - } - return s.Method(), true -} diff --git a/examples/google.golang.org/grpc/server_test.go b/examples/google.golang.org/grpc/server_test.go deleted file mode 100755 index 77e40b0..0000000 --- a/examples/google.golang.org/grpc/server_test.go +++ /dev/null @@ -1,136 +0,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. - * - */ - -package grpc - -import ( - "net" - "reflect" - "strings" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/transport" -) - -type emptyServiceServer interface{} - -type testServer struct{} - -func TestStopBeforeServe(t *testing.T) { - defer leakcheck.Check(t) - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to create listener: %v", err) - } - - server := NewServer() - server.Stop() - err = server.Serve(lis) - if err != ErrServerStopped { - t.Fatalf("server.Serve() error = %v, want %v", err, ErrServerStopped) - } - - // server.Serve is responsible for closing the listener, even if the - // server was already stopped. - err = lis.Close() - if got, want := errorDesc(err), "use of closed"; !strings.Contains(got, want) { - t.Errorf("Close() error = %q, want %q", got, want) - } -} - -func TestGracefulStop(t *testing.T) { - defer leakcheck.Check(t) - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to create listener: %v", err) - } - - server := NewServer() - go func() { - // make sure Serve() is called - time.Sleep(time.Millisecond * 500) - server.GracefulStop() - }() - - err = server.Serve(lis) - if err != nil { - t.Fatalf("Serve() returned non-nil error on GracefulStop: %v", err) - } -} - -func TestGetServiceInfo(t *testing.T) { - defer leakcheck.Check(t) - testSd := ServiceDesc{ - ServiceName: "grpc.testing.EmptyService", - HandlerType: (*emptyServiceServer)(nil), - Methods: []MethodDesc{ - { - MethodName: "EmptyCall", - Handler: nil, - }, - }, - Streams: []StreamDesc{ - { - StreamName: "EmptyStream", - Handler: nil, - ServerStreams: false, - ClientStreams: true, - }, - }, - Metadata: []int{0, 2, 1, 3}, - } - - server := NewServer() - server.RegisterService(&testSd, &testServer{}) - - info := server.GetServiceInfo() - want := map[string]ServiceInfo{ - "grpc.testing.EmptyService": { - Methods: []MethodInfo{ - { - Name: "EmptyCall", - IsClientStream: false, - IsServerStream: false, - }, - { - Name: "EmptyStream", - IsClientStream: true, - IsServerStream: false, - }}, - Metadata: []int{0, 2, 1, 3}, - }, - } - - if !reflect.DeepEqual(info, want) { - t.Errorf("GetServiceInfo() = %+v, want %+v", info, want) - } -} - -func TestStreamContext(t *testing.T) { - expectedStream := &transport.Stream{} - ctx := NewContextWithServerTransportStream(context.Background(), expectedStream) - s := ServerTransportStreamFromContext(ctx) - stream, ok := s.(*transport.Stream) - if !ok || expectedStream != stream { - t.Fatalf("GetStreamFromContext(%v) = %v, %t, want: %v, true", ctx, stream, ok, expectedStream) - } -} diff --git a/examples/google.golang.org/grpc/service_config.go b/examples/google.golang.org/grpc/service_config.go deleted file mode 100755 index 015631d..0000000 --- a/examples/google.golang.org/grpc/service_config.go +++ /dev/null @@ -1,233 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - "time" - - "google.golang.org/grpc/grpclog" -) - -const maxInt = int(^uint(0) >> 1) - -// MethodConfig defines the configuration recommended by the service providers for a -// particular method. -// -// Deprecated: Users should not use this struct. Service config should be received -// through name resolver, as specified here -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -type MethodConfig struct { - // WaitForReady indicates whether RPCs sent to this method should wait until - // the connection is ready by default (!failfast). The value specified via the - // gRPC client API will override the value set here. - WaitForReady *bool - // Timeout is the default timeout for RPCs sent to this method. The actual - // deadline used will be the minimum of the value specified here and the value - // set by the application via the gRPC client API. If either one is not set, - // then the other will be used. If neither is set, then the RPC has no deadline. - Timeout *time.Duration - // MaxReqSize is the maximum allowed payload size for an individual request in a - // stream (client->server) in bytes. The size which is measured is the serialized - // payload after per-message compression (but before stream compression) in bytes. - // The actual value used is the minimum of the value specified here and the value set - // by the application via the gRPC client API. If either one is not set, then the other - // will be used. If neither is set, then the built-in default is used. - MaxReqSize *int - // MaxRespSize is the maximum allowed payload size for an individual response in a - // stream (server->client) in bytes. - MaxRespSize *int -} - -// ServiceConfig is provided by the service provider and contains parameters for how -// clients that connect to the service should behave. -// -// Deprecated: Users should not use this struct. Service config should be received -// through name resolver, as specified here -// https://github.com/grpc/grpc/blob/master/doc/service_config.md -type ServiceConfig struct { - // LB is the load balancer the service providers recommends. The balancer specified - // via grpc.WithBalancer will override this. - LB *string - // Methods contains a map for the methods in this service. - // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. - // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. - // Otherwise, the method has no MethodConfig to use. - Methods map[string]MethodConfig - - stickinessMetadataKey *string -} - -func parseDuration(s *string) (*time.Duration, error) { - if s == nil { - return nil, nil - } - if !strings.HasSuffix(*s, "s") { - return nil, fmt.Errorf("malformed duration %q", *s) - } - ss := strings.SplitN((*s)[:len(*s)-1], ".", 3) - if len(ss) > 2 { - return nil, fmt.Errorf("malformed duration %q", *s) - } - // hasDigits is set if either the whole or fractional part of the number is - // present, since both are optional but one is required. - hasDigits := false - var d time.Duration - if len(ss[0]) > 0 { - i, err := strconv.ParseInt(ss[0], 10, 32) - if err != nil { - return nil, fmt.Errorf("malformed duration %q: %v", *s, err) - } - d = time.Duration(i) * time.Second - hasDigits = true - } - if len(ss) == 2 && len(ss[1]) > 0 { - if len(ss[1]) > 9 { - return nil, fmt.Errorf("malformed duration %q", *s) - } - f, err := strconv.ParseInt(ss[1], 10, 64) - if err != nil { - return nil, fmt.Errorf("malformed duration %q: %v", *s, err) - } - for i := 9; i > len(ss[1]); i-- { - f *= 10 - } - d += time.Duration(f) - hasDigits = true - } - if !hasDigits { - return nil, fmt.Errorf("malformed duration %q", *s) - } - - return &d, nil -} - -type jsonName struct { - Service *string - Method *string -} - -func (j jsonName) generatePath() (string, bool) { - if j.Service == nil { - return "", false - } - res := "/" + *j.Service + "/" - if j.Method != nil { - res += *j.Method - } - return res, true -} - -// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. -type jsonMC struct { - Name *[]jsonName - WaitForReady *bool - Timeout *string - MaxRequestMessageBytes *int64 - MaxResponseMessageBytes *int64 -} - -// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. -type jsonSC struct { - LoadBalancingPolicy *string - StickinessMetadataKey *string - MethodConfig *[]jsonMC -} - -func parseServiceConfig(js string) (ServiceConfig, error) { - var rsc jsonSC - err := json.Unmarshal([]byte(js), &rsc) - if err != nil { - grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) - return ServiceConfig{}, err - } - sc := ServiceConfig{ - LB: rsc.LoadBalancingPolicy, - Methods: make(map[string]MethodConfig), - - stickinessMetadataKey: rsc.StickinessMetadataKey, - } - if rsc.MethodConfig == nil { - return sc, nil - } - - for _, m := range *rsc.MethodConfig { - if m.Name == nil { - continue - } - d, err := parseDuration(m.Timeout) - if err != nil { - grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) - return ServiceConfig{}, err - } - - mc := MethodConfig{ - WaitForReady: m.WaitForReady, - Timeout: d, - } - if m.MaxRequestMessageBytes != nil { - if *m.MaxRequestMessageBytes > int64(maxInt) { - mc.MaxReqSize = newInt(maxInt) - } else { - mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes)) - } - } - if m.MaxResponseMessageBytes != nil { - if *m.MaxResponseMessageBytes > int64(maxInt) { - mc.MaxRespSize = newInt(maxInt) - } else { - mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes)) - } - } - for _, n := range *m.Name { - if path, valid := n.generatePath(); valid { - sc.Methods[path] = mc - } - } - } - - return sc, nil -} - -func min(a, b *int) *int { - if *a < *b { - return a - } - return b -} - -func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { - if mcMax == nil && doptMax == nil { - return &defaultVal - } - if mcMax != nil && doptMax != nil { - return min(mcMax, doptMax) - } - if mcMax != nil { - return mcMax - } - return doptMax -} - -func newInt(b int) *int { - return &b -} diff --git a/examples/google.golang.org/grpc/service_config_test.go b/examples/google.golang.org/grpc/service_config_test.go deleted file mode 100755 index 8301a50..0000000 --- a/examples/google.golang.org/grpc/service_config_test.go +++ /dev/null @@ -1,386 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "fmt" - "math" - "reflect" - "testing" - "time" -) - -func TestParseLoadBalancer(t *testing.T) { - testcases := []struct { - scjs string - wantSC ServiceConfig - wantErr bool - }{ - { - `{ - "loadBalancingPolicy": "round_robin", - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": true - } - ] -}`, - ServiceConfig{ - LB: newString("round_robin"), - Methods: map[string]MethodConfig{ - "/foo/Bar": { - WaitForReady: newBool(true), - }, - }, - }, - false, - }, - { - `{ - "loadBalancingPolicy": 1, - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": false - } - ] -}`, - ServiceConfig{}, - true, - }, - } - - for _, c := range testcases { - sc, err := parseServiceConfig(c.scjs) - if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { - t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) - } - } -} - -func TestParseWaitForReady(t *testing.T) { - testcases := []struct { - scjs string - wantSC ServiceConfig - wantErr bool - }{ - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": true - } - ] -}`, - ServiceConfig{ - Methods: map[string]MethodConfig{ - "/foo/Bar": { - WaitForReady: newBool(true), - }, - }, - }, - false, - }, - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": false - } - ] -}`, - ServiceConfig{ - Methods: map[string]MethodConfig{ - "/foo/Bar": { - WaitForReady: newBool(false), - }, - }, - }, - false, - }, - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": fall - }, - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "waitForReady": true - } - ] -}`, - ServiceConfig{}, - true, - }, - } - - for _, c := range testcases { - sc, err := parseServiceConfig(c.scjs) - if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { - t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) - } - } -} - -func TestPraseTimeOut(t *testing.T) { - testcases := []struct { - scjs string - wantSC ServiceConfig - wantErr bool - }{ - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "timeout": "1s" - } - ] -}`, - ServiceConfig{ - Methods: map[string]MethodConfig{ - "/foo/Bar": { - Timeout: newDuration(time.Second), - }, - }, - }, - false, - }, - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "timeout": "3c" - } - ] -}`, - ServiceConfig{}, - true, - }, - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "timeout": "3c" - }, - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "timeout": "1s" - } - ] -}`, - ServiceConfig{}, - true, - }, - } - - for _, c := range testcases { - sc, err := parseServiceConfig(c.scjs) - if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { - t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) - } - } -} - -func TestPraseMsgSize(t *testing.T) { - testcases := []struct { - scjs string - wantSC ServiceConfig - wantErr bool - }{ - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 2048 - } - ] -}`, - ServiceConfig{ - Methods: map[string]MethodConfig{ - "/foo/Bar": { - MaxReqSize: newInt(1024), - MaxRespSize: newInt(2048), - }, - }, - }, - false, - }, - { - `{ - "methodConfig": [ - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "maxRequestMessageBytes": "1024", - "maxResponseMessageBytes": "2048" - }, - { - "name": [ - { - "service": "foo", - "method": "Bar" - } - ], - "maxRequestMessageBytes": 1024, - "maxResponseMessageBytes": 2048 - } - ] -}`, - ServiceConfig{}, - true, - }, - } - - for _, c := range testcases { - sc, err := parseServiceConfig(c.scjs) - if c.wantErr != (err != nil) || !reflect.DeepEqual(sc, c.wantSC) { - t.Fatalf("parseServiceConfig(%s) = %+v, %v, want %+v, %v", c.scjs, sc, err, c.wantSC, c.wantErr) - } - } -} - -func TestParseDuration(t *testing.T) { - testCases := []struct { - s *string - want *time.Duration - err bool - }{ - {s: nil, want: nil}, - {s: newString("1s"), want: newDuration(time.Second)}, - {s: newString("-1s"), want: newDuration(-time.Second)}, - {s: newString("1.1s"), want: newDuration(1100 * time.Millisecond)}, - {s: newString("1.s"), want: newDuration(time.Second)}, - {s: newString("1.0s"), want: newDuration(time.Second)}, - {s: newString(".002s"), want: newDuration(2 * time.Millisecond)}, - {s: newString(".002000s"), want: newDuration(2 * time.Millisecond)}, - {s: newString("0.003s"), want: newDuration(3 * time.Millisecond)}, - {s: newString("0.000004s"), want: newDuration(4 * time.Microsecond)}, - {s: newString("5000.000000009s"), want: newDuration(5000*time.Second + 9*time.Nanosecond)}, - {s: newString("4999.999999999s"), want: newDuration(5000*time.Second - time.Nanosecond)}, - {s: newString("1"), err: true}, - {s: newString("s"), err: true}, - {s: newString(".s"), err: true}, - {s: newString("1 s"), err: true}, - {s: newString(" 1s"), err: true}, - {s: newString("1ms"), err: true}, - {s: newString("1.1.1s"), err: true}, - {s: newString("Xs"), err: true}, - {s: newString("as"), err: true}, - {s: newString(".0000000001s"), err: true}, - {s: newString(fmt.Sprint(math.MaxInt32) + "s"), want: newDuration(math.MaxInt32 * time.Second)}, - {s: newString(fmt.Sprint(int64(math.MaxInt32)+1) + "s"), err: true}, - } - for _, tc := range testCases { - got, err := parseDuration(tc.s) - if tc.err != (err != nil) || - (got == nil) != (tc.want == nil) || - (got != nil && *got != *tc.want) { - wantErr := "" - if tc.err { - wantErr = "" - } - s := "" - if tc.s != nil { - s = `&"` + *tc.s + `"` - } - t.Errorf("parseDuration(%v) = %v, %v; want %v, %v", s, got, err, tc.want, wantErr) - } - } -} - -func newBool(b bool) *bool { - return &b -} - -func newDuration(b time.Duration) *time.Duration { - return &b -} - -func newString(b string) *string { - return &b -} diff --git a/examples/google.golang.org/grpc/stats/grpc_testing/test.pb.go b/examples/google.golang.org/grpc/stats/grpc_testing/test.pb.go deleted file mode 100755 index 9db10f8..0000000 --- a/examples/google.golang.org/grpc/stats/grpc_testing/test.pb.go +++ /dev/null @@ -1,403 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SimpleRequest struct { - Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_dd7ffeaa75513a0a, []int{0} -} -func (m *SimpleRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleRequest.Unmarshal(m, b) -} -func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic) -} -func (dst *SimpleRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleRequest.Merge(dst, src) -} -func (m *SimpleRequest) XXX_Size() int { - return xxx_messageInfo_SimpleRequest.Size(m) -} -func (m *SimpleRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo - -func (m *SimpleRequest) GetId() int32 { - if m != nil { - return m.Id - } - return 0 -} - -type SimpleResponse struct { - Id int32 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_dd7ffeaa75513a0a, []int{1} -} -func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) -} -func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) -} -func (dst *SimpleResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleResponse.Merge(dst, src) -} -func (m *SimpleResponse) XXX_Size() int { - return xxx_messageInfo_SimpleResponse.Size(m) -} -func (m *SimpleResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo - -func (m *SimpleResponse) GetId() int32 { - if m != nil { - return m.Id - } - return 0 -} - -func init() { - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// TestServiceClient is the client API for TestService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TestServiceClient interface { - // One request followed by one response. - // The server returns the client id as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // Client stream - ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) - // Server stream - ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*SimpleRequest) error - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) ClientStreamCall(ctx context.Context, opts ...grpc.CallOption) (TestService_ClientStreamCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/ClientStreamCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceClientStreamCallClient{stream} - return x, nil -} - -type TestService_ClientStreamCallClient interface { - Send(*SimpleRequest) error - CloseAndRecv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceClientStreamCallClient struct { - grpc.ClientStream -} - -func (x *testServiceClientStreamCallClient) Send(m *SimpleRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceClientStreamCallClient) CloseAndRecv() (*SimpleResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) ServerStreamCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (TestService_ServerStreamCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/ServerStreamCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceServerStreamCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_ServerStreamCallClient interface { - Recv() (*SimpleResponse, error) - grpc.ClientStream -} - -type testServiceServerStreamCallClient struct { - grpc.ClientStream -} - -func (x *testServiceServerStreamCallClient) Recv() (*SimpleResponse, error) { - m := new(SimpleResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// TestServiceServer is the server API for TestService service. -type TestServiceServer interface { - // One request followed by one response. - // The server returns the client id as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // Client stream - ClientStreamCall(TestService_ClientStreamCallServer) error - // Server stream - ServerStreamCall(*SimpleRequest, TestService_ServerStreamCallServer) error -} - -func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { - s.RegisterService(&_TestService_serviceDesc, srv) -} - -func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_ClientStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).ClientStreamCall(&testServiceClientStreamCallServer{stream}) -} - -type TestService_ClientStreamCallServer interface { - SendAndClose(*SimpleResponse) error - Recv() (*SimpleRequest, error) - grpc.ServerStream -} - -type testServiceClientStreamCallServer struct { - grpc.ServerStream -} - -func (x *testServiceClientStreamCallServer) SendAndClose(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceClientStreamCallServer) Recv() (*SimpleRequest, error) { - m := new(SimpleRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_ServerStreamCall_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(SimpleRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServiceServer).ServerStreamCall(m, &testServiceServerStreamCallServer{stream}) -} - -type TestService_ServerStreamCallServer interface { - Send(*SimpleResponse) error - grpc.ServerStream -} - -type testServiceServerStreamCallServer struct { - grpc.ServerStream -} - -func (x *testServiceServerStreamCallServer) Send(m *SimpleResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "FullDuplexCall", - Handler: _TestService_FullDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "ClientStreamCall", - Handler: _TestService_ClientStreamCall_Handler, - ClientStreams: true, - }, - { - StreamName: "ServerStreamCall", - Handler: _TestService_ServerStreamCall_Handler, - ServerStreams: true, - }, - }, - Metadata: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor_test_dd7ffeaa75513a0a) } - -var fileDescriptor_test_dd7ffeaa75513a0a = []byte{ - // 202 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0x2f, 0x2a, 0x48, - 0x8e, 0x2f, 0x49, 0x2d, 0x2e, 0xc9, 0xcc, 0x4b, 0xd7, 0x07, 0xd1, 0x7a, 0x05, 0x45, 0xf9, 0x25, - 0xf9, 0x42, 0x3c, 0x20, 0x09, 0x3d, 0xa8, 0x84, 0x92, 0x3c, 0x17, 0x6f, 0x70, 0x66, 0x6e, 0x41, - 0x4e, 0x6a, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x10, 0x1f, 0x17, 0x53, 0x66, 0x8a, 0x04, - 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x53, 0x66, 0x8a, 0x92, 0x02, 0x17, 0x1f, 0x4c, 0x41, 0x71, - 0x41, 0x7e, 0x5e, 0x71, 0x2a, 0x54, 0x05, 0x33, 0x4c, 0x85, 0xd1, 0x09, 0x26, 0x2e, 0xee, 0x90, - 0xd4, 0xe2, 0x92, 0xe0, 0xd4, 0xa2, 0xb2, 0xcc, 0xe4, 0x54, 0x21, 0x37, 0x2e, 0xce, 0xd0, 0xbc, - 0xc4, 0xa2, 0x4a, 0xe7, 0xc4, 0x9c, 0x1c, 0x21, 0x69, 0x3d, 0x64, 0xeb, 0xf4, 0x50, 0xec, 0x92, - 0x92, 0xc1, 0x2e, 0x09, 0xb5, 0xc7, 0x9f, 0x8b, 0xcf, 0xad, 0x34, 0x27, 0xc7, 0xa5, 0xb4, 0x20, - 0x27, 0xb5, 0x82, 0x42, 0xc3, 0x34, 0x18, 0x0d, 0x18, 0x85, 0xfc, 0xb9, 0x04, 0x9c, 0x73, 0x32, - 0x53, 0xf3, 0x4a, 0x82, 0x4b, 0x8a, 0x52, 0x13, 0x73, 0x29, 0x36, 0x12, 0x64, 0x20, 0xc8, 0xd3, - 0xa9, 0x45, 0x54, 0x31, 0xd0, 0x80, 0x31, 0x89, 0x0d, 0x1c, 0x45, 0xc6, 0x80, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x4c, 0x43, 0x27, 0x67, 0xbd, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/stats/grpc_testing/test.proto b/examples/google.golang.org/grpc/stats/grpc_testing/test.proto deleted file mode 100755 index b49a0d5..0000000 --- a/examples/google.golang.org/grpc/stats/grpc_testing/test.proto +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -message SimpleRequest { - int32 id = 2; -} - -message SimpleResponse { - int32 id = 3; -} - -// A simple test service. -service TestService { - // One request followed by one response. - // The server returns the client id as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream SimpleRequest) returns (stream SimpleResponse); - - // Client stream - rpc ClientStreamCall(stream SimpleRequest) returns (SimpleResponse); - - // Server stream - rpc ServerStreamCall(SimpleRequest) returns (stream SimpleResponse); -} diff --git a/examples/google.golang.org/grpc/stats/handlers.go b/examples/google.golang.org/grpc/stats/handlers.go deleted file mode 100755 index 05b384c..0000000 --- a/examples/google.golang.org/grpc/stats/handlers.go +++ /dev/null @@ -1,64 +0,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. - * - */ - -package stats - -import ( - "net" - - "golang.org/x/net/context" -) - -// ConnTagInfo defines the relevant information needed by connection context tagger. -type ConnTagInfo struct { - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr -} - -// RPCTagInfo defines the relevant information needed by RPC context tagger. -type RPCTagInfo struct { - // FullMethodName is the RPC method in the format of /package.service/method. - FullMethodName string - // FailFast indicates if this RPC is failfast. - // This field is only valid on client side, it's always false on server side. - FailFast bool -} - -// Handler defines the interface for the related stats handling (e.g., RPCs, connections). -type Handler interface { - // TagRPC can attach some information to the given context. - // The context used for the rest lifetime of the RPC will be derived from - // the returned context. - TagRPC(context.Context, *RPCTagInfo) context.Context - // HandleRPC processes the RPC stats. - HandleRPC(context.Context, RPCStats) - - // TagConn can attach some information to the given context. - // The returned context will be used for stats handling. - // For conn stats handling, the context used in HandleConn for this - // connection will be derived from the context returned. - // For RPC stats handling, - // - On server side, the context used in HandleRPC for all RPCs on this - // connection will be derived from the context returned. - // - On client side, the context is not derived from the context returned. - TagConn(context.Context, *ConnTagInfo) context.Context - // HandleConn processes the Conn stats. - HandleConn(context.Context, ConnStats) -} diff --git a/examples/google.golang.org/grpc/stats/stats.go b/examples/google.golang.org/grpc/stats/stats.go deleted file mode 100755 index 3f13190..0000000 --- a/examples/google.golang.org/grpc/stats/stats.go +++ /dev/null @@ -1,296 +0,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. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -// Package stats is for collecting and reporting various network and RPC stats. -// This package is for monitoring purpose only. All fields are read-only. -// All APIs are experimental. -package stats // import "google.golang.org/grpc/stats" - -import ( - "net" - "time" - - "golang.org/x/net/context" -) - -// RPCStats contains stats information about RPCs. -type RPCStats interface { - isRPCStats() - // IsClient returns true if this RPCStats is from client side. - IsClient() bool -} - -// Begin contains stats when an RPC begins. -// FailFast is only valid if this Begin is from client side. -type Begin struct { - // Client is true if this Begin is from client side. - Client bool - // BeginTime is the time when the RPC begins. - BeginTime time.Time - // FailFast indicates if this RPC is failfast. - FailFast bool -} - -// IsClient indicates if the stats information is from client side. -func (s *Begin) IsClient() bool { return s.Client } - -func (s *Begin) isRPCStats() {} - -// InPayload contains the information for an incoming payload. -type InPayload struct { - // Client is true if this InPayload is from client side. - Client bool - // Payload is the payload with original type. - Payload interface{} - // Data is the serialized message payload. - Data []byte - // Length is the length of uncompressed data. - Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). - WireLength int - // RecvTime is the time when the payload is received. - RecvTime time.Time -} - -// IsClient indicates if the stats information is from client side. -func (s *InPayload) IsClient() bool { return s.Client } - -func (s *InPayload) isRPCStats() {} - -// InHeader contains stats when a header is received. -type InHeader struct { - // Client is true if this InHeader is from client side. - Client bool - // WireLength is the wire length of header. - WireLength int - - // The following fields are valid only if Client is false. - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string -} - -// IsClient indicates if the stats information is from client side. -func (s *InHeader) IsClient() bool { return s.Client } - -func (s *InHeader) isRPCStats() {} - -// InTrailer contains stats when a trailer is received. -type InTrailer struct { - // Client is true if this InTrailer is from client side. - Client bool - // WireLength is the wire length of trailer. - WireLength int -} - -// IsClient indicates if the stats information is from client side. -func (s *InTrailer) IsClient() bool { return s.Client } - -func (s *InTrailer) isRPCStats() {} - -// OutPayload contains the information for an outgoing payload. -type OutPayload struct { - // Client is true if this OutPayload is from client side. - Client bool - // Payload is the payload with original type. - Payload interface{} - // Data is the serialized message payload. - Data []byte - // Length is the length of uncompressed data. - Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). - WireLength int - // SentTime is the time when the payload is sent. - SentTime time.Time -} - -// IsClient indicates if this stats information is from client side. -func (s *OutPayload) IsClient() bool { return s.Client } - -func (s *OutPayload) isRPCStats() {} - -// OutHeader contains stats when a header is sent. -type OutHeader struct { - // Client is true if this OutHeader is from client side. - Client bool - - // The following fields are valid only if Client is true. - // FullMethod is the full RPC method string, i.e., /package.service/method. - FullMethod string - // RemoteAddr is the remote address of the corresponding connection. - RemoteAddr net.Addr - // LocalAddr is the local address of the corresponding connection. - LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string -} - -// IsClient indicates if this stats information is from client side. -func (s *OutHeader) IsClient() bool { return s.Client } - -func (s *OutHeader) isRPCStats() {} - -// OutTrailer contains stats when a trailer is sent. -type OutTrailer struct { - // Client is true if this OutTrailer is from client side. - Client bool - // WireLength is the wire length of trailer. - WireLength int -} - -// IsClient indicates if this stats information is from client side. -func (s *OutTrailer) IsClient() bool { return s.Client } - -func (s *OutTrailer) isRPCStats() {} - -// End contains stats when an RPC ends. -type End struct { - // Client is true if this End is from client side. - Client bool - // BeginTime is the time when the RPC began. - BeginTime time.Time - // EndTime is the time when the RPC ends. - EndTime time.Time - // Error is the error the RPC ended with. It is an error generated from - // status.Status and can be converted back to status.Status using - // status.FromError if non-nil. - Error error -} - -// IsClient indicates if this is from client side. -func (s *End) IsClient() bool { return s.Client } - -func (s *End) isRPCStats() {} - -// ConnStats contains stats information about connections. -type ConnStats interface { - isConnStats() - // IsClient returns true if this ConnStats is from client side. - IsClient() bool -} - -// ConnBegin contains the stats of a connection when it is established. -type ConnBegin struct { - // Client is true if this ConnBegin is from client side. - Client bool -} - -// IsClient indicates if this is from client side. -func (s *ConnBegin) IsClient() bool { return s.Client } - -func (s *ConnBegin) isConnStats() {} - -// ConnEnd contains the stats of a connection when it ends. -type ConnEnd struct { - // Client is true if this ConnEnd is from client side. - Client bool -} - -// IsClient indicates if this is from client side. -func (s *ConnEnd) IsClient() bool { return s.Client } - -func (s *ConnEnd) isConnStats() {} - -type incomingTagsKey struct{} -type outgoingTagsKey struct{} - -// SetTags attaches stats tagging data to the context, which will be sent in -// the outgoing RPC with the header grpc-tags-bin. Subsequent calls to -// SetTags will overwrite the values from earlier calls. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func SetTags(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, outgoingTagsKey{}, b) -} - -// Tags returns the tags from the context for the inbound RPC. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func Tags(ctx context.Context) []byte { - b, _ := ctx.Value(incomingTagsKey{}).([]byte) - return b -} - -// SetIncomingTags attaches stats tagging data to the context, to be read by -// the application (not sent in outgoing RPCs). -// -// This is intended for gRPC-internal use ONLY. -func SetIncomingTags(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, incomingTagsKey{}, b) -} - -// OutgoingTags returns the tags from the context for the outbound RPC. -// -// This is intended for gRPC-internal use ONLY. -func OutgoingTags(ctx context.Context) []byte { - b, _ := ctx.Value(outgoingTagsKey{}).([]byte) - return b -} - -type incomingTraceKey struct{} -type outgoingTraceKey struct{} - -// SetTrace attaches stats tagging data to the context, which will be sent in -// the outgoing RPC with the header grpc-trace-bin. Subsequent calls to -// SetTrace will overwrite the values from earlier calls. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func SetTrace(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, outgoingTraceKey{}, b) -} - -// Trace returns the trace from the context for the inbound RPC. -// -// NOTE: this is provided only for backward compatibility with existing clients -// and will likely be removed in an upcoming release. New uses should transmit -// this type of data using metadata with a different, non-reserved (i.e. does -// not begin with "grpc-") header name. -func Trace(ctx context.Context) []byte { - b, _ := ctx.Value(incomingTraceKey{}).([]byte) - return b -} - -// SetIncomingTrace attaches stats tagging data to the context, to be read by -// the application (not sent in outgoing RPCs). It is intended for -// gRPC-internal use. -func SetIncomingTrace(ctx context.Context, b []byte) context.Context { - return context.WithValue(ctx, incomingTraceKey{}, b) -} - -// OutgoingTrace returns the trace from the context for the outbound RPC. It is -// intended for gRPC-internal use. -func OutgoingTrace(ctx context.Context) []byte { - b, _ := ctx.Value(outgoingTraceKey{}).([]byte) - return b -} diff --git a/examples/google.golang.org/grpc/stats/stats_test.go b/examples/google.golang.org/grpc/stats/stats_test.go deleted file mode 100755 index 00a5e4f..0000000 --- a/examples/google.golang.org/grpc/stats/stats_test.go +++ /dev/null @@ -1,1257 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package stats_test - -import ( - "fmt" - "io" - "net" - "reflect" - "sync" - "testing" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - testpb "google.golang.org/grpc/stats/grpc_testing" - "google.golang.org/grpc/status" -) - -func init() { - grpc.EnableTracing = false -} - -type connCtxKey struct{} -type rpcCtxKey struct{} - -var ( - // For headers: - testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, - } - // For trailers: - testTrailerMetadata = metadata.MD{ - "tkey1": []string{"trailerValue1"}, - "tkey2": []string{"trailerValue2"}, - } - // The id for which the service handler should return error. - errorID int32 = 32202 -) - -type testServer struct{} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - if ok { - if err := grpc.SendHeader(ctx, md); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SendHeader(_, %v) = %v, want ", md, err) - } - if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetTrailer(_, %v) = %v, want ", testTrailerMetadata, err) - } - } - - if in.Id == errorID { - return nil, fmt.Errorf("got error id: %v", in.Id) - } - - return &testpb.SimpleResponse{Id: in.Id}, nil -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - - if err := stream.Send(&testpb.SimpleResponse{Id: in.Id}); err != nil { - return err - } - } -} - -func (s *testServer) ClientStreamCall(stream testpb.TestService_ClientStreamCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return stream.SendAndClose(&testpb.SimpleResponse{Id: int32(0)}) - } - if err != nil { - return err - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - } -} - -func (s *testServer) ServerStreamCall(in *testpb.SimpleRequest, stream testpb.TestService_ServerStreamCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - - for i := 0; i < 5; i++ { - if err := stream.Send(&testpb.SimpleResponse{Id: in.Id}); err != nil { - return err - } - } - return nil -} - -// test is an end-to-end test. It should be created with the newTest -// func, modified as needed, and then started with its startServer method. -// It should be cleaned up with the tearDown method. -type test struct { - t *testing.T - compress string - clientStatsHandler stats.Handler - serverStatsHandler stats.Handler - - testServer testpb.TestServiceServer // nil means none - // srv and srvAddr are set once startServer is called. - srv *grpc.Server - srvAddr string - - cc *grpc.ClientConn // nil until requested via clientConn -} - -func (te *test) tearDown() { - if te.cc != nil { - te.cc.Close() - te.cc = nil - } - te.srv.Stop() -} - -type testConfig struct { - compress string -} - -// newTest returns a new test using the provided testing.T and -// environment. It is returned with default values. Tests should -// modify it before calling its startServer and clientConn methods. -func newTest(t *testing.T, tc *testConfig, ch stats.Handler, sh stats.Handler) *test { - te := &test{ - t: t, - compress: tc.compress, - clientStatsHandler: ch, - serverStatsHandler: sh, - } - return te -} - -// startServer starts a gRPC server listening. Callers should defer a -// call to te.tearDown to clean up. -func (te *test) startServer(ts testpb.TestServiceServer) { - te.testServer = ts - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - te.t.Fatalf("Failed to listen: %v", err) - } - var opts []grpc.ServerOption - if te.compress == "gzip" { - opts = append(opts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.serverStatsHandler != nil { - opts = append(opts, grpc.StatsHandler(te.serverStatsHandler)) - } - s := grpc.NewServer(opts...) - te.srv = s - if te.testServer != nil { - testpb.RegisterTestServiceServer(s, te.testServer) - } - - go s.Serve(lis) - te.srvAddr = lis.Addr().String() -} - -func (te *test) clientConn() *grpc.ClientConn { - if te.cc != nil { - return te.cc - } - opts := []grpc.DialOption{grpc.WithInsecure(), grpc.WithBlock()} - if te.compress == "gzip" { - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.clientStatsHandler != nil { - opts = append(opts, grpc.WithStatsHandler(te.clientStatsHandler)) - } - - var err error - te.cc, err = grpc.Dial(te.srvAddr, opts...) - if err != nil { - te.t.Fatalf("Dial(%q) = %v", te.srvAddr, err) - } - return te.cc -} - -type rpcType int - -const ( - unaryRPC rpcType = iota - clientStreamRPC - serverStreamRPC - fullDuplexStreamRPC -) - -type rpcConfig struct { - count int // Number of requests and responses for streaming RPCs. - success bool // Whether the RPC should succeed or return error. - failfast bool - callType rpcType // Type of RPC. -} - -func (te *test) doUnaryCall(c *rpcConfig) (*testpb.SimpleRequest, *testpb.SimpleResponse, error) { - var ( - resp *testpb.SimpleResponse - req *testpb.SimpleRequest - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - if c.success { - req = &testpb.SimpleRequest{Id: errorID + 1} - } else { - req = &testpb.SimpleRequest{Id: errorID} - } - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - - resp, err = tc.UnaryCall(ctx, req, grpc.FailFast(c.failfast)) - return req, resp, err -} - -func (te *test) doFullDuplexCallRoundtrip(c *rpcConfig) ([]*testpb.SimpleRequest, []*testpb.SimpleResponse, error) { - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - stream, err := tc.FullDuplexCall(metadata.NewOutgoingContext(context.Background(), testMetadata), grpc.FailFast(c.failfast)) - if err != nil { - return reqs, resps, err - } - var startID int32 - if !c.success { - startID = errorID - } - for i := 0; i < c.count; i++ { - req := &testpb.SimpleRequest{ - Id: int32(i) + startID, - } - reqs = append(reqs, req) - if err = stream.Send(req); err != nil { - return reqs, resps, err - } - var resp *testpb.SimpleResponse - if resp, err = stream.Recv(); err != nil { - return reqs, resps, err - } - resps = append(resps, resp) - } - if err = stream.CloseSend(); err != nil && err != io.EOF { - return reqs, resps, err - } - if _, err = stream.Recv(); err != io.EOF { - return reqs, resps, err - } - - return reqs, resps, nil -} - -func (te *test) doClientStreamCall(c *rpcConfig) ([]*testpb.SimpleRequest, *testpb.SimpleResponse, error) { - var ( - reqs []*testpb.SimpleRequest - resp *testpb.SimpleResponse - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - stream, err := tc.ClientStreamCall(metadata.NewOutgoingContext(context.Background(), testMetadata), grpc.FailFast(c.failfast)) - if err != nil { - return reqs, resp, err - } - var startID int32 - if !c.success { - startID = errorID - } - for i := 0; i < c.count; i++ { - req := &testpb.SimpleRequest{ - Id: int32(i) + startID, - } - reqs = append(reqs, req) - if err = stream.Send(req); err != nil { - return reqs, resp, err - } - } - resp, err = stream.CloseAndRecv() - return reqs, resp, err -} - -func (te *test) doServerStreamCall(c *rpcConfig) (*testpb.SimpleRequest, []*testpb.SimpleResponse, error) { - var ( - req *testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - ) - - tc := testpb.NewTestServiceClient(te.clientConn()) - - var startID int32 - if !c.success { - startID = errorID - } - req = &testpb.SimpleRequest{Id: startID} - stream, err := tc.ServerStreamCall(metadata.NewOutgoingContext(context.Background(), testMetadata), req, grpc.FailFast(c.failfast)) - if err != nil { - return req, resps, err - } - for { - var resp *testpb.SimpleResponse - resp, err := stream.Recv() - if err == io.EOF { - return req, resps, nil - } else if err != nil { - return req, resps, err - } - resps = append(resps, resp) - } -} - -type expectedData struct { - method string - serverAddr string - compression string - reqIdx int - requests []*testpb.SimpleRequest - respIdx int - responses []*testpb.SimpleResponse - err error - failfast bool -} - -type gotData struct { - ctx context.Context - client bool - s interface{} // This could be RPCStats or ConnStats. -} - -const ( - begin int = iota - end - inPayload - inHeader - inTrailer - outPayload - outHeader - outTrailer - connbegin - connend -) - -func checkBegin(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.Begin - ) - if st, ok = d.s.(*stats.Begin); !ok { - t.Fatalf("got %T, want Begin", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if st.BeginTime.IsZero() { - t.Fatalf("st.BeginTime = %v, want ", st.BeginTime) - } - if d.client { - if st.FailFast != e.failfast { - t.Fatalf("st.FailFast = %v, want %v", st.FailFast, e.failfast) - } - } -} - -func checkInHeader(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.InHeader - ) - if st, ok = d.s.(*stats.InHeader); !ok { - t.Fatalf("got %T, want InHeader", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if !d.client { - if st.FullMethod != e.method { - t.Fatalf("st.FullMethod = %s, want %v", st.FullMethod, e.method) - } - if st.LocalAddr.String() != e.serverAddr { - t.Fatalf("st.LocalAddr = %v, want %v", st.LocalAddr, e.serverAddr) - } - if st.Compression != e.compression { - t.Fatalf("st.Compression = %v, want %v", st.Compression, e.compression) - } - - if connInfo, ok := d.ctx.Value(connCtxKey{}).(*stats.ConnTagInfo); ok { - if connInfo.RemoteAddr != st.RemoteAddr { - t.Fatalf("connInfo.RemoteAddr = %v, want %v", connInfo.RemoteAddr, st.RemoteAddr) - } - if connInfo.LocalAddr != st.LocalAddr { - t.Fatalf("connInfo.LocalAddr = %v, want %v", connInfo.LocalAddr, st.LocalAddr) - } - } else { - t.Fatalf("got context %v, want one with connCtxKey", d.ctx) - } - if rpcInfo, ok := d.ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo); ok { - if rpcInfo.FullMethodName != st.FullMethod { - t.Fatalf("rpcInfo.FullMethod = %s, want %v", rpcInfo.FullMethodName, st.FullMethod) - } - } else { - t.Fatalf("got context %v, want one with rpcCtxKey", d.ctx) - } - } -} - -func checkInPayload(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.InPayload - ) - if st, ok = d.s.(*stats.InPayload); !ok { - t.Fatalf("got %T, want InPayload", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if d.client { - b, err := proto.Marshal(e.responses[e.respIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.responses[e.respIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.responses[e.respIdx]) - } - e.respIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } else { - b, err := proto.Marshal(e.requests[e.reqIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.requests[e.reqIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.requests[e.reqIdx]) - } - e.reqIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } - // TODO check WireLength and ReceivedTime. - if st.RecvTime.IsZero() { - t.Fatalf("st.ReceivedTime = %v, want ", st.RecvTime) - } -} - -func checkInTrailer(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - ) - if _, ok = d.s.(*stats.InTrailer); !ok { - t.Fatalf("got %T, want InTrailer", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } -} - -func checkOutHeader(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutHeader - ) - if st, ok = d.s.(*stats.OutHeader); !ok { - t.Fatalf("got %T, want OutHeader", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if d.client { - if st.FullMethod != e.method { - t.Fatalf("st.FullMethod = %s, want %v", st.FullMethod, e.method) - } - if st.RemoteAddr.String() != e.serverAddr { - t.Fatalf("st.RemoteAddr = %v, want %v", st.RemoteAddr, e.serverAddr) - } - if st.Compression != e.compression { - t.Fatalf("st.Compression = %v, want %v", st.Compression, e.compression) - } - - if rpcInfo, ok := d.ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo); ok { - if rpcInfo.FullMethodName != st.FullMethod { - t.Fatalf("rpcInfo.FullMethod = %s, want %v", rpcInfo.FullMethodName, st.FullMethod) - } - } else { - t.Fatalf("got context %v, want one with rpcCtxKey", d.ctx) - } - } -} - -func checkOutPayload(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutPayload - ) - if st, ok = d.s.(*stats.OutPayload); !ok { - t.Fatalf("got %T, want OutPayload", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if d.client { - b, err := proto.Marshal(e.requests[e.reqIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.requests[e.reqIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.requests[e.reqIdx]) - } - e.reqIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } else { - b, err := proto.Marshal(e.responses[e.respIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.responses[e.respIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.responses[e.respIdx]) - } - e.respIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } - // TODO check WireLength and ReceivedTime. - if st.SentTime.IsZero() { - t.Fatalf("st.SentTime = %v, want ", st.SentTime) - } -} - -func checkOutTrailer(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutTrailer - ) - if st, ok = d.s.(*stats.OutTrailer); !ok { - t.Fatalf("got %T, want OutTrailer", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if st.Client { - t.Fatalf("st IsClient = true, want false") - } -} - -func checkEnd(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.End - ) - if st, ok = d.s.(*stats.End); !ok { - t.Fatalf("got %T, want End", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - if st.BeginTime.IsZero() { - t.Fatalf("st.BeginTime = %v, want ", st.BeginTime) - } - if st.EndTime.IsZero() { - t.Fatalf("st.EndTime = %v, want ", st.EndTime) - } - - actual, ok := status.FromError(st.Error) - if !ok { - t.Fatalf("expected st.Error to be a statusError, got %v (type %T)", st.Error, st.Error) - } - - expectedStatus, _ := status.FromError(e.err) - if actual.Code() != expectedStatus.Code() || actual.Message() != expectedStatus.Message() { - t.Fatalf("st.Error = %v, want %v", st.Error, e.err) - } -} - -func checkConnBegin(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.ConnBegin - ) - if st, ok = d.s.(*stats.ConnBegin); !ok { - t.Fatalf("got %T, want ConnBegin", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - st.IsClient() // TODO remove this. -} - -func checkConnEnd(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.ConnEnd - ) - if st, ok = d.s.(*stats.ConnEnd); !ok { - t.Fatalf("got %T, want ConnEnd", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want ") - } - st.IsClient() // TODO remove this. -} - -type statshandler struct { - mu sync.Mutex - gotRPC []*gotData - gotConn []*gotData -} - -func (h *statshandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context { - return context.WithValue(ctx, connCtxKey{}, info) -} - -func (h *statshandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - return context.WithValue(ctx, rpcCtxKey{}, info) -} - -func (h *statshandler) HandleConn(ctx context.Context, s stats.ConnStats) { - h.mu.Lock() - defer h.mu.Unlock() - h.gotConn = append(h.gotConn, &gotData{ctx, s.IsClient(), s}) -} - -func (h *statshandler) HandleRPC(ctx context.Context, s stats.RPCStats) { - h.mu.Lock() - defer h.mu.Unlock() - h.gotRPC = append(h.gotRPC, &gotData{ctx, s.IsClient(), s}) -} - -func checkConnStats(t *testing.T, got []*gotData) { - if len(got) <= 0 || len(got)%2 != 0 { - for i, g := range got { - t.Errorf(" - %v, %T = %+v, ctx: %v", i, g.s, g.s, g.ctx) - } - t.Fatalf("got %v stats, want even positive number", len(got)) - } - // The first conn stats must be a ConnBegin. - checkConnBegin(t, got[0], nil) - // The last conn stats must be a ConnEnd. - checkConnEnd(t, got[len(got)-1], nil) -} - -func checkServerStats(t *testing.T, got []*gotData, expect *expectedData, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { - if len(got) != len(checkFuncs) { - for i, g := range got { - t.Errorf(" - %v, %T", i, g.s) - } - t.Fatalf("got %v stats, want %v stats", len(got), len(checkFuncs)) - } - - var rpcctx context.Context - for i := 0; i < len(got); i++ { - if _, ok := got[i].s.(stats.RPCStats); ok { - if rpcctx != nil && got[i].ctx != rpcctx { - t.Fatalf("got different contexts with stats %T", got[i].s) - } - rpcctx = got[i].ctx - } - } - - for i, f := range checkFuncs { - f(t, got[i], expect) - } -} - -func testServerStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { - h := &statshandler{} - te := newTest(t, tc, nil, h) - te.startServer(&testServer{}) - defer te.tearDown() - - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - method string - - req *testpb.SimpleRequest - resp *testpb.SimpleResponse - e error - ) - - switch cc.callType { - case unaryRPC: - method = "/grpc.testing.TestService/UnaryCall" - req, resp, e = te.doUnaryCall(cc) - reqs = []*testpb.SimpleRequest{req} - resps = []*testpb.SimpleResponse{resp} - err = e - case clientStreamRPC: - method = "/grpc.testing.TestService/ClientStreamCall" - reqs, resp, e = te.doClientStreamCall(cc) - resps = []*testpb.SimpleResponse{resp} - err = e - case serverStreamRPC: - method = "/grpc.testing.TestService/ServerStreamCall" - req, resps, e = te.doServerStreamCall(cc) - reqs = []*testpb.SimpleRequest{req} - err = e - case fullDuplexStreamRPC: - method = "/grpc.testing.TestService/FullDuplexCall" - reqs, resps, err = te.doFullDuplexCallRoundtrip(cc) - } - if cc.success != (err == nil) { - t.Fatalf("cc.success: %v, got error: %v", cc.success, err) - } - te.cc.Close() - te.srv.GracefulStop() // Wait for the server to stop. - - for { - h.mu.Lock() - if len(h.gotRPC) >= len(checkFuncs) { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - for { - h.mu.Lock() - if _, ok := h.gotConn[len(h.gotConn)-1].s.(*stats.ConnEnd); ok { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - expect := &expectedData{ - serverAddr: te.srvAddr, - compression: tc.compress, - method: method, - requests: reqs, - responses: resps, - err: err, - } - - h.mu.Lock() - checkConnStats(t, h.gotConn) - h.mu.Unlock() - checkServerStats(t, h.gotRPC, expect, checkFuncs) -} - -func TestServerStatsUnaryRPC(t *testing.T) { - testServerStats(t, &testConfig{compress: ""}, &rpcConfig{success: true, callType: unaryRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutPayload, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsUnaryRPCError(t *testing.T) { - testServerStats(t, &testConfig{compress: ""}, &rpcConfig{success: false, callType: unaryRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsClientStreamRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutPayload, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: clientStreamRPC}, checkFuncs) -} - -func TestServerStatsClientStreamRPCError(t *testing.T) { - count := 1 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: clientStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - checkInPayload, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsServerStreamRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkOutPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: serverStreamRPC}, checkFuncs) -} - -func TestServerStatsServerStreamRPCError(t *testing.T) { - count := 5 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: serverStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsFullDuplexRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInPayload, - checkOutPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: fullDuplexStreamRPC}, checkFuncs) -} - -func TestServerStatsFullDuplexRPCError(t *testing.T) { - count := 5 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: fullDuplexStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - checkInPayload, - checkOutTrailer, - checkEnd, - }) -} - -type checkFuncWithCount struct { - f func(t *testing.T, d *gotData, e *expectedData) - c int // expected count -} - -func checkClientStats(t *testing.T, got []*gotData, expect *expectedData, checkFuncs map[int]*checkFuncWithCount) { - var expectLen int - for _, v := range checkFuncs { - expectLen += v.c - } - if len(got) != expectLen { - for i, g := range got { - t.Errorf(" - %v, %T", i, g.s) - } - t.Fatalf("got %v stats, want %v stats", len(got), expectLen) - } - - var tagInfoInCtx *stats.RPCTagInfo - for i := 0; i < len(got); i++ { - if _, ok := got[i].s.(stats.RPCStats); ok { - tagInfoInCtxNew, _ := got[i].ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo) - if tagInfoInCtx != nil && tagInfoInCtx != tagInfoInCtxNew { - t.Fatalf("got context containing different tagInfo with stats %T", got[i].s) - } - tagInfoInCtx = tagInfoInCtxNew - } - } - - for _, s := range got { - switch s.s.(type) { - case *stats.Begin: - if checkFuncs[begin].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[begin].f(t, s, expect) - checkFuncs[begin].c-- - case *stats.OutHeader: - if checkFuncs[outHeader].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[outHeader].f(t, s, expect) - checkFuncs[outHeader].c-- - case *stats.OutPayload: - if checkFuncs[outPayload].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[outPayload].f(t, s, expect) - checkFuncs[outPayload].c-- - case *stats.InHeader: - if checkFuncs[inHeader].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inHeader].f(t, s, expect) - checkFuncs[inHeader].c-- - case *stats.InPayload: - if checkFuncs[inPayload].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inPayload].f(t, s, expect) - checkFuncs[inPayload].c-- - case *stats.InTrailer: - if checkFuncs[inTrailer].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inTrailer].f(t, s, expect) - checkFuncs[inTrailer].c-- - case *stats.End: - if checkFuncs[end].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[end].f(t, s, expect) - checkFuncs[end].c-- - case *stats.ConnBegin: - if checkFuncs[connbegin].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[connbegin].f(t, s, expect) - checkFuncs[connbegin].c-- - case *stats.ConnEnd: - if checkFuncs[connend].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[connend].f(t, s, expect) - checkFuncs[connend].c-- - default: - t.Fatalf("unexpected stats: %T", s.s) - } - } -} - -func testClientStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs map[int]*checkFuncWithCount) { - h := &statshandler{} - te := newTest(t, tc, h, nil) - te.startServer(&testServer{}) - defer te.tearDown() - - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - method string - err error - - req *testpb.SimpleRequest - resp *testpb.SimpleResponse - e error - ) - switch cc.callType { - case unaryRPC: - method = "/grpc.testing.TestService/UnaryCall" - req, resp, e = te.doUnaryCall(cc) - reqs = []*testpb.SimpleRequest{req} - resps = []*testpb.SimpleResponse{resp} - err = e - case clientStreamRPC: - method = "/grpc.testing.TestService/ClientStreamCall" - reqs, resp, e = te.doClientStreamCall(cc) - resps = []*testpb.SimpleResponse{resp} - err = e - case serverStreamRPC: - method = "/grpc.testing.TestService/ServerStreamCall" - req, resps, e = te.doServerStreamCall(cc) - reqs = []*testpb.SimpleRequest{req} - err = e - case fullDuplexStreamRPC: - method = "/grpc.testing.TestService/FullDuplexCall" - reqs, resps, err = te.doFullDuplexCallRoundtrip(cc) - } - if cc.success != (err == nil) { - t.Fatalf("cc.success: %v, got error: %v", cc.success, err) - } - te.cc.Close() - te.srv.GracefulStop() // Wait for the server to stop. - - lenRPCStats := 0 - for _, v := range checkFuncs { - lenRPCStats += v.c - } - for { - h.mu.Lock() - if len(h.gotRPC) >= lenRPCStats { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - for { - h.mu.Lock() - if _, ok := h.gotConn[len(h.gotConn)-1].s.(*stats.ConnEnd); ok { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - expect := &expectedData{ - serverAddr: te.srvAddr, - compression: tc.compress, - method: method, - requests: reqs, - responses: resps, - failfast: cc.failfast, - err: err, - } - - h.mu.Lock() - checkConnStats(t, h.gotConn) - h.mu.Unlock() - checkClientStats(t, h.gotRPC, expect, checkFuncs) -} - -func TestClientStatsUnaryRPC(t *testing.T) { - testClientStats(t, &testConfig{compress: ""}, &rpcConfig{success: true, failfast: false, callType: unaryRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsUnaryRPCError(t *testing.T) { - testClientStats(t, &testConfig{compress: ""}, &rpcConfig{success: false, failfast: false, callType: unaryRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsClientStreamRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: clientStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - inHeader: {checkInHeader, 1}, - outPayload: {checkOutPayload, count}, - inTrailer: {checkInTrailer, 1}, - inPayload: {checkInPayload, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsClientStreamRPCError(t *testing.T) { - count := 1 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: clientStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - inHeader: {checkInHeader, 1}, - outPayload: {checkOutPayload, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsServerStreamRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: serverStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, count}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsServerStreamRPCError(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: serverStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsFullDuplexRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: fullDuplexStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, count}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, count}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsFullDuplexRPCError(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: fullDuplexStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestTags(t *testing.T) { - b := []byte{5, 2, 4, 3, 1} - ctx := stats.SetTags(context.Background(), b) - if tg := stats.OutgoingTags(ctx); !reflect.DeepEqual(tg, b) { - t.Errorf("OutgoingTags(%v) = %v; want %v", ctx, tg, b) - } - if tg := stats.Tags(ctx); tg != nil { - t.Errorf("Tags(%v) = %v; want nil", ctx, tg) - } - - ctx = stats.SetIncomingTags(context.Background(), b) - if tg := stats.Tags(ctx); !reflect.DeepEqual(tg, b) { - t.Errorf("Tags(%v) = %v; want %v", ctx, tg, b) - } - if tg := stats.OutgoingTags(ctx); tg != nil { - t.Errorf("OutgoingTags(%v) = %v; want nil", ctx, tg) - } -} - -func TestTrace(t *testing.T) { - b := []byte{5, 2, 4, 3, 1} - ctx := stats.SetTrace(context.Background(), b) - if tr := stats.OutgoingTrace(ctx); !reflect.DeepEqual(tr, b) { - t.Errorf("OutgoingTrace(%v) = %v; want %v", ctx, tr, b) - } - if tr := stats.Trace(ctx); tr != nil { - t.Errorf("Trace(%v) = %v; want nil", ctx, tr) - } - - ctx = stats.SetIncomingTrace(context.Background(), b) - if tr := stats.Trace(ctx); !reflect.DeepEqual(tr, b) { - t.Errorf("Trace(%v) = %v; want %v", ctx, tr, b) - } - if tr := stats.OutgoingTrace(ctx); tr != nil { - t.Errorf("OutgoingTrace(%v) = %v; want nil", ctx, tr) - } -} diff --git a/examples/google.golang.org/grpc/status/go16.go b/examples/google.golang.org/grpc/status/go16.go deleted file mode 100755 index e59b53e..0000000 --- a/examples/google.golang.org/grpc/status/go16.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * 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. - * - */ - -package status - -import ( - "golang.org/x/net/context" - "google.golang.org/grpc/codes" -) - -// FromContextError converts a context error into a Status. It returns a -// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is -// non-nil and not a context error. -func FromContextError(err error) *Status { - switch err { - case nil: - return New(codes.OK, "") - case context.DeadlineExceeded: - return New(codes.DeadlineExceeded, err.Error()) - case context.Canceled: - return New(codes.Canceled, err.Error()) - default: - return New(codes.Unknown, err.Error()) - } -} diff --git a/examples/google.golang.org/grpc/status/go17.go b/examples/google.golang.org/grpc/status/go17.go deleted file mode 100755 index 0902151..0000000 --- a/examples/google.golang.org/grpc/status/go17.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build go1.7 - -/* - * - * 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. - * - */ - -package status - -import ( - "context" - - netctx "golang.org/x/net/context" - "google.golang.org/grpc/codes" -) - -// FromContextError converts a context error into a Status. It returns a -// Status with codes.OK if err is nil, or a Status with codes.Unknown if err is -// non-nil and not a context error. -func FromContextError(err error) *Status { - switch err { - case nil: - return New(codes.OK, "") - case context.DeadlineExceeded, netctx.DeadlineExceeded: - return New(codes.DeadlineExceeded, err.Error()) - case context.Canceled, netctx.Canceled: - return New(codes.Canceled, err.Error()) - default: - return New(codes.Unknown, err.Error()) - } -} diff --git a/examples/google.golang.org/grpc/status/go17_test.go b/examples/google.golang.org/grpc/status/go17_test.go deleted file mode 100755 index 2dc5add..0000000 --- a/examples/google.golang.org/grpc/status/go17_test.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build go1.7 - -/* - * - * 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. - * - */ - -package status - -import ( - "context" - "testing" - - "google.golang.org/grpc/codes" -) - -func TestFromStdContextError(t *testing.T) { - testCases := []struct { - in error - want *Status - }{ - {in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())}, - {in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())}, - } - for _, tc := range testCases { - got := FromContextError(tc.in) - if got.Code() != tc.want.Code() || got.Message() != tc.want.Message() { - t.Errorf("FromContextError(%v) = %v; want %v", tc.in, got, tc.want) - } - } -} diff --git a/examples/google.golang.org/grpc/status/status.go b/examples/google.golang.org/grpc/status/status.go deleted file mode 100755 index 9c61b09..0000000 --- a/examples/google.golang.org/grpc/status/status.go +++ /dev/null @@ -1,189 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package status implements errors returned by gRPC. These errors are -// serialized and transmitted on the wire between server and client, and allow -// for additional data to be transmitted via the Details field in the status -// proto. gRPC service handlers should return an error created by this -// package, and gRPC clients should expect a corresponding error to be -// returned from the RPC call. -// -// This package upholds the invariants that a non-nil error may not -// contain an OK code, and an OK code must result in a nil error. -package status - -import ( - "errors" - "fmt" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" -) - -// statusError is an alias of a status proto. It implements error and Status, -// and a nil statusError should never be returned by this package. -type statusError spb.Status - -func (se *statusError) Error() string { - p := (*spb.Status)(se) - return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage()) -} - -func (se *statusError) GRPCStatus() *Status { - return &Status{s: (*spb.Status)(se)} -} - -// Status represents an RPC status code, message, and details. It is immutable -// and should be created with New, Newf, or FromProto. -type Status struct { - s *spb.Status -} - -// Code returns the status code contained in s. -func (s *Status) Code() codes.Code { - if s == nil || s.s == nil { - return codes.OK - } - return codes.Code(s.s.Code) -} - -// Message returns the message contained in s. -func (s *Status) Message() string { - if s == nil || s.s == nil { - return "" - } - return s.s.Message -} - -// Proto returns s's status as an spb.Status proto message. -func (s *Status) Proto() *spb.Status { - if s == nil { - return nil - } - return proto.Clone(s.s).(*spb.Status) -} - -// Err returns an immutable error representing s; returns nil if s.Code() is -// OK. -func (s *Status) Err() error { - if s.Code() == codes.OK { - return nil - } - return (*statusError)(s.s) -} - -// New returns a Status representing c and msg. -func New(c codes.Code, msg string) *Status { - return &Status{s: &spb.Status{Code: int32(c), Message: msg}} -} - -// Newf returns New(c, fmt.Sprintf(format, a...)). -func Newf(c codes.Code, format string, a ...interface{}) *Status { - return New(c, fmt.Sprintf(format, a...)) -} - -// Error returns an error representing c and msg. If c is OK, returns nil. -func Error(c codes.Code, msg string) error { - return New(c, msg).Err() -} - -// Errorf returns Error(c, fmt.Sprintf(format, a...)). -func Errorf(c codes.Code, format string, a ...interface{}) error { - return Error(c, fmt.Sprintf(format, a...)) -} - -// ErrorProto returns an error representing s. If s.Code is OK, returns nil. -func ErrorProto(s *spb.Status) error { - return FromProto(s).Err() -} - -// FromProto returns a Status representing s. -func FromProto(s *spb.Status) *Status { - return &Status{s: proto.Clone(s).(*spb.Status)} -} - -// FromError returns a Status representing err if it was produced from this -// package or has a method `GRPCStatus() *Status`. Otherwise, ok is false and a -// Status is returned with codes.Unknown and the original error message. -func FromError(err error) (s *Status, ok bool) { - if err == nil { - return &Status{s: &spb.Status{Code: int32(codes.OK)}}, true - } - if se, ok := err.(interface{ GRPCStatus() *Status }); ok { - return se.GRPCStatus(), true - } - return New(codes.Unknown, err.Error()), false -} - -// Convert is a convenience function which removes the need to handle the -// boolean return value from FromError. -func Convert(err error) *Status { - s, _ := FromError(err) - return s -} - -// WithDetails returns a new status with the provided details messages appended to the status. -// If any errors are encountered, it returns nil and the first error encountered. -func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { - if s.Code() == codes.OK { - return nil, errors.New("no error details for status with code OK") - } - // s.Code() != OK implies that s.Proto() != nil. - p := s.Proto() - for _, detail := range details { - any, err := ptypes.MarshalAny(detail) - if err != nil { - return nil, err - } - p.Details = append(p.Details, any) - } - return &Status{s: p}, nil -} - -// Details returns a slice of details messages attached to the status. -// If a detail cannot be decoded, the error is returned in place of the detail. -func (s *Status) Details() []interface{} { - if s == nil || s.s == nil { - return nil - } - details := make([]interface{}, 0, len(s.s.Details)) - for _, any := range s.s.Details { - detail := &ptypes.DynamicAny{} - if err := ptypes.UnmarshalAny(any, detail); err != nil { - details = append(details, err) - continue - } - details = append(details, detail.Message) - } - return details -} - -// Code returns the Code of the error if it is a Status error, codes.OK if err -// is nil, or codes.Unknown otherwise. -func Code(err error) codes.Code { - // Don't use FromError to avoid allocation of OK status. - if err == nil { - return codes.OK - } - if se, ok := err.(interface{ GRPCStatus() *Status }); ok { - return se.GRPCStatus().Code() - } - return codes.Unknown -} diff --git a/examples/google.golang.org/grpc/status/status_test.go b/examples/google.golang.org/grpc/status/status_test.go deleted file mode 100755 index 1eb1320..0000000 --- a/examples/google.golang.org/grpc/status/status_test.go +++ /dev/null @@ -1,348 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package status - -import ( - "errors" - "fmt" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - apb "github.com/golang/protobuf/ptypes/any" - dpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - cpb "google.golang.org/genproto/googleapis/rpc/code" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" -) - -func TestErrorsWithSameParameters(t *testing.T) { - const description = "some description" - e1 := Errorf(codes.AlreadyExists, description) - e2 := Errorf(codes.AlreadyExists, description) - if e1 == e2 || !reflect.DeepEqual(e1, e2) { - t.Fatalf("Errors should be equivalent but unique - e1: %v, %v e2: %p, %v", e1.(*statusError), e1, e2.(*statusError), e2) - } -} - -func TestFromToProto(t *testing.T) { - s := &spb.Status{ - Code: int32(codes.Internal), - Message: "test test test", - Details: []*apb.Any{{TypeUrl: "foo", Value: []byte{3, 2, 1}}}, - } - - err := FromProto(s) - if got := err.Proto(); !proto.Equal(s, got) { - t.Fatalf("Expected errors to be identical - s: %v got: %v", s, got) - } -} - -func TestFromNilProto(t *testing.T) { - tests := []*Status{nil, FromProto(nil)} - for _, s := range tests { - if c := s.Code(); c != codes.OK { - t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c) - } - if m := s.Message(); m != "" { - t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m) - } - if p := s.Proto(); p != nil { - t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p) - } - if e := s.Err(); e != nil { - t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e) - } - } -} - -func TestError(t *testing.T) { - err := Error(codes.Internal, "test description") - if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want { - t.Fatalf("err.Error() = %q; want %q", got, want) - } - s, _ := FromError(err) - if got, want := s.Code(), codes.Internal; got != want { - t.Fatalf("err.Code() = %s; want %s", got, want) - } - if got, want := s.Message(), "test description"; got != want { - t.Fatalf("err.Message() = %s; want %s", got, want) - } -} - -func TestErrorOK(t *testing.T) { - err := Error(codes.OK, "foo") - if err != nil { - t.Fatalf("Error(codes.OK, _) = %p; want nil", err.(*statusError)) - } -} - -func TestErrorProtoOK(t *testing.T) { - s := &spb.Status{Code: int32(codes.OK)} - if got := ErrorProto(s); got != nil { - t.Fatalf("ErrorProto(%v) = %v; want nil", s, got) - } -} - -func TestFromError(t *testing.T) { - code, message := codes.Internal, "test description" - err := Error(code, message) - s, ok := FromError(err) - if !ok || s.Code() != code || s.Message() != message || s.Err() == nil { - t.Fatalf("FromError(%v) = %v, %v; want , true", err, s, ok, code, message) - } -} - -func TestFromErrorOK(t *testing.T) { - code, message := codes.OK, "" - s, ok := FromError(nil) - if !ok || s.Code() != code || s.Message() != message || s.Err() != nil { - t.Fatalf("FromError(nil) = %v, %v; want , true", s, ok, code, message) - } -} - -type customError struct { - Code codes.Code - Message string - Details []*apb.Any -} - -func (c customError) Error() string { - return fmt.Sprintf("rpc error: code = %s desc = %s", c.Code, c.Message) -} - -func (c customError) GRPCStatus() *Status { - return &Status{ - s: &spb.Status{ - Code: int32(c.Code), - Message: c.Message, - Details: c.Details, - }, - } -} - -func TestFromErrorImplementsInterface(t *testing.T) { - code, message := codes.Internal, "test description" - details := []*apb.Any{{ - TypeUrl: "testUrl", - Value: []byte("testValue"), - }} - err := customError{ - Code: code, - Message: message, - Details: details, - } - s, ok := FromError(err) - if !ok || s.Code() != code || s.Message() != message || s.Err() == nil { - t.Fatalf("FromError(%v) = %v, %v; want , true", err, s, ok, code, message) - } - pd := s.Proto().GetDetails() - if len(pd) != 1 || !reflect.DeepEqual(pd[0], details[0]) { - t.Fatalf("s.Proto.GetDetails() = %v; want ", pd, details) - } -} - -func TestFromErrorUnknownError(t *testing.T) { - code, message := codes.Unknown, "unknown error" - err := errors.New("unknown error") - s, ok := FromError(err) - if ok || s.Code() != code || s.Message() != message { - t.Fatalf("FromError(%v) = %v, %v; want , false", err, s, ok, code, message) - } -} - -func TestConvertKnownError(t *testing.T) { - code, message := codes.Internal, "test description" - err := Error(code, message) - s := Convert(err) - if s.Code() != code || s.Message() != message { - t.Fatalf("Convert(%v) = %v; want ", err, s, code, message) - } -} - -func TestConvertUnknownError(t *testing.T) { - code, message := codes.Unknown, "unknown error" - err := errors.New("unknown error") - s := Convert(err) - if s.Code() != code || s.Message() != message { - t.Fatalf("Convert(%v) = %v; want ", err, s, code, message) - } -} - -func TestStatus_ErrorDetails(t *testing.T) { - tests := []struct { - code codes.Code - details []proto.Message - }{ - { - code: codes.NotFound, - details: nil, - }, - { - code: codes.NotFound, - details: []proto.Message{ - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - { - code: codes.Internal, - details: []proto.Message{ - &epb.DebugInfo{ - StackEntries: []string{ - "first stack", - "second stack", - }, - }, - }, - }, - { - code: codes.Unavailable, - details: []proto.Message{ - &epb.RetryInfo{ - RetryDelay: &dpb.Duration{Seconds: 60}, - }, - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - } - - for _, tc := range tests { - s, err := New(tc.code, "").WithDetails(tc.details...) - if err != nil { - t.Fatalf("(%v).WithDetails(%+v) failed: %v", str(s), tc.details, err) - } - details := s.Details() - for i := range details { - if !proto.Equal(details[i].(proto.Message), tc.details[i]) { - t.Fatalf("(%v).Details()[%d] = %+v, want %+v", str(s), i, details[i], tc.details[i]) - } - } - } -} - -func TestStatus_WithDetails_Fail(t *testing.T) { - tests := []*Status{ - nil, - FromProto(nil), - New(codes.OK, ""), - } - for _, s := range tests { - if s, err := s.WithDetails(); err == nil || s != nil { - t.Fatalf("(%v).WithDetails(%+v) = %v, %v; want nil, non-nil", str(s), []proto.Message{}, s, err) - } - } -} - -func TestStatus_ErrorDetails_Fail(t *testing.T) { - tests := []struct { - s *Status - i []interface{} - }{ - { - nil, - nil, - }, - { - FromProto(nil), - nil, - }, - { - New(codes.OK, ""), - []interface{}{}, - }, - { - FromProto(&spb.Status{ - Code: int32(cpb.Code_CANCELLED), - Details: []*apb.Any{ - { - TypeUrl: "", - Value: []byte{}, - }, - mustMarshalAny(&epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }), - }, - }), - []interface{}{ - errors.New(`message type url "" is invalid`), - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - } - for _, tc := range tests { - got := tc.s.Details() - if !reflect.DeepEqual(got, tc.i) { - t.Errorf("(%v).Details() = %+v, want %+v", str(tc.s), got, tc.i) - } - } -} - -func str(s *Status) string { - if s == nil { - return "nil" - } - if s.s == nil { - return "" - } - return fmt.Sprintf("", codes.Code(s.s.GetCode()), s.s.GetMessage(), s.s.GetDetails()) -} - -// mustMarshalAny converts a protobuf message to an any. -func mustMarshalAny(msg proto.Message) *apb.Any { - any, err := ptypes.MarshalAny(msg) - if err != nil { - panic(fmt.Sprintf("ptypes.MarshalAny(%+v) failed: %v", msg, err)) - } - return any -} - -func TestFromContextError(t *testing.T) { - testCases := []struct { - in error - want *Status - }{ - {in: nil, want: New(codes.OK, "")}, - {in: context.DeadlineExceeded, want: New(codes.DeadlineExceeded, context.DeadlineExceeded.Error())}, - {in: context.Canceled, want: New(codes.Canceled, context.Canceled.Error())}, - {in: errors.New("other"), want: New(codes.Unknown, "other")}, - } - for _, tc := range testCases { - got := FromContextError(tc.in) - if got.Code() != tc.want.Code() || got.Message() != tc.want.Message() { - t.Errorf("FromContextError(%v) = %v; want %v", tc.in, got, tc.want) - } - } -} diff --git a/examples/google.golang.org/grpc/stickiness_linkedmap.go b/examples/google.golang.org/grpc/stickiness_linkedmap.go deleted file mode 100755 index 1c726af..0000000 --- a/examples/google.golang.org/grpc/stickiness_linkedmap.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * 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. - * - */ - -package grpc - -import ( - "container/list" -) - -type linkedMapKVPair struct { - key string - value *stickyStoreEntry -} - -// linkedMap is an implementation of a map that supports removing the oldest -// entry. -// -// linkedMap is NOT thread safe. -// -// It's for use of stickiness only! -type linkedMap struct { - m map[string]*list.Element - l *list.List // Head of the list is the oldest element. -} - -// newLinkedMap returns a new LinkedMap. -func newLinkedMap() *linkedMap { - return &linkedMap{ - m: make(map[string]*list.Element), - l: list.New(), - } -} - -// put adds entry (key, value) to the map. Existing key will be overridden. -func (m *linkedMap) put(key string, value *stickyStoreEntry) { - if oldE, ok := m.m[key]; ok { - // Remove existing entry. - m.l.Remove(oldE) - } - e := m.l.PushBack(&linkedMapKVPair{key: key, value: value}) - m.m[key] = e -} - -// get returns the value of the given key. -func (m *linkedMap) get(key string) (*stickyStoreEntry, bool) { - e, ok := m.m[key] - if !ok { - return nil, false - } - m.l.MoveToBack(e) - return e.Value.(*linkedMapKVPair).value, true -} - -// remove removes key from the map, and returns the value. The map is not -// modified if key is not in the map. -func (m *linkedMap) remove(key string) (*stickyStoreEntry, bool) { - e, ok := m.m[key] - if !ok { - return nil, false - } - delete(m.m, key) - m.l.Remove(e) - return e.Value.(*linkedMapKVPair).value, true -} - -// len returns the len of the map. -func (m *linkedMap) len() int { - return len(m.m) -} - -// clear removes all elements from the map. -func (m *linkedMap) clear() { - m.m = make(map[string]*list.Element) - m.l = list.New() -} - -// removeOldest removes the oldest key from the map. -func (m *linkedMap) removeOldest() { - e := m.l.Front() - m.l.Remove(e) - delete(m.m, e.Value.(*linkedMapKVPair).key) -} diff --git a/examples/google.golang.org/grpc/stickiness_linkedmap_test.go b/examples/google.golang.org/grpc/stickiness_linkedmap_test.go deleted file mode 100755 index e2d7635..0000000 --- a/examples/google.golang.org/grpc/stickiness_linkedmap_test.go +++ /dev/null @@ -1,186 +0,0 @@ -/* - * - * 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. - * - */ - -package grpc - -import ( - "container/list" - "fmt" - "reflect" - "testing" -) - -var linkedMapTestData = make([]*stickyStoreEntry, 5) - -func TestLinkedMapPutGet(t *testing.T) { - m := newLinkedMap() - m.put("one", linkedMapTestData[0]) - if got, ok := m.get("one"); !ok || got != linkedMapTestData[0] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 1, got, ok, "one") - } - m.put("two", linkedMapTestData[1]) - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } - m.put("oneone", linkedMapTestData[4]) - if got, ok := m.get("one"); !ok || got != linkedMapTestData[4] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 1, got, ok, "oneone") - } -} - -func TestLinkedMapRemove(t *testing.T) { - m := newLinkedMap() - m.put("one", linkedMapTestData[0]) - if got, ok := m.get("one"); !ok || got != linkedMapTestData[0] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 1, got, ok, "one") - } - m.put("two", linkedMapTestData[1]) - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } - - if got, ok := m.remove("one"); !ok || got != linkedMapTestData[0] { - t.Errorf("m.Remove(%v) = %v, %v, want %v, true", 1, got, ok, "one") - } - if got, ok := m.get("one"); ok { - t.Errorf("m.Get(%v) = %v, %v, want _, false", 1, got, ok) - } - // 2 should still in the map. - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } -} - -func TestLinkedMapLen(t *testing.T) { - m := newLinkedMap() - if got := m.len(); got != 0 { - t.Errorf("m.Len() = %v, want %v", got, 0) - } - m.put("one", linkedMapTestData[0]) - if got := m.len(); got != 1 { - t.Errorf("m.Len() = %v, want %v", got, 1) - } - m.put("two", linkedMapTestData[1]) - if got := m.len(); got != 2 { - t.Errorf("m.Len() = %v, want %v", got, 2) - } - m.put("one", linkedMapTestData[4]) - if got := m.len(); got != 2 { - t.Errorf("m.Len() = %v, want %v", got, 2) - } - - // Internal checks. - if got := len(m.m); got != 2 { - t.Errorf("len(m.m) = %v, want %v", got, 2) - } - if got := m.l.Len(); got != 2 { - t.Errorf("m.l.Len() = %v, want %v", got, 2) - } -} - -func TestLinkedMapClear(t *testing.T) { - m := newLinkedMap() - m.put("one", linkedMapTestData[0]) - if got, ok := m.get("one"); !ok || got != linkedMapTestData[0] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 1, got, ok, "one") - } - m.put("two", linkedMapTestData[1]) - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } - - m.clear() - if got, ok := m.get("one"); ok { - t.Errorf("m.Get(%v) = %v, %v, want _, false", 1, got, ok) - } - if got, ok := m.get("two"); ok { - t.Errorf("m.Get(%v) = %v, %v, want _, false", 2, got, ok) - } - if got := m.len(); got != 0 { - t.Errorf("m.Len() = %v, want %v", got, 0) - } -} - -func TestLinkedMapRemoveOldest(t *testing.T) { - m := newLinkedMap() - m.put("one", linkedMapTestData[0]) - m.put("two", linkedMapTestData[1]) - m.put("three", linkedMapTestData[2]) - m.put("four", linkedMapTestData[3]) - if got, ok := m.get("one"); !ok || got != linkedMapTestData[0] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 1, got, ok, "one") - } - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } - if got, ok := m.get("three"); !ok || got != linkedMapTestData[2] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 3, got, ok, "three") - } - if got, ok := m.get("four"); !ok || got != linkedMapTestData[3] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 4, got, ok, "four") - } - - if err := checkListOrdered(m.l, []string{"one", "two", "three", "four"}); err != nil { - t.Fatalf("m.l is not expected: %v", err) - } - - m.put("three", linkedMapTestData[2]) - if err := checkListOrdered(m.l, []string{"one", "two", "four", "three"}); err != nil { - t.Fatalf("m.l is not expected: %v", err) - } - m.put("four", linkedMapTestData[3]) - if err := checkListOrdered(m.l, []string{"one", "two", "three", "four"}); err != nil { - t.Fatalf("m.l is not expected: %v", err) - } - - m.removeOldest() - if got, ok := m.get("one"); ok { - t.Errorf("m.Get(%v) = %v, %v, want _, false", 1, got, ok) - } - if err := checkListOrdered(m.l, []string{"two", "three", "four"}); err != nil { - t.Fatalf("m.l is not expected: %v", err) - } - - m.get("two") // 2 is refreshed, 3 becomes the oldest - if err := checkListOrdered(m.l, []string{"three", "four", "two"}); err != nil { - t.Fatalf("m.l is not expected: %v", err) - } - - m.removeOldest() - if got, ok := m.get("three"); ok { - t.Errorf("m.Get(%v) = %v, %v, want _, false", 3, got, ok) - } - // 2 and 4 are still in map. - if got, ok := m.get("two"); !ok || got != linkedMapTestData[1] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 2, got, ok, "two") - } - if got, ok := m.get("four"); !ok || got != linkedMapTestData[3] { - t.Errorf("m.Get(%v) = %v, %v, want %v, true", 4, got, ok, "four") - } -} - -func checkListOrdered(l *list.List, want []string) error { - got := make([]string, 0, len(want)) - for p := l.Front(); p != nil; p = p.Next() { - got = append(got, p.Value.(*linkedMapKVPair).key) - } - if !reflect.DeepEqual(got, want) { - return fmt.Errorf("list elements: %v, want %v", got, want) - } - return nil -} diff --git a/examples/google.golang.org/grpc/stickiness_test.go b/examples/google.golang.org/grpc/stickiness_test.go deleted file mode 100755 index f625d68..0000000 --- a/examples/google.golang.org/grpc/stickiness_test.go +++ /dev/null @@ -1,288 +0,0 @@ -/* - * - * 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. - * - */ - -package grpc - -import ( - "fmt" - "math" - "strings" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer/roundrobin" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" -) - -func TestStickyKeyFromContext(t *testing.T) { - for _, test := range []struct { - org, add []string - mdKey string - wantStr string - wantBool bool - }{ - {[]string{}, []string{}, "", "", false}, - {[]string{"k1", "v1"}, []string{"k2", "v2"}, "k", "", false}, - - {[]string{"k", "v"}, []string{}, "k", "v", true}, - {[]string{}, []string{"k", "v"}, "k", "v", true}, - {[]string{"k1", "v1"}, []string{"k2", "v2"}, "k1", "v1", true}, - {[]string{"k1", "v1"}, []string{"k2", "v2"}, "k2", "v2", true}, - } { - ctx := context.Background() - if len(test.org) > 0 { - ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs(test.org...)) - } - if len(test.add) > 0 { - ctx = metadata.AppendToOutgoingContext(ctx, test.add...) - } - got, ok := stickyKeyFromContext(ctx, test.mdKey) - if got != test.wantStr || ok != test.wantBool { - t.Errorf("test: %+v, got: %q, %v, want: %q, %v\n", test, got, ok, test.wantStr, test.wantBool) - } - } -} - -func TestStickinessServiceConfig(t *testing.T) { - envConfigStickinessOn = true - defer func() { envConfigStickinessOn = false }() - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - - const testInput = "testStickinessKey" - wantStr := strings.ToLower(testInput) - - r.NewServiceConfig(fmt.Sprintf(`{"stickinessMetadataKey": "%v"}`, testInput)) // ToLower() will be applied to the input. - - for i := 0; i < 1000; i++ { - if key := cc.blockingpicker.getStickinessMDKey(); key == wantStr { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("cc.blockingpicker.stickiness.stickinessMDKey failed to change to %v within one second", wantStr) -} - -func TestStickinessEnd2end(t *testing.T) { - envConfigStickinessOn = true - defer func() { envConfigStickinessOn = false }() - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", - WithInsecure(), WithCodec(testCodec{}), WithBalancerName(roundrobin.Name)) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - req := "port" - var reply string - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - - var ( - i int - picked []int - ) - - // Check that each backend will be picked for at least 3 times. - picked = make([]int, 2, 2) - for i = 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil { - if errorDesc(err) == servers[0].port { - picked[0]++ - } else if errorDesc(err) == servers[1].port { - picked[1]++ - } - } - if picked[0] >= 3 && picked[1] >= 3 { - break - } - time.Sleep(time.Millisecond) - } - if i >= 1000 { - t.Fatalf("When doing roundrobin, addr1 was picked %v times, addr2 was picked %v times", picked[0], picked[1]) - } - - r.NewServiceConfig(fmt.Sprintf(`{"stickinessMetadataKey": "sessionid"}`)) - - // Should still be roundrobin. - picked = make([]int, 2, 2) - for i = 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil { - if errorDesc(err) == servers[0].port { - picked[0]++ - } else if errorDesc(err) == servers[1].port { - picked[1]++ - } - } - if picked[0] >= 3 && picked[1] >= 3 { - break - } - time.Sleep(time.Millisecond) - } - if i >= 1000 { - t.Fatalf("When doing roundrobin, addr1 was picked %v times, addr2 was picked %v times", picked[0], picked[1]) - } - - // Do sticky call, only one backend will be picked. - picked = make([]int, 2, 2) - for i = 0; i < 100; i++ { - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("sessionid", "1")) - if err = Invoke(ctx, "/foo/bar", &req, &reply, cc); err != nil { - if errorDesc(err) == servers[0].port { - picked[0]++ - } else if errorDesc(err) == servers[1].port { - picked[1]++ - } - } - time.Sleep(time.Millisecond) - } - - if (picked[0] != 0) == (picked[1] != 0) { - t.Fatalf("When doing sticky RPC, addr1 was picked %v times, addr2 was picked %v times, want at least one of them to be 0", picked[0], picked[1]) - } - -} - -// Changing stickinessMDKey in service config will clear the sticky map. -func TestStickinessChangeMDKey(t *testing.T) { - envConfigStickinessOn = true - defer func() { envConfigStickinessOn = false }() - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - req := "port" - var reply string - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - - r.NewServiceConfig(fmt.Sprintf(`{"stickinessMetadataKey": "sessionid"}`)) - - // Do sticky call, only one backend will be picked, and there will be one - // entry in stickiness map. - for i := 0; i < 100; i++ { - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("sessionid", "1")) - Invoke(ctx, "/foo/bar", &req, &reply, cc) - time.Sleep(time.Millisecond) - } - - cc.blockingpicker.stickiness.mu.Lock() - mapLen := cc.blockingpicker.stickiness.store.len() - cc.blockingpicker.stickiness.mu.Unlock() - if mapLen != 1 { - t.Fatalf("length of stickiness map is %v, want 1", mapLen) - } - - r.NewServiceConfig(fmt.Sprintf(`{"stickinessMetadataKey": "sessionidnew"}`)) - - var i int - for i = 0; i < 1000; i++ { - cc.blockingpicker.stickiness.mu.Lock() - mapLen = cc.blockingpicker.stickiness.store.len() - cc.blockingpicker.stickiness.mu.Unlock() - if mapLen == 0 { - break - } - time.Sleep(time.Millisecond) - } - if i >= 1000 { - t.Fatalf("After 1 second, length of stickiness map is %v, want 0", mapLen) - } -} - -// Switching balancer will clear the sticky map. -func TestStickinessSwitchingBalancer(t *testing.T) { - envConfigStickinessOn = true - defer func() { envConfigStickinessOn = false }() - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - req := "port" - var reply string - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - - r.NewServiceConfig(fmt.Sprintf(`{"stickinessMetadataKey": "sessionid"}`)) - - // Do sticky call, only one backend will be picked, and there will be one - // entry in stickiness map. - for i := 0; i < 100; i++ { - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("sessionid", "1")) - Invoke(ctx, "/foo/bar", &req, &reply, cc) - time.Sleep(time.Millisecond) - } - - cc.blockingpicker.stickiness.mu.Lock() - mapLen := cc.blockingpicker.stickiness.store.len() - cc.blockingpicker.stickiness.mu.Unlock() - if mapLen != 1 { - t.Fatalf("length of stickiness map is %v, want 1", mapLen) - } - - cc.mu.Lock() - cc.switchBalancer("round_robin") - cc.mu.Unlock() - - var i int - for i = 0; i < 1000; i++ { - cc.blockingpicker.stickiness.mu.Lock() - mapLen = cc.blockingpicker.stickiness.store.len() - cc.blockingpicker.stickiness.mu.Unlock() - if mapLen == 0 { - break - } - time.Sleep(time.Millisecond) - } - if i >= 1000 { - t.Fatalf("After 1 second, length of stickiness map is %v, want 0", mapLen) - } -} diff --git a/examples/google.golang.org/grpc/stream.go b/examples/google.golang.org/grpc/stream.go deleted file mode 100755 index 152d9ec..0000000 --- a/examples/google.golang.org/grpc/stream.go +++ /dev/null @@ -1,779 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package grpc - -import ( - "errors" - "io" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/trace" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/encoding" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" -) - -// StreamHandler defines the handler called by gRPC server to complete the -// execution of a streaming RPC. If a StreamHandler returns an error, it -// should be produced by the status package, or else gRPC will use -// codes.Unknown as the status code and err.Error() as the status message -// of the RPC. -type StreamHandler func(srv interface{}, stream ServerStream) error - -// StreamDesc represents a streaming RPC service's method specification. -type StreamDesc struct { - StreamName string - Handler StreamHandler - - // At least one of these is true. - ServerStreams bool - ClientStreams bool -} - -// Stream defines the common interface a client or server stream has to satisfy. -// -// All errors returned from Stream are compatible with the status package. -type Stream interface { - // Context returns the context for this stream. - Context() context.Context - // SendMsg blocks until it sends m, the stream is done or the stream - // breaks. - // On error, it aborts the stream and returns an RPC status on client - // side. On server side, it simply returns the error to the caller. - // SendMsg is called by generated code. Also Users can call SendMsg - // directly when it is really needed in their use cases. - // It's safe to have a goroutine calling SendMsg and another goroutine calling - // recvMsg on the same stream at the same time. - // But it is not safe to call SendMsg on the same stream in different goroutines. - SendMsg(m interface{}) error - // RecvMsg blocks until it receives a message or the stream is - // done. On client side, it returns io.EOF when the stream is done. On - // any other error, it aborts the stream and returns an RPC status. On - // server side, it simply returns the error to the caller. - // It's safe to have a goroutine calling SendMsg and another goroutine calling - // recvMsg on the same stream at the same time. - // But it is not safe to call RecvMsg on the same stream in different goroutines. - RecvMsg(m interface{}) error -} - -// ClientStream defines the interface a client stream has to satisfy. -type ClientStream interface { - // Header returns the header metadata received from the server if there - // is any. It blocks if the metadata is not ready to read. - Header() (metadata.MD, error) - // Trailer returns the trailer metadata from the server, if there is any. - // It must only be called after stream.CloseAndRecv has returned, or - // stream.Recv has returned a non-nil error (including io.EOF). - Trailer() metadata.MD - // CloseSend closes the send direction of the stream. It closes the stream - // when non-nil error is met. - CloseSend() error - // Stream.SendMsg() may return a non-nil error when something wrong happens sending - // the request. The returned error indicates the status of this sending, not the final - // status of the RPC. - // - // Always call Stream.RecvMsg() to drain the stream and get the final - // status, otherwise there could be leaked resources. - Stream -} - -// NewStream creates a new Stream for the client side. This is typically -// called by generated code. ctx is used for the lifetime of the stream. -// -// To ensure resources are not leaked due to the stream returned, one of the following -// actions must be performed: -// -// 1. Call Close on the ClientConn. -// 2. Cancel the context provided. -// 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated -// client-streaming RPC, for instance, might use the helper function -// CloseAndRecv (note that CloseSend does not Recv, therefore is not -// guaranteed to release all resources). -// 4. Receive a non-nil, non-io.EOF error from Header or SendMsg. -// -// If none of the above happen, a goroutine and a context will be leaked, and grpc -// will not call the optionally-configured stats handler with a stats.End message. -func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { - // allow interceptor to see all applicable call options, which means those - // configured as defaults from dial option as well as per-call options - opts = combine(cc.dopts.callOptions, opts) - - if cc.dopts.streamInt != nil { - return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) - } - return newClientStream(ctx, desc, cc, method, opts...) -} - -// NewClientStream is a wrapper for ClientConn.NewStream. -// -// DEPRECATED: Use ClientConn.NewStream instead. -func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { - return cc.NewStream(ctx, desc, method, opts...) -} - -func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { - if channelz.IsOn() { - cc.incrCallsStarted() - defer func() { - if err != nil { - cc.incrCallsFailed() - } - }() - } - c := defaultCallInfo() - mc := cc.GetMethodConfig(method) - if mc.WaitForReady != nil { - c.failFast = !*mc.WaitForReady - } - - // Possible context leak: - // The cancel function for the child context we create will only be called - // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if - // an error is generated by SendMsg. - // https://github.com/grpc/grpc-go/issues/1818. - var cancel context.CancelFunc - if mc.Timeout != nil && *mc.Timeout >= 0 { - ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) - } else { - ctx, cancel = context.WithCancel(ctx) - } - defer func() { - if err != nil { - cancel() - } - }() - - for _, o := range opts { - if err := o.before(c); err != nil { - return nil, toRPCErr(err) - } - } - c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize) - c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) - if err := setCallInfoCodec(c); err != nil { - return nil, err - } - - callHdr := &transport.CallHdr{ - Host: cc.authority, - Method: method, - // If it's not client streaming, we should already have the request to be sent, - // so we don't flush the header. - // If it's client streaming, the user may never send a request or send it any - // time soon, so we ask the transport to flush the header. - Flush: desc.ClientStreams, - ContentSubtype: c.contentSubtype, - } - - // Set our outgoing compression according to the UseCompressor CallOption, if - // set. In that case, also find the compressor from the encoding package. - // Otherwise, use the compressor configured by the WithCompressor DialOption, - // if set. - var cp Compressor - var comp encoding.Compressor - if ct := c.compressorType; ct != "" { - callHdr.SendCompress = ct - if ct != encoding.Identity { - comp = encoding.GetCompressor(ct) - if comp == nil { - return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) - } - } - } else if cc.dopts.cp != nil { - callHdr.SendCompress = cc.dopts.cp.Type() - cp = cc.dopts.cp - } - if c.creds != nil { - callHdr.Creds = c.creds - } - var trInfo traceInfo - if EnableTracing { - trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) - trInfo.firstLine.client = true - if deadline, ok := ctx.Deadline(); ok { - trInfo.firstLine.deadline = deadline.Sub(time.Now()) - } - trInfo.tr.LazyLog(&trInfo.firstLine, false) - ctx = trace.NewContext(ctx, trInfo.tr) - defer func() { - if err != nil { - // Need to call tr.finish() if error is returned. - // Because tr will not be returned to caller. - trInfo.tr.LazyPrintf("RPC: [%v]", err) - trInfo.tr.SetError() - trInfo.tr.Finish() - } - }() - } - ctx = newContextWithRPCInfo(ctx, c.failFast) - sh := cc.dopts.copts.StatsHandler - var beginTime time.Time - if sh != nil { - ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) - beginTime = time.Now() - begin := &stats.Begin{ - Client: true, - BeginTime: beginTime, - FailFast: c.failFast, - } - sh.HandleRPC(ctx, begin) - defer func() { - if err != nil { - // Only handle end stats if err != nil. - end := &stats.End{ - Client: true, - Error: err, - BeginTime: beginTime, - EndTime: time.Now(), - } - sh.HandleRPC(ctx, end) - } - }() - } - - var ( - t transport.ClientTransport - s *transport.Stream - done func(balancer.DoneInfo) - ) - for { - // Check to make sure the context has expired. This will prevent us from - // looping forever if an error occurs for wait-for-ready RPCs where no data - // is sent on the wire. - select { - case <-ctx.Done(): - return nil, toRPCErr(ctx.Err()) - default: - } - - t, done, err = cc.getTransport(ctx, c.failFast) - if err != nil { - return nil, err - } - - s, err = t.NewStream(ctx, callHdr) - if err != nil { - if done != nil { - done(balancer.DoneInfo{Err: err}) - done = nil - } - // In the event of any error from NewStream, we never attempted to write - // anything to the wire, so we can retry indefinitely for non-fail-fast - // RPCs. - if !c.failFast { - continue - } - return nil, toRPCErr(err) - } - break - } - - cs := &clientStream{ - opts: opts, - c: c, - cc: cc, - desc: desc, - codec: c.codec, - cp: cp, - comp: comp, - cancel: cancel, - attempt: &csAttempt{ - t: t, - s: s, - p: &parser{r: s}, - done: done, - dc: cc.dopts.dc, - ctx: ctx, - trInfo: trInfo, - statsHandler: sh, - beginTime: beginTime, - }, - } - cs.c.stream = cs - cs.attempt.cs = cs - if desc != unaryStreamDesc { - // Listen on cc and stream contexts to cleanup when the user closes the - // ClientConn or cancels the stream context. In all other cases, an error - // should already be injected into the recv buffer by the transport, which - // the client will eventually receive, and then we will cancel the stream's - // context in clientStream.finish. - go func() { - select { - case <-cc.ctx.Done(): - cs.finish(ErrClientConnClosing) - case <-ctx.Done(): - cs.finish(toRPCErr(ctx.Err())) - } - }() - } - return cs, nil -} - -// clientStream implements a client side Stream. -type clientStream struct { - opts []CallOption - c *callInfo - cc *ClientConn - desc *StreamDesc - - codec baseCodec - cp Compressor - comp encoding.Compressor - - cancel context.CancelFunc // cancels all attempts - - sentLast bool // sent an end stream - - mu sync.Mutex // guards finished - finished bool // TODO: replace with atomic cmpxchg or sync.Once? - - attempt *csAttempt // the active client stream attempt - // TODO(hedging): hedging will have multiple attempts simultaneously. -} - -// csAttempt implements a single transport stream attempt within a -// clientStream. -type csAttempt struct { - cs *clientStream - t transport.ClientTransport - s *transport.Stream - p *parser - done func(balancer.DoneInfo) - - dc Decompressor - decomp encoding.Compressor - decompSet bool - - ctx context.Context // the application's context, wrapped by stats/tracing - - mu sync.Mutex // guards trInfo.tr - // trInfo.tr is set when created (if EnableTracing is true), - // and cleared when the finish method is called. - trInfo traceInfo - - statsHandler stats.Handler - beginTime time.Time -} - -func (cs *clientStream) Context() context.Context { - // TODO(retry): commit the current attempt (the context has peer-aware data). - return cs.attempt.context() -} - -func (cs *clientStream) Header() (metadata.MD, error) { - m, err := cs.attempt.header() - if err != nil { - // TODO(retry): maybe retry on error or commit attempt on success. - err = toRPCErr(err) - cs.finish(err) - } - return m, err -} - -func (cs *clientStream) Trailer() metadata.MD { - // TODO(retry): on error, maybe retry (trailers-only). - return cs.attempt.trailer() -} - -func (cs *clientStream) SendMsg(m interface{}) (err error) { - // TODO(retry): buffer message for replaying if not committed. - return cs.attempt.sendMsg(m) -} - -func (cs *clientStream) RecvMsg(m interface{}) (err error) { - // TODO(retry): maybe retry on error or commit attempt on success. - return cs.attempt.recvMsg(m) -} - -func (cs *clientStream) CloseSend() error { - cs.attempt.closeSend() - return nil -} - -func (cs *clientStream) finish(err error) { - if err == io.EOF { - // Ending a stream with EOF indicates a success. - err = nil - } - cs.mu.Lock() - if cs.finished { - cs.mu.Unlock() - return - } - cs.finished = true - cs.mu.Unlock() - if channelz.IsOn() { - if err != nil { - cs.cc.incrCallsFailed() - } else { - cs.cc.incrCallsSucceeded() - } - } - // TODO(retry): commit current attempt if necessary. - cs.attempt.finish(err) - for _, o := range cs.opts { - o.after(cs.c) - } - cs.cancel() -} - -func (a *csAttempt) context() context.Context { - return a.s.Context() -} - -func (a *csAttempt) header() (metadata.MD, error) { - return a.s.Header() -} - -func (a *csAttempt) trailer() metadata.MD { - return a.s.Trailer() -} - -func (a *csAttempt) sendMsg(m interface{}) (err error) { - // TODO Investigate how to signal the stats handling party. - // generate error stats if err != nil && err != io.EOF? - cs := a.cs - defer func() { - // For non-client-streaming RPCs, we return nil instead of EOF on success - // because the generated code requires it. finish is not called; RecvMsg() - // will call it with the stream's status independently. - if err == io.EOF && !cs.desc.ClientStreams { - err = nil - } - if err != nil && err != io.EOF { - // Call finish on the client stream for errors generated by this SendMsg - // call, as these indicate problems created by this client. (Transport - // errors are converted to an io.EOF error below; the real error will be - // returned from RecvMsg eventually in that case, or be retried.) - cs.finish(err) - } - }() - // TODO: Check cs.sentLast and error if we already ended the stream. - if EnableTracing { - a.mu.Lock() - if a.trInfo.tr != nil { - a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) - } - a.mu.Unlock() - } - data, err := encode(cs.codec, m) - if err != nil { - return err - } - compData, err := compress(data, cs.cp, cs.comp) - if err != nil { - return err - } - hdr, payload := msgHeader(data, compData) - // TODO(dfawley): should we be checking len(data) instead? - if len(payload) > *cs.c.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), *cs.c.maxSendMessageSize) - } - - if !cs.desc.ClientStreams { - cs.sentLast = true - } - err = a.t.Write(a.s, hdr, payload, &transport.Options{Last: !cs.desc.ClientStreams}) - if err == nil { - if a.statsHandler != nil { - a.statsHandler.HandleRPC(a.ctx, outPayload(true, m, data, payload, time.Now())) - } - if channelz.IsOn() { - a.t.IncrMsgSent() - } - return nil - } - return io.EOF -} - -func (a *csAttempt) recvMsg(m interface{}) (err error) { - cs := a.cs - defer func() { - if err != nil || !cs.desc.ServerStreams { - // err != nil or non-server-streaming indicates end of stream. - cs.finish(err) - } - }() - var inPayload *stats.InPayload - if a.statsHandler != nil { - inPayload = &stats.InPayload{ - Client: true, - } - } - if !a.decompSet { - // Block until we receive headers containing received message encoding. - if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity { - if a.dc == nil || a.dc.Type() != ct { - // No configured decompressor, or it does not match the incoming - // message encoding; attempt to find a registered compressor that does. - a.dc = nil - a.decomp = encoding.GetCompressor(ct) - } - } else { - // No compression is used; disable our decompressor. - a.dc = nil - } - // Only initialize this state once per stream. - a.decompSet = true - } - err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, inPayload, a.decomp) - if err != nil { - if err == io.EOF { - if statusErr := a.s.Status().Err(); statusErr != nil { - return statusErr - } - return io.EOF // indicates successful end of stream. - } - return toRPCErr(err) - } - if EnableTracing { - a.mu.Lock() - if a.trInfo.tr != nil { - a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) - } - a.mu.Unlock() - } - if inPayload != nil { - a.statsHandler.HandleRPC(a.ctx, inPayload) - } - if channelz.IsOn() { - a.t.IncrMsgRecv() - } - if cs.desc.ServerStreams { - // Subsequent messages should be received by subsequent RecvMsg calls. - return nil - } - - // Special handling for non-server-stream rpcs. - // This recv expects EOF or errors, so we don't collect inPayload. - err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, nil, a.decomp) - if err == nil { - return toRPCErr(errors.New("grpc: client streaming protocol violation: get , want ")) - } - if err == io.EOF { - return a.s.Status().Err() // non-server streaming Recv returns nil on success - } - return toRPCErr(err) -} - -func (a *csAttempt) closeSend() { - cs := a.cs - if cs.sentLast { - return - } - cs.sentLast = true - cs.attempt.t.Write(cs.attempt.s, nil, nil, &transport.Options{Last: true}) - // We ignore errors from Write. Any error it would return would also be - // returned by a subsequent RecvMsg call, and the user is supposed to always - // finish the stream by calling RecvMsg until it returns err != nil. -} - -func (a *csAttempt) finish(err error) { - a.mu.Lock() - a.t.CloseStream(a.s, err) - - if a.done != nil { - a.done(balancer.DoneInfo{ - Err: err, - BytesSent: true, - BytesReceived: a.s.BytesReceived(), - }) - } - if a.statsHandler != nil { - end := &stats.End{ - Client: true, - BeginTime: a.beginTime, - EndTime: time.Now(), - Error: err, - } - a.statsHandler.HandleRPC(a.ctx, end) - } - if a.trInfo.tr != nil { - if err == nil { - a.trInfo.tr.LazyPrintf("RPC: [OK]") - } else { - a.trInfo.tr.LazyPrintf("RPC: [%v]", err) - a.trInfo.tr.SetError() - } - a.trInfo.tr.Finish() - a.trInfo.tr = nil - } - a.mu.Unlock() -} - -// ServerStream defines the interface a server stream has to satisfy. -type ServerStream interface { - // SetHeader sets the header metadata. It may be called multiple times. - // When call multiple times, all the provided metadata will be merged. - // All the metadata will be sent out when one of the following happens: - // - ServerStream.SendHeader() is called; - // - The first response is sent out; - // - An RPC status is sent out (error or success). - SetHeader(metadata.MD) error - // SendHeader sends the header metadata. - // The provided md and headers set by SetHeader() will be sent. - // It fails if called multiple times. - SendHeader(metadata.MD) error - // SetTrailer sets the trailer metadata which will be sent with the RPC status. - // When called more than once, all the provided metadata will be merged. - SetTrailer(metadata.MD) - Stream -} - -// serverStream implements a server side Stream. -type serverStream struct { - ctx context.Context - t transport.ServerTransport - s *transport.Stream - p *parser - codec baseCodec - - cp Compressor - dc Decompressor - comp encoding.Compressor - decomp encoding.Compressor - - maxReceiveMessageSize int - maxSendMessageSize int - trInfo *traceInfo - - statsHandler stats.Handler - - mu sync.Mutex // protects trInfo.tr after the service handler runs. -} - -func (ss *serverStream) Context() context.Context { - return ss.ctx -} - -func (ss *serverStream) SetHeader(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - return ss.s.SetHeader(md) -} - -func (ss *serverStream) SendHeader(md metadata.MD) error { - return ss.t.WriteHeader(ss.s, md) -} - -func (ss *serverStream) SetTrailer(md metadata.MD) { - if md.Len() == 0 { - return - } - ss.s.SetTrailer(md) -} - -func (ss *serverStream) SendMsg(m interface{}) (err error) { - defer func() { - if ss.trInfo != nil { - ss.mu.Lock() - if ss.trInfo.tr != nil { - if err == nil { - ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) - } else { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - } - ss.mu.Unlock() - } - if err != nil && err != io.EOF { - st, _ := status.FromError(toRPCErr(err)) - ss.t.WriteStatus(ss.s, st) - } - if channelz.IsOn() && err == nil { - ss.t.IncrMsgSent() - } - }() - data, err := encode(ss.codec, m) - if err != nil { - return err - } - compData, err := compress(data, ss.cp, ss.comp) - if err != nil { - return err - } - hdr, payload := msgHeader(data, compData) - // TODO(dfawley): should we be checking len(data) instead? - if len(payload) > ss.maxSendMessageSize { - return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(payload), ss.maxSendMessageSize) - } - if err := ss.t.Write(ss.s, hdr, payload, &transport.Options{Last: false}); err != nil { - return toRPCErr(err) - } - if ss.statsHandler != nil { - ss.statsHandler.HandleRPC(ss.s.Context(), outPayload(false, m, data, payload, time.Now())) - } - return nil -} - -func (ss *serverStream) RecvMsg(m interface{}) (err error) { - defer func() { - if ss.trInfo != nil { - ss.mu.Lock() - if ss.trInfo.tr != nil { - if err == nil { - ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) - } else if err != io.EOF { - ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) - ss.trInfo.tr.SetError() - } - } - ss.mu.Unlock() - } - if err != nil && err != io.EOF { - st, _ := status.FromError(toRPCErr(err)) - ss.t.WriteStatus(ss.s, st) - } - if channelz.IsOn() && err == nil { - ss.t.IncrMsgRecv() - } - }() - var inPayload *stats.InPayload - if ss.statsHandler != nil { - inPayload = &stats.InPayload{} - } - if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil { - if err == io.EOF { - return err - } - if err == io.ErrUnexpectedEOF { - err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) - } - return toRPCErr(err) - } - if inPayload != nil { - ss.statsHandler.HandleRPC(ss.s.Context(), inPayload) - } - return nil -} - -// MethodFromServerStream returns the method string for the input stream. -// The returned string is in the format of "/service/method". -func MethodFromServerStream(stream ServerStream) (string, bool) { - return Method(stream.Context()) -} diff --git a/examples/google.golang.org/grpc/stress/client/main.go b/examples/google.golang.org/grpc/stress/client/main.go deleted file mode 100755 index dab8a9d..0000000 --- a/examples/google.golang.org/grpc/stress/client/main.go +++ /dev/null @@ -1,337 +0,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. - * - */ - -//go:generate protoc -I ../grpc_testing --go_out=plugins=grpc:../grpc_testing ../grpc_testing/metrics.proto - -// client starts an interop client to do stress test and a metrics server to report qps. -package main - -import ( - "flag" - "fmt" - "math/rand" - "net" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/interop" - testpb "google.golang.org/grpc/interop/grpc_testing" - "google.golang.org/grpc/status" - metricspb "google.golang.org/grpc/stress/grpc_testing" - "google.golang.org/grpc/testdata" -) - -var ( - serverAddresses = flag.String("server_addresses", "localhost:8080", "a list of server addresses") - testCases = flag.String("test_cases", "", "a list of test cases along with the relative weights") - testDurationSecs = flag.Int("test_duration_secs", -1, "test duration in seconds") - numChannelsPerServer = flag.Int("num_channels_per_server", 1, "Number of channels (i.e connections) to each server") - numStubsPerChannel = flag.Int("num_stubs_per_channel", 1, "Number of client stubs per each connection to server") - metricsPort = flag.Int("metrics_port", 8081, "The port at which the stress client exposes QPS metrics") - useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP") - testCA = flag.Bool("use_test_ca", false, "Whether to replace platform root CAs with test CA as the CA root") - tlsServerName = flag.String("server_host_override", "foo.test.google.fr", "The server name use to verify the hostname returned by TLS handshake if it is not empty. Otherwise, --server_host is used.") - caFile = flag.String("ca_file", "", "The file containning the CA root cert file") -) - -// testCaseWithWeight contains the test case type and its weight. -type testCaseWithWeight struct { - name string - weight int -} - -// parseTestCases converts test case string to a list of struct testCaseWithWeight. -func parseTestCases(testCaseString string) []testCaseWithWeight { - testCaseStrings := strings.Split(testCaseString, ",") - testCases := make([]testCaseWithWeight, len(testCaseStrings)) - for i, str := range testCaseStrings { - testCase := strings.Split(str, ":") - if len(testCase) != 2 { - panic(fmt.Sprintf("invalid test case with weight: %s", str)) - } - // Check if test case is supported. - switch testCase[0] { - case - "empty_unary", - "large_unary", - "client_streaming", - "server_streaming", - "ping_pong", - "empty_stream", - "timeout_on_sleeping_server", - "cancel_after_begin", - "cancel_after_first_response", - "status_code_and_message", - "custom_metadata": - default: - panic(fmt.Sprintf("unknown test type: %s", testCase[0])) - } - testCases[i].name = testCase[0] - w, err := strconv.Atoi(testCase[1]) - if err != nil { - panic(fmt.Sprintf("%v", err)) - } - testCases[i].weight = w - } - return testCases -} - -// weightedRandomTestSelector defines a weighted random selector for test case types. -type weightedRandomTestSelector struct { - tests []testCaseWithWeight - totalWeight int -} - -// newWeightedRandomTestSelector constructs a weightedRandomTestSelector with the given list of testCaseWithWeight. -func newWeightedRandomTestSelector(tests []testCaseWithWeight) *weightedRandomTestSelector { - var totalWeight int - for _, t := range tests { - totalWeight += t.weight - } - rand.Seed(time.Now().UnixNano()) - return &weightedRandomTestSelector{tests, totalWeight} -} - -func (selector weightedRandomTestSelector) getNextTest() string { - random := rand.Intn(selector.totalWeight) - var weightSofar int - for _, test := range selector.tests { - weightSofar += test.weight - if random < weightSofar { - return test.name - } - } - panic("no test case selected by weightedRandomTestSelector") -} - -// gauge stores the qps of one interop client (one stub). -type gauge struct { - mutex sync.RWMutex - val int64 -} - -func (g *gauge) set(v int64) { - g.mutex.Lock() - defer g.mutex.Unlock() - g.val = v -} - -func (g *gauge) get() int64 { - g.mutex.RLock() - defer g.mutex.RUnlock() - return g.val -} - -// server implements metrics server functions. -type server struct { - mutex sync.RWMutex - // gauges is a map from /stress_test/server_/channel_/stub_/qps to its qps gauge. - gauges map[string]*gauge -} - -// newMetricsServer returns a new metrics server. -func newMetricsServer() *server { - return &server{gauges: make(map[string]*gauge)} -} - -// GetAllGauges returns all gauges. -func (s *server) GetAllGauges(in *metricspb.EmptyMessage, stream metricspb.MetricsService_GetAllGaugesServer) error { - s.mutex.RLock() - defer s.mutex.RUnlock() - - for name, gauge := range s.gauges { - if err := stream.Send(&metricspb.GaugeResponse{Name: name, Value: &metricspb.GaugeResponse_LongValue{LongValue: gauge.get()}}); err != nil { - return err - } - } - return nil -} - -// GetGauge returns the gauge for the given name. -func (s *server) GetGauge(ctx context.Context, in *metricspb.GaugeRequest) (*metricspb.GaugeResponse, error) { - s.mutex.RLock() - defer s.mutex.RUnlock() - - if g, ok := s.gauges[in.Name]; ok { - return &metricspb.GaugeResponse{Name: in.Name, Value: &metricspb.GaugeResponse_LongValue{LongValue: g.get()}}, nil - } - return nil, status.Errorf(codes.InvalidArgument, "gauge with name %s not found", in.Name) -} - -// createGauge creates a gauge using the given name in metrics server. -func (s *server) createGauge(name string) *gauge { - s.mutex.Lock() - defer s.mutex.Unlock() - - if _, ok := s.gauges[name]; ok { - // gauge already exists. - panic(fmt.Sprintf("gauge %s already exists", name)) - } - var g gauge - s.gauges[name] = &g - return &g -} - -func startServer(server *server, port int) { - lis, err := net.Listen("tcp", ":"+strconv.Itoa(port)) - if err != nil { - grpclog.Fatalf("failed to listen: %v", err) - } - - s := grpc.NewServer() - metricspb.RegisterMetricsServiceServer(s, server) - s.Serve(lis) - -} - -// performRPCs uses weightedRandomTestSelector to select test case and runs the tests. -func performRPCs(gauge *gauge, conn *grpc.ClientConn, selector *weightedRandomTestSelector, stop <-chan bool) { - client := testpb.NewTestServiceClient(conn) - var numCalls int64 - startTime := time.Now() - for { - test := selector.getNextTest() - switch test { - case "empty_unary": - interop.DoEmptyUnaryCall(client, grpc.FailFast(false)) - case "large_unary": - interop.DoLargeUnaryCall(client, grpc.FailFast(false)) - case "client_streaming": - interop.DoClientStreaming(client, grpc.FailFast(false)) - case "server_streaming": - interop.DoServerStreaming(client, grpc.FailFast(false)) - case "ping_pong": - interop.DoPingPong(client, grpc.FailFast(false)) - case "empty_stream": - interop.DoEmptyStream(client, grpc.FailFast(false)) - case "timeout_on_sleeping_server": - interop.DoTimeoutOnSleepingServer(client, grpc.FailFast(false)) - case "cancel_after_begin": - interop.DoCancelAfterBegin(client, grpc.FailFast(false)) - case "cancel_after_first_response": - interop.DoCancelAfterFirstResponse(client, grpc.FailFast(false)) - case "status_code_and_message": - interop.DoStatusCodeAndMessage(client, grpc.FailFast(false)) - case "custom_metadata": - interop.DoCustomMetadata(client, grpc.FailFast(false)) - } - numCalls++ - gauge.set(int64(float64(numCalls) / time.Since(startTime).Seconds())) - - select { - case <-stop: - return - default: - } - } -} - -func logParameterInfo(addresses []string, tests []testCaseWithWeight) { - grpclog.Infof("server_addresses: %s", *serverAddresses) - grpclog.Infof("test_cases: %s", *testCases) - grpclog.Infof("test_duration_secs: %d", *testDurationSecs) - grpclog.Infof("num_channels_per_server: %d", *numChannelsPerServer) - grpclog.Infof("num_stubs_per_channel: %d", *numStubsPerChannel) - grpclog.Infof("metrics_port: %d", *metricsPort) - grpclog.Infof("use_tls: %t", *useTLS) - grpclog.Infof("use_test_ca: %t", *testCA) - grpclog.Infof("server_host_override: %s", *tlsServerName) - - grpclog.Infoln("addresses:") - for i, addr := range addresses { - grpclog.Infof("%d. %s\n", i+1, addr) - } - grpclog.Infoln("tests:") - for i, test := range tests { - grpclog.Infof("%d. %v\n", i+1, test) - } -} - -func newConn(address string, useTLS, testCA bool, tlsServerName string) (*grpc.ClientConn, error) { - var opts []grpc.DialOption - if useTLS { - var sn string - if tlsServerName != "" { - sn = tlsServerName - } - var creds credentials.TransportCredentials - if testCA { - var err error - if *caFile == "" { - *caFile = testdata.Path("ca.pem") - } - creds, err = credentials.NewClientTLSFromFile(*caFile, sn) - if err != nil { - grpclog.Fatalf("Failed to create TLS credentials %v", err) - } - } else { - creds = credentials.NewClientTLSFromCert(nil, sn) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - } else { - opts = append(opts, grpc.WithInsecure()) - } - return grpc.Dial(address, opts...) -} - -func main() { - flag.Parse() - addresses := strings.Split(*serverAddresses, ",") - tests := parseTestCases(*testCases) - logParameterInfo(addresses, tests) - testSelector := newWeightedRandomTestSelector(tests) - metricsServer := newMetricsServer() - - var wg sync.WaitGroup - wg.Add(len(addresses) * *numChannelsPerServer * *numStubsPerChannel) - stop := make(chan bool) - - for serverIndex, address := range addresses { - for connIndex := 0; connIndex < *numChannelsPerServer; connIndex++ { - conn, err := newConn(address, *useTLS, *testCA, *tlsServerName) - if err != nil { - grpclog.Fatalf("Fail to dial: %v", err) - } - defer conn.Close() - for clientIndex := 0; clientIndex < *numStubsPerChannel; clientIndex++ { - name := fmt.Sprintf("/stress_test/server_%d/channel_%d/stub_%d/qps", serverIndex+1, connIndex+1, clientIndex+1) - go func() { - defer wg.Done() - g := metricsServer.createGauge(name) - performRPCs(g, conn, testSelector, stop) - }() - } - - } - } - go startServer(metricsServer, *metricsPort) - if *testDurationSecs > 0 { - time.Sleep(time.Duration(*testDurationSecs) * time.Second) - close(stop) - } - wg.Wait() - grpclog.Infof(" ===== ALL DONE ===== ") - -} diff --git a/examples/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go b/examples/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go deleted file mode 100755 index 31e95d2..0000000 --- a/examples/google.golang.org/grpc/stress/grpc_testing/metrics.pb.go +++ /dev/null @@ -1,429 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: metrics.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Response message containing the gauge name and value -type GaugeResponse struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - // Types that are valid to be assigned to Value: - // *GaugeResponse_LongValue - // *GaugeResponse_DoubleValue - // *GaugeResponse_StringValue - Value isGaugeResponse_Value `protobuf_oneof:"value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GaugeResponse) Reset() { *m = GaugeResponse{} } -func (m *GaugeResponse) String() string { return proto.CompactTextString(m) } -func (*GaugeResponse) ProtoMessage() {} -func (*GaugeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_metrics_c9a45afc44ac5637, []int{0} -} -func (m *GaugeResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GaugeResponse.Unmarshal(m, b) -} -func (m *GaugeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GaugeResponse.Marshal(b, m, deterministic) -} -func (dst *GaugeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_GaugeResponse.Merge(dst, src) -} -func (m *GaugeResponse) XXX_Size() int { - return xxx_messageInfo_GaugeResponse.Size(m) -} -func (m *GaugeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_GaugeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_GaugeResponse proto.InternalMessageInfo - -type isGaugeResponse_Value interface { - isGaugeResponse_Value() -} - -type GaugeResponse_LongValue struct { - LongValue int64 `protobuf:"varint,2,opt,name=long_value,json=longValue,proto3,oneof"` -} -type GaugeResponse_DoubleValue struct { - DoubleValue float64 `protobuf:"fixed64,3,opt,name=double_value,json=doubleValue,proto3,oneof"` -} -type GaugeResponse_StringValue struct { - StringValue string `protobuf:"bytes,4,opt,name=string_value,json=stringValue,proto3,oneof"` -} - -func (*GaugeResponse_LongValue) isGaugeResponse_Value() {} -func (*GaugeResponse_DoubleValue) isGaugeResponse_Value() {} -func (*GaugeResponse_StringValue) isGaugeResponse_Value() {} - -func (m *GaugeResponse) GetValue() isGaugeResponse_Value { - if m != nil { - return m.Value - } - return nil -} - -func (m *GaugeResponse) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *GaugeResponse) GetLongValue() int64 { - if x, ok := m.GetValue().(*GaugeResponse_LongValue); ok { - return x.LongValue - } - return 0 -} - -func (m *GaugeResponse) GetDoubleValue() float64 { - if x, ok := m.GetValue().(*GaugeResponse_DoubleValue); ok { - return x.DoubleValue - } - return 0 -} - -func (m *GaugeResponse) GetStringValue() string { - if x, ok := m.GetValue().(*GaugeResponse_StringValue); ok { - return x.StringValue - } - return "" -} - -// XXX_OneofFuncs is for the internal use of the proto package. -func (*GaugeResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _GaugeResponse_OneofMarshaler, _GaugeResponse_OneofUnmarshaler, _GaugeResponse_OneofSizer, []interface{}{ - (*GaugeResponse_LongValue)(nil), - (*GaugeResponse_DoubleValue)(nil), - (*GaugeResponse_StringValue)(nil), - } -} - -func _GaugeResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*GaugeResponse) - // value - switch x := m.Value.(type) { - case *GaugeResponse_LongValue: - b.EncodeVarint(2<<3 | proto.WireVarint) - b.EncodeVarint(uint64(x.LongValue)) - case *GaugeResponse_DoubleValue: - b.EncodeVarint(3<<3 | proto.WireFixed64) - b.EncodeFixed64(math.Float64bits(x.DoubleValue)) - case *GaugeResponse_StringValue: - b.EncodeVarint(4<<3 | proto.WireBytes) - b.EncodeStringBytes(x.StringValue) - case nil: - default: - return fmt.Errorf("GaugeResponse.Value has unexpected type %T", x) - } - return nil -} - -func _GaugeResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*GaugeResponse) - switch tag { - case 2: // value.long_value - if wire != proto.WireVarint { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeVarint() - m.Value = &GaugeResponse_LongValue{int64(x)} - return true, err - case 3: // value.double_value - if wire != proto.WireFixed64 { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeFixed64() - m.Value = &GaugeResponse_DoubleValue{math.Float64frombits(x)} - return true, err - case 4: // value.string_value - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - x, err := b.DecodeStringBytes() - m.Value = &GaugeResponse_StringValue{x} - return true, err - default: - return false, nil - } -} - -func _GaugeResponse_OneofSizer(msg proto.Message) (n int) { - m := msg.(*GaugeResponse) - // value - switch x := m.Value.(type) { - case *GaugeResponse_LongValue: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(x.LongValue)) - case *GaugeResponse_DoubleValue: - n += 1 // tag and wire - n += 8 - case *GaugeResponse_StringValue: - n += 1 // tag and wire - n += proto.SizeVarint(uint64(len(x.StringValue))) - n += len(x.StringValue) - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - -// Request message containing the gauge name -type GaugeRequest struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GaugeRequest) Reset() { *m = GaugeRequest{} } -func (m *GaugeRequest) String() string { return proto.CompactTextString(m) } -func (*GaugeRequest) ProtoMessage() {} -func (*GaugeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_metrics_c9a45afc44ac5637, []int{1} -} -func (m *GaugeRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GaugeRequest.Unmarshal(m, b) -} -func (m *GaugeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GaugeRequest.Marshal(b, m, deterministic) -} -func (dst *GaugeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GaugeRequest.Merge(dst, src) -} -func (m *GaugeRequest) XXX_Size() int { - return xxx_messageInfo_GaugeRequest.Size(m) -} -func (m *GaugeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GaugeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_GaugeRequest proto.InternalMessageInfo - -func (m *GaugeRequest) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type EmptyMessage struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EmptyMessage) Reset() { *m = EmptyMessage{} } -func (m *EmptyMessage) String() string { return proto.CompactTextString(m) } -func (*EmptyMessage) ProtoMessage() {} -func (*EmptyMessage) Descriptor() ([]byte, []int) { - return fileDescriptor_metrics_c9a45afc44ac5637, []int{2} -} -func (m *EmptyMessage) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EmptyMessage.Unmarshal(m, b) -} -func (m *EmptyMessage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EmptyMessage.Marshal(b, m, deterministic) -} -func (dst *EmptyMessage) XXX_Merge(src proto.Message) { - xxx_messageInfo_EmptyMessage.Merge(dst, src) -} -func (m *EmptyMessage) XXX_Size() int { - return xxx_messageInfo_EmptyMessage.Size(m) -} -func (m *EmptyMessage) XXX_DiscardUnknown() { - xxx_messageInfo_EmptyMessage.DiscardUnknown(m) -} - -var xxx_messageInfo_EmptyMessage proto.InternalMessageInfo - -func init() { - proto.RegisterType((*GaugeResponse)(nil), "grpc.testing.GaugeResponse") - proto.RegisterType((*GaugeRequest)(nil), "grpc.testing.GaugeRequest") - proto.RegisterType((*EmptyMessage)(nil), "grpc.testing.EmptyMessage") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MetricsServiceClient is the client API for MetricsService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MetricsServiceClient interface { - // Returns the values of all the gauges that are currently being maintained by - // the service - GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) - // Returns the value of one gauge - GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) -} - -type metricsServiceClient struct { - cc *grpc.ClientConn -} - -func NewMetricsServiceClient(cc *grpc.ClientConn) MetricsServiceClient { - return &metricsServiceClient{cc} -} - -func (c *metricsServiceClient) GetAllGauges(ctx context.Context, in *EmptyMessage, opts ...grpc.CallOption) (MetricsService_GetAllGaugesClient, error) { - stream, err := c.cc.NewStream(ctx, &_MetricsService_serviceDesc.Streams[0], "/grpc.testing.MetricsService/GetAllGauges", opts...) - if err != nil { - return nil, err - } - x := &metricsServiceGetAllGaugesClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type MetricsService_GetAllGaugesClient interface { - Recv() (*GaugeResponse, error) - grpc.ClientStream -} - -type metricsServiceGetAllGaugesClient struct { - grpc.ClientStream -} - -func (x *metricsServiceGetAllGaugesClient) Recv() (*GaugeResponse, error) { - m := new(GaugeResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *metricsServiceClient) GetGauge(ctx context.Context, in *GaugeRequest, opts ...grpc.CallOption) (*GaugeResponse, error) { - out := new(GaugeResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.MetricsService/GetGauge", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MetricsServiceServer is the server API for MetricsService service. -type MetricsServiceServer interface { - // Returns the values of all the gauges that are currently being maintained by - // the service - GetAllGauges(*EmptyMessage, MetricsService_GetAllGaugesServer) error - // Returns the value of one gauge - GetGauge(context.Context, *GaugeRequest) (*GaugeResponse, error) -} - -func RegisterMetricsServiceServer(s *grpc.Server, srv MetricsServiceServer) { - s.RegisterService(&_MetricsService_serviceDesc, srv) -} - -func _MetricsService_GetAllGauges_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(EmptyMessage) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(MetricsServiceServer).GetAllGauges(m, &metricsServiceGetAllGaugesServer{stream}) -} - -type MetricsService_GetAllGaugesServer interface { - Send(*GaugeResponse) error - grpc.ServerStream -} - -type metricsServiceGetAllGaugesServer struct { - grpc.ServerStream -} - -func (x *metricsServiceGetAllGaugesServer) Send(m *GaugeResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _MetricsService_GetGauge_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GaugeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MetricsServiceServer).GetGauge(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.MetricsService/GetGauge", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MetricsServiceServer).GetGauge(ctx, req.(*GaugeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _MetricsService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.MetricsService", - HandlerType: (*MetricsServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetGauge", - Handler: _MetricsService_GetGauge_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "GetAllGauges", - Handler: _MetricsService_GetAllGauges_Handler, - ServerStreams: true, - }, - }, - Metadata: "metrics.proto", -} - -func init() { proto.RegisterFile("metrics.proto", fileDescriptor_metrics_c9a45afc44ac5637) } - -var fileDescriptor_metrics_c9a45afc44ac5637 = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x3f, 0x4f, 0xc3, 0x30, - 0x10, 0xc5, 0x6b, 0x5a, 0xfe, 0xf4, 0x70, 0x3b, 0x78, 0xaa, 0xca, 0x40, 0x14, 0x96, 0x4c, 0x11, - 0x82, 0x4f, 0x00, 0x08, 0xa5, 0x0c, 0x5d, 0x82, 0xc4, 0x8a, 0xd2, 0x70, 0xb2, 0x22, 0x39, 0x71, - 0xf0, 0x5d, 0x2a, 0xf1, 0x49, 0x58, 0xf9, 0xa8, 0xc8, 0x4e, 0x55, 0xa5, 0x08, 0x75, 0xb3, 0x7e, - 0xf7, 0xfc, 0xfc, 0x9e, 0x0f, 0x66, 0x35, 0xb2, 0xab, 0x4a, 0x4a, 0x5b, 0x67, 0xd9, 0x2a, 0xa9, - 0x5d, 0x5b, 0xa6, 0x8c, 0xc4, 0x55, 0xa3, 0xe3, 0x6f, 0x01, 0xb3, 0xac, 0xe8, 0x34, 0xe6, 0x48, - 0xad, 0x6d, 0x08, 0x95, 0x82, 0x49, 0x53, 0xd4, 0xb8, 0x10, 0x91, 0x48, 0xa6, 0x79, 0x38, 0xab, - 0x6b, 0x00, 0x63, 0x1b, 0xfd, 0xbe, 0x2d, 0x4c, 0x87, 0x8b, 0x93, 0x48, 0x24, 0xe3, 0xd5, 0x28, - 0x9f, 0x7a, 0xf6, 0xe6, 0x91, 0xba, 0x01, 0xf9, 0x61, 0xbb, 0x8d, 0xc1, 0x9d, 0x64, 0x1c, 0x89, - 0x44, 0xac, 0x46, 0xf9, 0x65, 0x4f, 0xf7, 0x22, 0x62, 0x57, 0xed, 0x7d, 0x26, 0xfe, 0x05, 0x2f, - 0xea, 0x69, 0x10, 0x3d, 0x9e, 0xc3, 0x69, 0x98, 0xc6, 0x31, 0xc8, 0x5d, 0xb0, 0xcf, 0x0e, 0x89, - 0xff, 0xcb, 0x15, 0xcf, 0x41, 0x3e, 0xd7, 0x2d, 0x7f, 0xad, 0x91, 0xa8, 0xd0, 0x78, 0xf7, 0x23, - 0x60, 0xbe, 0xee, 0xdb, 0xbe, 0xa2, 0xdb, 0x56, 0x25, 0xaa, 0x17, 0x90, 0x19, 0xf2, 0x83, 0x31, - 0xc1, 0x8c, 0xd4, 0x32, 0x1d, 0xf6, 0x4f, 0x87, 0xd7, 0x97, 0x57, 0x87, 0xb3, 0x83, 0x7f, 0xb9, - 0x15, 0xea, 0x09, 0x2e, 0x32, 0xe4, 0x40, 0xff, 0xda, 0x0c, 0x93, 0x1e, 0xb5, 0xd9, 0x9c, 0x85, - 0x2d, 0xdc, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x7d, 0xb2, 0xc9, 0x96, 0x01, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/stress/grpc_testing/metrics.proto b/examples/google.golang.org/grpc/stress/grpc_testing/metrics.proto deleted file mode 100755 index 6950400..0000000 --- a/examples/google.golang.org/grpc/stress/grpc_testing/metrics.proto +++ /dev/null @@ -1,49 +0,0 @@ -// 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. - -// Contains the definitions for a metrics service and the type of metrics -// exposed by the service. -// -// Currently, 'Gauge' (i.e a metric that represents the measured value of -// something at an instant of time) is the only metric type supported by the -// service. -syntax = "proto3"; - -package grpc.testing; - -// Response message containing the gauge name and value -message GaugeResponse { - string name = 1; - oneof value { - int64 long_value = 2; - double double_value = 3; - string string_value = 4; - } -} - -// Request message containing the gauge name -message GaugeRequest { - string name = 1; -} - -message EmptyMessage {} - -service MetricsService { - // Returns the values of all the gauges that are currently being maintained by - // the service - rpc GetAllGauges(EmptyMessage) returns (stream GaugeResponse); - - // Returns the value of one gauge - rpc GetGauge(GaugeRequest) returns (GaugeResponse); -} diff --git a/examples/google.golang.org/grpc/stress/metrics_client/main.go b/examples/google.golang.org/grpc/stress/metrics_client/main.go deleted file mode 100755 index 70b024b..0000000 --- a/examples/google.golang.org/grpc/stress/metrics_client/main.go +++ /dev/null @@ -1,82 +0,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. - * - */ - -package main - -import ( - "flag" - "fmt" - "io" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" - metricspb "google.golang.org/grpc/stress/grpc_testing" -) - -var ( - metricsServerAddress = flag.String("metrics_server_address", "", "The metrics server addresses in the fomrat :") - totalOnly = flag.Bool("total_only", false, "If true, this prints only the total value of all gauges") -) - -func printMetrics(client metricspb.MetricsServiceClient, totalOnly bool) { - stream, err := client.GetAllGauges(context.Background(), &metricspb.EmptyMessage{}) - if err != nil { - grpclog.Fatalf("failed to call GetAllGuages: %v", err) - } - - var ( - overallQPS int64 - rpcStatus error - ) - for { - gaugeResponse, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - if _, ok := gaugeResponse.GetValue().(*metricspb.GaugeResponse_LongValue); !ok { - panic(fmt.Sprintf("gauge %s is not a long value", gaugeResponse.Name)) - } - v := gaugeResponse.GetLongValue() - if !totalOnly { - grpclog.Infof("%s: %d", gaugeResponse.Name, v) - } - overallQPS += v - } - if rpcStatus != io.EOF { - grpclog.Fatalf("failed to finish server streaming: %v", rpcStatus) - } - grpclog.Infof("overall qps: %d", overallQPS) -} - -func main() { - flag.Parse() - if *metricsServerAddress == "" { - grpclog.Fatalf("Metrics server address is empty.") - } - - conn, err := grpc.Dial(*metricsServerAddress, grpc.WithInsecure()) - if err != nil { - grpclog.Fatalf("cannot connect to metrics server: %v", err) - } - defer conn.Close() - - c := metricspb.NewMetricsServiceClient(conn) - printMetrics(c, *totalOnly) -} diff --git a/examples/google.golang.org/grpc/tap/tap.go b/examples/google.golang.org/grpc/tap/tap.go deleted file mode 100755 index 22b8fb5..0000000 --- a/examples/google.golang.org/grpc/tap/tap.go +++ /dev/null @@ -1,51 +0,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. - * - */ - -// Package tap defines the function handles which are executed on the transport -// layer of gRPC-Go and related information. Everything here is EXPERIMENTAL. -package tap - -import ( - "golang.org/x/net/context" -) - -// Info defines the relevant information needed by the handles. -type Info struct { - // FullMethodName is the string of grpc method (in the format of - // /package.service/method). - FullMethodName string - // TODO: More to be added. -} - -// ServerInHandle defines the function which runs before a new stream is created -// on the server side. If it returns a non-nil error, the stream will not be -// created and a RST_STREAM will be sent back to the client with REFUSED_STREAM. -// The client will receive an RPC error "code = Unavailable, desc = stream -// terminated by RST_STREAM with error code: REFUSED_STREAM". -// -// It's intended to be used in situations where you don't want to waste the -// resources to accept the new stream (e.g. rate-limiting). And the content of -// the error will be ignored and won't be sent back to the client. For other -// general usages, please use interceptors. -// -// Note that it is executed in the per-connection I/O goroutine(s) instead of -// per-RPC goroutine. Therefore, users should NOT have any -// blocking/time-consuming work in this handle. Otherwise all the RPCs would -// slow down. Also, for the same reason, this handle won't be called -// concurrently by gRPC. -type ServerInHandle func(ctx context.Context, info *Info) (context.Context, error) diff --git a/examples/google.golang.org/grpc/test/bufconn/bufconn.go b/examples/google.golang.org/grpc/test/bufconn/bufconn.go deleted file mode 100755 index bdb5d81..0000000 --- a/examples/google.golang.org/grpc/test/bufconn/bufconn.go +++ /dev/null @@ -1,244 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package bufconn provides a net.Conn implemented by a buffer and related -// dialing and listening functionality. -package bufconn - -import ( - "fmt" - "io" - "net" - "sync" - "time" -) - -// Listener implements a net.Listener that creates local, buffered net.Conns -// via its Accept and Dial method. -type Listener struct { - mu sync.Mutex - sz int - ch chan net.Conn - done chan struct{} -} - -var errClosed = fmt.Errorf("Closed") - -// Listen returns a Listener that can only be contacted by its own Dialers and -// creates buffered connections between the two. -func Listen(sz int) *Listener { - return &Listener{sz: sz, ch: make(chan net.Conn), done: make(chan struct{})} -} - -// Accept blocks until Dial is called, then returns a net.Conn for the server -// half of the connection. -func (l *Listener) Accept() (net.Conn, error) { - select { - case <-l.done: - return nil, errClosed - case c := <-l.ch: - return c, nil - } -} - -// Close stops the listener. -func (l *Listener) Close() error { - l.mu.Lock() - defer l.mu.Unlock() - select { - case <-l.done: - // Already closed. - break - default: - close(l.done) - } - return nil -} - -// Addr reports the address of the listener. -func (l *Listener) Addr() net.Addr { return addr{} } - -// Dial creates an in-memory full-duplex network connection, unblocks Accept by -// providing it the server half of the connection, and returns the client half -// of the connection. -func (l *Listener) Dial() (net.Conn, error) { - p1, p2 := newPipe(l.sz), newPipe(l.sz) - select { - case <-l.done: - return nil, errClosed - case l.ch <- &conn{p1, p2}: - return &conn{p2, p1}, nil - } -} - -type pipe struct { - mu sync.Mutex - - // buf contains the data in the pipe. It is a ring buffer of fixed capacity, - // with r and w pointing to the offset to read and write, respsectively. - // - // Data is read between [r, w) and written to [w, r), wrapping around the end - // of the slice if necessary. - // - // The buffer is empty if r == len(buf), otherwise if r == w, it is full. - // - // w and r are always in the range [0, cap(buf)) and [0, len(buf)]. - buf []byte - w, r int - - wwait sync.Cond - rwait sync.Cond - - closed bool - writeClosed bool -} - -func newPipe(sz int) *pipe { - p := &pipe{buf: make([]byte, 0, sz)} - p.wwait.L = &p.mu - p.rwait.L = &p.mu - return p -} - -func (p *pipe) empty() bool { - return p.r == len(p.buf) -} - -func (p *pipe) full() bool { - return p.r < len(p.buf) && p.r == p.w -} - -func (p *pipe) Read(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - // Block until p has data. - for { - if p.closed { - return 0, io.ErrClosedPipe - } - if !p.empty() { - break - } - if p.writeClosed { - return 0, io.EOF - } - p.rwait.Wait() - } - wasFull := p.full() - - n = copy(b, p.buf[p.r:len(p.buf)]) - p.r += n - if p.r == cap(p.buf) { - p.r = 0 - p.buf = p.buf[:p.w] - } - - // Signal a blocked writer, if any - if wasFull { - p.wwait.Signal() - } - - return n, nil -} - -func (p *pipe) Write(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - if p.closed { - return 0, io.ErrClosedPipe - } - for len(b) > 0 { - // Block until p is not full. - for { - if p.closed || p.writeClosed { - return 0, io.ErrClosedPipe - } - if !p.full() { - break - } - p.wwait.Wait() - } - wasEmpty := p.empty() - - end := cap(p.buf) - if p.w < p.r { - end = p.r - } - x := copy(p.buf[p.w:end], b) - b = b[x:] - n += x - p.w += x - if p.w > len(p.buf) { - p.buf = p.buf[:p.w] - } - if p.w == cap(p.buf) { - p.w = 0 - } - - // Signal a blocked reader, if any. - if wasEmpty { - p.rwait.Signal() - } - } - return n, nil -} - -func (p *pipe) Close() error { - p.mu.Lock() - defer p.mu.Unlock() - p.closed = true - // Signal all blocked readers and writers to return an error. - p.rwait.Broadcast() - p.wwait.Broadcast() - return nil -} - -func (p *pipe) closeWrite() error { - p.mu.Lock() - defer p.mu.Unlock() - p.writeClosed = true - // Signal all blocked readers and writers to return an error. - p.rwait.Broadcast() - p.wwait.Broadcast() - return nil -} - -type conn struct { - io.Reader - io.Writer -} - -func (c *conn) Close() error { - err1 := c.Reader.(*pipe).Close() - err2 := c.Writer.(*pipe).closeWrite() - if err1 != nil { - return err1 - } - return err2 -} - -func (*conn) LocalAddr() net.Addr { return addr{} } -func (*conn) RemoteAddr() net.Addr { return addr{} } -func (c *conn) SetDeadline(t time.Time) error { return fmt.Errorf("unsupported") } -func (c *conn) SetReadDeadline(t time.Time) error { return fmt.Errorf("unsupported") } -func (c *conn) SetWriteDeadline(t time.Time) error { return fmt.Errorf("unsupported") } - -type addr struct{} - -func (addr) Network() string { return "bufconn" } -func (addr) String() string { return "bufconn" } diff --git a/examples/google.golang.org/grpc/test/bufconn/bufconn_test.go b/examples/google.golang.org/grpc/test/bufconn/bufconn_test.go deleted file mode 100755 index 65b4caa..0000000 --- a/examples/google.golang.org/grpc/test/bufconn/bufconn_test.go +++ /dev/null @@ -1,199 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package bufconn - -import ( - "fmt" - "io" - "net" - "reflect" - "testing" - "time" -) - -func testRW(r io.Reader, w io.Writer) error { - for i := 0; i < 20; i++ { - d := make([]byte, i) - for j := 0; j < i; j++ { - d[j] = byte(i - j) - } - var rn int - var rerr error - b := make([]byte, i) - done := make(chan struct{}) - go func() { - for rn < len(b) && rerr == nil { - var x int - x, rerr = r.Read(b[rn:]) - rn += x - } - close(done) - }() - wn, werr := w.Write(d) - if wn != i || werr != nil { - return fmt.Errorf("%v: w.Write(%v) = %v, %v; want %v, nil", i, d, wn, werr, i) - } - select { - case <-done: - case <-time.After(500 * time.Millisecond): - return fmt.Errorf("%v: r.Read never returned", i) - } - if rn != i || rerr != nil { - return fmt.Errorf("%v: r.Read = %v, %v; want %v, nil", i, rn, rerr, i) - } - if !reflect.DeepEqual(b, d) { - return fmt.Errorf("%v: r.Read read %v; want %v", i, b, d) - } - } - return nil -} - -func TestPipe(t *testing.T) { - p := newPipe(10) - if err := testRW(p, p); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestPipeClose(t *testing.T) { - p := newPipe(10) - p.Close() - if _, err := p.Write(nil); err != io.ErrClosedPipe { - t.Fatalf("p.Write = _, %v; want _, %v", err, io.ErrClosedPipe) - } - if _, err := p.Read(nil); err != io.ErrClosedPipe { - t.Fatalf("p.Read = _, %v; want _, %v", err, io.ErrClosedPipe) - } -} - -func TestConn(t *testing.T) { - p1, p2 := newPipe(10), newPipe(10) - c1, c2 := &conn{p1, p2}, &conn{p2, p1} - - if err := testRW(c1, c2); err != nil { - t.Fatalf(err.Error()) - } - if err := testRW(c2, c1); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestConnCloseWithData(t *testing.T) { - lis := Listen(7) - errChan := make(chan error) - var lisConn net.Conn - go func() { - var err error - if lisConn, err = lis.Accept(); err != nil { - errChan <- err - } - close(errChan) - }() - dialConn, err := lis.Dial() - if err != nil { - t.Fatalf("Dial error: %v", err) - } - if err := <-errChan; err != nil { - t.Fatalf("Listen error: %v", err) - } - - // Write some data on both sides of the connection. - n, err := dialConn.Write([]byte("hello")) - if n != 5 || err != nil { - t.Fatalf("dialConn.Write([]byte{\"hello\"}) = %v, %v; want 5, ", n, err) - } - n, err = lisConn.Write([]byte("hello")) - if n != 5 || err != nil { - t.Fatalf("lisConn.Write([]byte{\"hello\"}) = %v, %v; want 5, ", n, err) - } - - // Close dial-side; writes from either side should fail. - dialConn.Close() - if _, err := lisConn.Write([]byte("hello")); err != io.ErrClosedPipe { - t.Fatalf("lisConn.Write() = _, ; want _, ") - } - if _, err := dialConn.Write([]byte("hello")); err != io.ErrClosedPipe { - t.Fatalf("dialConn.Write() = _, ; want _, ") - } - - // Read from both sides; reads on lisConn should work, but dialConn should - // fail. - buf := make([]byte, 6) - if _, err := dialConn.Read(buf); err != io.ErrClosedPipe { - t.Fatalf("dialConn.Read(buf) = %v, %v; want _, io.ErrClosedPipe", n, err) - } - n, err = lisConn.Read(buf) - if n != 5 || err != nil { - t.Fatalf("lisConn.Read(buf) = %v, %v; want 5, ", n, err) - } -} - -func TestListener(t *testing.T) { - l := Listen(7) - var s net.Conn - var serr error - done := make(chan struct{}) - go func() { - s, serr = l.Accept() - close(done) - }() - c, cerr := l.Dial() - <-done - if cerr != nil || serr != nil { - t.Fatalf("cerr = %v, serr = %v; want nil, nil", cerr, serr) - } - if err := testRW(c, s); err != nil { - t.Fatalf(err.Error()) - } - if err := testRW(s, c); err != nil { - t.Fatalf(err.Error()) - } -} - -func TestCloseWhileDialing(t *testing.T) { - l := Listen(7) - var c net.Conn - var err error - done := make(chan struct{}) - go func() { - c, err = l.Dial() - close(done) - }() - l.Close() - <-done - if c != nil || err != errClosed { - t.Fatalf("c, err = %v, %v; want nil, %v", c, err, errClosed) - } -} - -func TestCloseWhileAccepting(t *testing.T) { - l := Listen(7) - var c net.Conn - var err error - done := make(chan struct{}) - go func() { - c, err = l.Accept() - close(done) - }() - l.Close() - <-done - if c != nil || err != errClosed { - t.Fatalf("c, err = %v, %v; want nil, %v", c, err, errClosed) - } -} diff --git a/examples/google.golang.org/grpc/test/channelz_test.go b/examples/google.golang.org/grpc/test/channelz_test.go deleted file mode 100755 index eaa657c..0000000 --- a/examples/google.golang.org/grpc/test/channelz_test.go +++ /dev/null @@ -1,1199 +0,0 @@ -/* - * - * 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. - * - */ - -package test - -import ( - "fmt" - "net" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "google.golang.org/grpc" - _ "google.golang.org/grpc/balancer/grpclb" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - "google.golang.org/grpc/status" - testpb "google.golang.org/grpc/test/grpc_testing" -) - -func init() { - channelz.TurnOn() -} - -func (te *test) startServers(ts testpb.TestServiceServer, num int) { - for i := 0; i < num; i++ { - te.startServer(ts) - te.srvs = append(te.srvs, te.srv) - te.srvAddrs = append(te.srvAddrs, te.srvAddr) - te.srv = nil - te.srvAddr = "" - } -} - -func verifyResultWithDelay(f func() (bool, error)) error { - var ok bool - var err error - for i := 0; i < 1000; i++ { - if ok, err = f(); ok { - return nil - } - time.Sleep(10 * time.Millisecond) - } - return err -} - -func TestCZServerRegistrationAndDeletion(t *testing.T) { - defer leakcheck.Check(t) - testcases := []struct { - total int - start int64 - length int - end bool - }{ - {total: channelz.EntryPerPage, start: 0, length: channelz.EntryPerPage, end: true}, - {total: channelz.EntryPerPage - 1, start: 0, length: channelz.EntryPerPage - 1, end: true}, - {total: channelz.EntryPerPage + 1, start: 0, length: channelz.EntryPerPage, end: false}, - {total: channelz.EntryPerPage + 1, start: int64(2*(channelz.EntryPerPage+1) + 1), length: 0, end: true}, - } - - for _, c := range testcases { - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.startServers(&testServer{security: e.security}, c.total) - - ss, end := channelz.GetServers(c.start) - if len(ss) != c.length || end != c.end { - t.Fatalf("GetServers(%d) = %+v (len of which: %d), end: %+v, want len(GetServers(%d)) = %d, end: %+v", c.start, ss, len(ss), end, c.start, c.length, c.end) - } - te.tearDown() - ss, end = channelz.GetServers(c.start) - if len(ss) != 0 || !end { - t.Fatalf("GetServers(0) = %+v (len of which: %d), end: %+v, want len(GetServers(0)) = 0, end: true", ss, len(ss), end) - } - } -} - -func TestCZTopChannelRegistrationAndDeletion(t *testing.T) { - defer leakcheck.Check(t) - testcases := []struct { - total int - start int64 - length int - end bool - }{ - {total: channelz.EntryPerPage, start: 0, length: channelz.EntryPerPage, end: true}, - {total: channelz.EntryPerPage - 1, start: 0, length: channelz.EntryPerPage - 1, end: true}, - {total: channelz.EntryPerPage + 1, start: 0, length: channelz.EntryPerPage, end: false}, - {total: channelz.EntryPerPage + 1, start: int64(2*(channelz.EntryPerPage+1) + 1), length: 0, end: true}, - } - - for _, c := range testcases { - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - var ccs []*grpc.ClientConn - for i := 0; i < c.total; i++ { - cc := te.clientConn() - te.cc = nil - // avoid making next dial blocking - te.srvAddr = "" - ccs = append(ccs, cc) - } - if err := verifyResultWithDelay(func() (bool, error) { - if tcs, end := channelz.GetTopChannels(c.start); len(tcs) != c.length || end != c.end { - return false, fmt.Errorf("GetTopChannels(%d) = %+v (len of which: %d), end: %+v, want len(GetTopChannels(%d)) = %d, end: %+v", c.start, tcs, len(tcs), end, c.start, c.length, c.end) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - for _, cc := range ccs { - cc.Close() - } - - if err := verifyResultWithDelay(func() (bool, error) { - if tcs, end := channelz.GetTopChannels(c.start); len(tcs) != 0 || !end { - return false, fmt.Errorf("GetTopChannels(0) = %+v (len of which: %d), end: %+v, want len(GetTopChannels(0)) = 0, end: true", tcs, len(tcs), end) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - te.tearDown() - } -} - -func TestCZNestedChannelRegistrationAndDeletion(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - // avoid calling API to set balancer type, which will void service config's change of balancer. - e.balancer = "" - te := newTest(t, e) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - resolvedAddrs := []resolver.Address{{Addr: "127.0.0.1:0", Type: resolver.GRPCLB, ServerName: "grpclb.server"}} - r.InitialAddrs(resolvedAddrs) - te.resolverScheme = r.Scheme() - te.clientConn() - defer te.tearDown() - - if err := verifyResultWithDelay(func() (bool, error) { - tcs, _ := channelz.GetTopChannels(0) - if len(tcs) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tcs)) - } - if len(tcs[0].NestedChans) != 1 { - return false, fmt.Errorf("There should be one nested channel from grpclb, not %d", len(tcs[0].NestedChans)) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - r.NewServiceConfig(`{"loadBalancingPolicy": "round_robin"}`) - r.NewAddress([]resolver.Address{{Addr: "127.0.0.1:0"}}) - - // wait for the shutdown of grpclb balancer - if err := verifyResultWithDelay(func() (bool, error) { - tcs, _ := channelz.GetTopChannels(0) - if len(tcs) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tcs)) - } - if len(tcs[0].NestedChans) != 0 { - return false, fmt.Errorf("There should be 0 nested channel from grpclb, not %d", len(tcs[0].NestedChans)) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - num := 3 // number of backends - te := newTest(t, e) - var svrAddrs []resolver.Address - te.startServers(&testServer{security: e.security}, num) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - for _, a := range te.srvAddrs { - svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) - } - r.InitialAddrs(svrAddrs) - te.resolverScheme = r.Scheme() - te.clientConn() - defer te.tearDown() - // Here, we just wait for all sockets to be up. In the future, if we implement - // IDLE, we may need to make several rpc calls to create the sockets. - if err := verifyResultWithDelay(func() (bool, error) { - tcs, _ := channelz.GetTopChannels(0) - if len(tcs) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tcs)) - } - if len(tcs[0].SubChans) != num { - return false, fmt.Errorf("There should be %d subchannel not %d", num, len(tcs[0].SubChans)) - } - count := 0 - for k := range tcs[0].SubChans { - sc := channelz.GetSubChannel(k) - if sc == nil { - return false, fmt.Errorf("got subchannel") - } - count += len(sc.Sockets) - } - if count != num { - return false, fmt.Errorf("There should be %d sockets not %d", num, count) - } - - return true, nil - }); err != nil { - t.Fatal(err) - } - - r.NewAddress(svrAddrs[:len(svrAddrs)-1]) - - if err := verifyResultWithDelay(func() (bool, error) { - tcs, _ := channelz.GetTopChannels(0) - if len(tcs) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tcs)) - } - if len(tcs[0].SubChans) != num-1 { - return false, fmt.Errorf("There should be %d subchannel not %d", num-1, len(tcs[0].SubChans)) - } - count := 0 - for k := range tcs[0].SubChans { - sc := channelz.GetSubChannel(k) - if sc == nil { - return false, fmt.Errorf("got subchannel") - } - count += len(sc.Sockets) - } - if count != num-1 { - return false, fmt.Errorf("There should be %d sockets not %d", num-1, count) - } - - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZServerSocketRegistrationAndDeletion(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - num := 3 // number of clients - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - var ccs []*grpc.ClientConn - for i := 0; i < num; i++ { - cc := te.clientConn() - te.cc = nil - ccs = append(ccs, cc) - } - defer func() { - for _, c := range ccs[:len(ccs)-1] { - c.Close() - } - }() - var svrID int64 - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - if len(ss[0].ListenSockets) != 1 { - return false, fmt.Errorf("There should only be one server listen socket, not %d", len(ss[0].ListenSockets)) - } - ns, _ := channelz.GetServerSockets(ss[0].ID, 0) - if len(ns) != num { - return false, fmt.Errorf("There should be %d normal sockets not %d", num, len(ns)) - } - svrID = ss[0].ID - return true, nil - }); err != nil { - t.Fatal(err) - } - - ccs[len(ccs)-1].Close() - - if err := verifyResultWithDelay(func() (bool, error) { - ns, _ := channelz.GetServerSockets(svrID, 0) - if len(ns) != num-1 { - return false, fmt.Errorf("There should be %d normal sockets not %d", num-1, len(ns)) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZServerListenSocketDeletion(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - s := grpc.NewServer() - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - go s.Serve(lis) - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - if len(ss[0].ListenSockets) != 1 { - return false, fmt.Errorf("There should only be one server listen socket, not %d", len(ss[0].ListenSockets)) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - lis.Close() - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should be 1 server, not %d", len(ss)) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - s.Stop() -} - -type dummyChannel struct{} - -func (d *dummyChannel) ChannelzMetric() *channelz.ChannelInternalMetric { - return &channelz.ChannelInternalMetric{} -} - -type dummySocket struct{} - -func (d *dummySocket) ChannelzMetric() *channelz.SocketInternalMetric { - return &channelz.SocketInternalMetric{} -} - -func TestCZRecusivelyDeletionOfEntry(t *testing.T) { - // +--+TopChan+---+ - // | | - // v v - // +-+SubChan1+--+ SubChan2 - // | | - // v v - // Socket1 Socket2 - channelz.NewChannelzStorage() - topChanID := channelz.RegisterChannel(&dummyChannel{}, 0, "") - subChanID1 := channelz.RegisterSubChannel(&dummyChannel{}, topChanID, "") - subChanID2 := channelz.RegisterSubChannel(&dummyChannel{}, topChanID, "") - sktID1 := channelz.RegisterNormalSocket(&dummySocket{}, subChanID1, "") - sktID2 := channelz.RegisterNormalSocket(&dummySocket{}, subChanID1, "") - - tcs, _ := channelz.GetTopChannels(0) - if tcs == nil || len(tcs) != 1 { - t.Fatalf("There should be one TopChannel entry") - } - if len(tcs[0].SubChans) != 2 { - t.Fatalf("There should be two SubChannel entries") - } - sc := channelz.GetSubChannel(subChanID1) - if sc == nil || len(sc.Sockets) != 2 { - t.Fatalf("There should be two Socket entries") - } - - channelz.RemoveEntry(topChanID) - tcs, _ = channelz.GetTopChannels(0) - if tcs == nil || len(tcs) != 1 { - t.Fatalf("There should be one TopChannel entry") - } - - channelz.RemoveEntry(subChanID1) - channelz.RemoveEntry(subChanID2) - tcs, _ = channelz.GetTopChannels(0) - if tcs == nil || len(tcs) != 1 { - t.Fatalf("There should be one TopChannel entry") - } - if len(tcs[0].SubChans) != 1 { - t.Fatalf("There should be one SubChannel entry") - } - - channelz.RemoveEntry(sktID1) - channelz.RemoveEntry(sktID2) - tcs, _ = channelz.GetTopChannels(0) - if tcs != nil { - t.Fatalf("There should be no TopChannel entry") - } -} - -func TestCZChannelMetrics(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - num := 3 // number of backends - te := newTest(t, e) - te.maxClientSendMsgSize = newInt(8) - var svrAddrs []resolver.Address - te.startServers(&testServer{security: e.security}, num) - r, cleanup := manual.GenerateAndRegisterManualResolver() - defer cleanup() - for _, a := range te.srvAddrs { - svrAddrs = append(svrAddrs, resolver.Address{Addr: a}) - } - r.InitialAddrs(svrAddrs) - te.resolverScheme = r.Scheme() - cc := te.clientConn() - defer te.tearDown() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - - const smallSize = 1 - const largeSize = 8 - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(smallSize), - Payload: largePayload, - } - - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - defer stream.CloseSend() - // Here, we just wait for all sockets to be up. In the future, if we implement - // IDLE, we may need to make several rpc calls to create the sockets. - if err := verifyResultWithDelay(func() (bool, error) { - tcs, _ := channelz.GetTopChannels(0) - if len(tcs) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tcs)) - } - if len(tcs[0].SubChans) != num { - return false, fmt.Errorf("There should be %d subchannel not %d", num, len(tcs[0].SubChans)) - } - var cst, csu, cf int64 - for k := range tcs[0].SubChans { - sc := channelz.GetSubChannel(k) - if sc == nil { - return false, fmt.Errorf("got subchannel") - } - cst += sc.ChannelData.CallsStarted - csu += sc.ChannelData.CallsSucceeded - cf += sc.ChannelData.CallsFailed - } - if cst != 3 { - return false, fmt.Errorf("There should be 3 CallsStarted not %d", cst) - } - if csu != 1 { - return false, fmt.Errorf("There should be 1 CallsSucceeded not %d", csu) - } - if cf != 1 { - return false, fmt.Errorf("There should be 1 CallsFailed not %d", cf) - } - if tcs[0].ChannelData.CallsStarted != 3 { - return false, fmt.Errorf("There should be 3 CallsStarted not %d", tcs[0].ChannelData.CallsStarted) - } - if tcs[0].ChannelData.CallsSucceeded != 1 { - return false, fmt.Errorf("There should be 1 CallsSucceeded not %d", tcs[0].ChannelData.CallsSucceeded) - } - if tcs[0].ChannelData.CallsFailed != 1 { - return false, fmt.Errorf("There should be 1 CallsFailed not %d", tcs[0].ChannelData.CallsFailed) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZServerMetrics(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.maxServerReceiveMsgSize = newInt(8) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - - const smallSize = 1 - const largeSize = 8 - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(smallSize), - Payload: largePayload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - defer stream.CloseSend() - - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - if ss[0].ServerData.CallsStarted != 3 { - return false, fmt.Errorf("There should be 3 CallsStarted not %d", ss[0].ServerData.CallsStarted) - } - if ss[0].ServerData.CallsSucceeded != 1 { - return false, fmt.Errorf("There should be 1 CallsSucceeded not %d", ss[0].ServerData.CallsSucceeded) - } - if ss[0].ServerData.CallsFailed != 1 { - return false, fmt.Errorf("There should be 1 CallsFailed not %d", ss[0].ServerData.CallsFailed) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -type testServiceClientWrapper struct { - testpb.TestServiceClient - mu sync.RWMutex - streamsCreated int -} - -func (t *testServiceClientWrapper) getCurrentStreamID() uint32 { - t.mu.RLock() - defer t.mu.RUnlock() - return uint32(2*t.streamsCreated - 1) -} - -func (t *testServiceClientWrapper) EmptyCall(ctx context.Context, in *testpb.Empty, opts ...grpc.CallOption) (*testpb.Empty, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.EmptyCall(ctx, in, opts...) -} - -func (t *testServiceClientWrapper) UnaryCall(ctx context.Context, in *testpb.SimpleRequest, opts ...grpc.CallOption) (*testpb.SimpleResponse, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.UnaryCall(ctx, in, opts...) -} - -func (t *testServiceClientWrapper) StreamingOutputCall(ctx context.Context, in *testpb.StreamingOutputCallRequest, opts ...grpc.CallOption) (testpb.TestService_StreamingOutputCallClient, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.StreamingOutputCall(ctx, in, opts...) -} - -func (t *testServiceClientWrapper) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (testpb.TestService_StreamingInputCallClient, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.StreamingInputCall(ctx, opts...) -} - -func (t *testServiceClientWrapper) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (testpb.TestService_FullDuplexCallClient, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.FullDuplexCall(ctx, opts...) -} - -func (t *testServiceClientWrapper) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (testpb.TestService_HalfDuplexCallClient, error) { - t.mu.Lock() - defer t.mu.Unlock() - t.streamsCreated++ - return t.TestServiceClient.HalfDuplexCall(ctx, opts...) -} - -func doSuccessfulUnaryCall(tc testpb.TestServiceClient, t *testing.T) { - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } -} - -func doStreamingInputCallWithLargePayload(tc testpb.TestServiceClient, t *testing.T) { - s, err := tc.StreamingInputCall(context.Background()) - if err != nil { - t.Fatalf("TestService/StreamingInputCall(_) = _, %v, want ", err) - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 10000) - if err != nil { - t.Fatal(err) - } - s.Send(&testpb.StreamingInputCallRequest{Payload: payload}) -} - -func doServerSideFailedUnaryCall(tc testpb.TestServiceClient, t *testing.T) { - const smallSize = 1 - const largeSize = 2000 - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(smallSize), - Payload: largePayload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } -} - -func doClientSideInitiatedFailedStream(tc testpb.TestServiceClient, t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - - const smallSize = 1 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{ - {Size: smallSize}, - }, - Payload: smallPayload, - } - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - // By canceling the call, the client will send rst_stream to end the call, and - // the stream will failed as a result. - cancel() -} - -// This func is to be used to test client side counting of failed streams. -func doServerSideInitiatedFailedStreamWithRSTStream(tc testpb.TestServiceClient, t *testing.T, l *listenerWrapper) { - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - - const smallSize = 1 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{ - {Size: smallSize}, - }, - Payload: smallPayload, - } - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - - rcw := l.getLastConn() - - if rcw != nil { - rcw.writeRSTStream(tc.(*testServiceClientWrapper).getCurrentStreamID(), http2.ErrCodeCancel) - } - if _, err := stream.Recv(); err == nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } -} - -// this func is to be used to test client side counting of failed streams. -func doServerSideInitiatedFailedStreamWithGoAway(tc testpb.TestServiceClient, t *testing.T, l *listenerWrapper) { - // This call is just to keep the transport from shutting down (socket will be deleted - // in this case, and we will not be able to get metrics). - s, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - if err := s.Send(&testpb.StreamingOutputCallRequest{ResponseParameters: []*testpb.ResponseParameters{ - { - Size: 1, - }, - }}); err != nil { - t.Fatalf("s.Send() failed with error: %v", err) - } - if _, err := s.Recv(); err != nil { - t.Fatalf("s.Recv() failed with error: %v", err) - } - - s, err = tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - if err := s.Send(&testpb.StreamingOutputCallRequest{ResponseParameters: []*testpb.ResponseParameters{ - { - Size: 1, - }, - }}); err != nil { - t.Fatalf("s.Send() failed with error: %v", err) - } - if _, err := s.Recv(); err != nil { - t.Fatalf("s.Recv() failed with error: %v", err) - } - - rcw := l.getLastConn() - if rcw != nil { - rcw.writeGoAway(tc.(*testServiceClientWrapper).getCurrentStreamID()-2, http2.ErrCodeCancel, []byte{}) - } - if _, err := s.Recv(); err == nil { - t.Fatalf("%v.Recv() = %v, want ", s, err) - } -} - -// this func is to be used to test client side counting of failed streams. -func doServerSideInitiatedFailedStreamWithClientBreakFlowControl(tc testpb.TestServiceClient, t *testing.T, dw *dialerWrapper) { - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - // sleep here to make sure header frame being sent before the data frame we write directly below. - time.Sleep(10 * time.Millisecond) - payload := make([]byte, 65537, 65537) - dw.getRawConnWrapper().writeRawFrame(http2.FrameData, 0, tc.(*testServiceClientWrapper).getCurrentStreamID(), payload) - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = %v, want error code: %v", stream, err, codes.ResourceExhausted) - } -} - -func doIdleCallToInvokeKeepAlive(tc testpb.TestServiceClient, t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - _, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - // 2500ms allow for 2 keepalives (1000ms per round trip) - time.Sleep(2500 * time.Millisecond) - cancel() -} - -func TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.maxServerReceiveMsgSize = newInt(20) - te.maxClientReceiveMsgSize = newInt(20) - rcw := te.startServerWithConnControl(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} - - doSuccessfulUnaryCall(tc, t) - var scID, skID int64 - if err := verifyResultWithDelay(func() (bool, error) { - tchan, _ := channelz.GetTopChannels(0) - if len(tchan) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tchan)) - } - if len(tchan[0].SubChans) != 1 { - return false, fmt.Errorf("There should only be one subchannel under top channel %d, not %d", tchan[0].ID, len(tchan[0].SubChans)) - } - - for scID = range tchan[0].SubChans { - break - } - sc := channelz.GetSubChannel(scID) - if sc == nil { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not 0", scID) - } - if len(sc.Sockets) != 1 { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not %d", sc.ID, len(sc.Sockets)) - } - for skID = range sc.Sockets { - break - } - skt := channelz.GetSocket(skID) - sktData := skt.SocketData - if sktData.StreamsStarted != 1 || sktData.StreamsSucceeded != 1 || sktData.MessagesSent != 1 || sktData.MessagesReceived != 1 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, MessagesSent, MessagesReceived) = (1, 1, 1, 1), got (%d, %d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doServerSideFailedUnaryCall(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(skID) - sktData := skt.SocketData - if sktData.StreamsStarted != 2 || sktData.StreamsSucceeded != 2 || sktData.MessagesSent != 2 || sktData.MessagesReceived != 1 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, MessagesSent, MessagesReceived) = (2, 2, 2, 1), got (%d, %d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doClientSideInitiatedFailedStream(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(skID) - sktData := skt.SocketData - if sktData.StreamsStarted != 3 || sktData.StreamsSucceeded != 2 || sktData.StreamsFailed != 1 || sktData.MessagesSent != 3 || sktData.MessagesReceived != 2 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, StreamsFailed, MessagesSent, MessagesReceived) = (3, 2, 1, 3, 2), got (%d, %d, %d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doServerSideInitiatedFailedStreamWithRSTStream(tc, t, rcw) - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(skID) - sktData := skt.SocketData - if sktData.StreamsStarted != 4 || sktData.StreamsSucceeded != 2 || sktData.StreamsFailed != 2 || sktData.MessagesSent != 4 || sktData.MessagesReceived != 3 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, StreamsFailed, MessagesSent, MessagesReceived) = (4, 2, 2, 4, 3), got (%d, %d, %d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doServerSideInitiatedFailedStreamWithGoAway(tc, t, rcw) - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(skID) - sktData := skt.SocketData - if sktData.StreamsStarted != 6 || sktData.StreamsSucceeded != 2 || sktData.StreamsFailed != 3 || sktData.MessagesSent != 6 || sktData.MessagesReceived != 5 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, StreamsFailed, MessagesSent, MessagesReceived) = (6, 2, 3, 6, 5), got (%d, %d, %d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -// This test is to complete TestCZClientSocketMetricsStreamsAndMessagesCount and -// TestCZServerSocketMetricsStreamsAndMessagesCount by adding the test case of -// server sending RST_STREAM to client due to client side flow control violation. -// It is separated from other cases due to setup incompatibly, i.e. max receive -// size violation will mask flow control violation. -func TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.serverInitialWindowSize = 65536 - // Avoid overflowing connection level flow control window, which will lead to - // transport being closed. - te.serverInitialConnWindowSize = 65536 * 2 - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc, dw := te.clientConnWithConnControl() - tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} - - doServerSideInitiatedFailedStreamWithClientBreakFlowControl(tc, t, dw) - if err := verifyResultWithDelay(func() (bool, error) { - tchan, _ := channelz.GetTopChannels(0) - if len(tchan) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tchan)) - } - if len(tchan[0].SubChans) != 1 { - return false, fmt.Errorf("There should only be one subchannel under top channel %d, not %d", tchan[0].ID, len(tchan[0].SubChans)) - } - var id int64 - for id = range tchan[0].SubChans { - break - } - sc := channelz.GetSubChannel(id) - if sc == nil { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not 0", id) - } - if len(sc.Sockets) != 1 { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not %d", sc.ID, len(sc.Sockets)) - } - for id = range sc.Sockets { - break - } - skt := channelz.GetSocket(id) - sktData := skt.SocketData - if sktData.StreamsStarted != 1 || sktData.StreamsSucceeded != 0 || sktData.StreamsFailed != 1 { - return false, fmt.Errorf("channelz.GetSocket(%d), want (StreamsStarted, StreamsSucceeded, StreamsFailed) = (1, 0, 1), got (%d, %d, %d)", skt.ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed) - } - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - - ns, _ := channelz.GetServerSockets(ss[0].ID, 0) - if len(ns) != 1 { - return false, fmt.Errorf("There should be one server normal socket, not %d", len(ns)) - } - sktData = ns[0].SocketData - if sktData.StreamsStarted != 1 || sktData.StreamsSucceeded != 0 || sktData.StreamsFailed != 1 { - return false, fmt.Errorf("Server socket metric with ID %d, want (StreamsStarted, StreamsSucceeded, StreamsFailed) = (1, 0, 1), got (%d, %d, %d)", ns[0].ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - // disable BDP - te.serverInitialWindowSize = 65536 - te.serverInitialConnWindowSize = 65536 - te.clientInitialWindowSize = 65536 - te.clientInitialConnWindowSize = 65536 - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - for i := 0; i < 10; i++ { - doSuccessfulUnaryCall(tc, t) - } - - var cliSktID, svrSktID int64 - if err := verifyResultWithDelay(func() (bool, error) { - tchan, _ := channelz.GetTopChannels(0) - if len(tchan) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tchan)) - } - if len(tchan[0].SubChans) != 1 { - return false, fmt.Errorf("There should only be one subchannel under top channel %d, not %d", tchan[0].ID, len(tchan[0].SubChans)) - } - var id int64 - for id = range tchan[0].SubChans { - break - } - sc := channelz.GetSubChannel(id) - if sc == nil { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not 0", id) - } - if len(sc.Sockets) != 1 { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not %d", sc.ID, len(sc.Sockets)) - } - for id = range sc.Sockets { - break - } - skt := channelz.GetSocket(id) - sktData := skt.SocketData - // 65536 - 5 (Length-Prefixed-Message size) * 10 = 65486 - if sktData.LocalFlowControlWindow != 65486 || sktData.RemoteFlowControlWindow != 65486 { - return false, fmt.Errorf("Client: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (65536, 65486), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - ns, _ := channelz.GetServerSockets(ss[0].ID, 0) - sktData = ns[0].SocketData - if sktData.LocalFlowControlWindow != 65486 || sktData.RemoteFlowControlWindow != 65486 { - return false, fmt.Errorf("Server: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (65536, 65486), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - cliSktID, svrSktID = id, ss[0].ID - return true, nil - }); err != nil { - t.Fatal(err) - } - - doStreamingInputCallWithLargePayload(tc, t) - - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(cliSktID) - sktData := skt.SocketData - // Local: 65536 - 5 (Length-Prefixed-Message size) * 10 = 65486 - // Remote: 65536 - 5 (Length-Prefixed-Message size) * 10 - 10011 = 55475 - if sktData.LocalFlowControlWindow != 65486 || sktData.RemoteFlowControlWindow != 55475 { - return false, fmt.Errorf("Client: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (65486, 55475), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - ns, _ := channelz.GetServerSockets(svrSktID, 0) - sktData = ns[0].SocketData - if sktData.LocalFlowControlWindow != 55475 || sktData.RemoteFlowControlWindow != 65486 { - return false, fmt.Errorf("Server: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (55475, 65486), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - // triggers transport flow control window update on server side, since unacked - // bytes should be larger than limit now. i.e. 50 + 20022 > 65536/4. - doStreamingInputCallWithLargePayload(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - skt := channelz.GetSocket(cliSktID) - sktData := skt.SocketData - // Local: 65536 - 5 (Length-Prefixed-Message size) * 10 = 65486 - // Remote: 65536 - if sktData.LocalFlowControlWindow != 65486 || sktData.RemoteFlowControlWindow != 65536 { - return false, fmt.Errorf("Client: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (65486, 65536), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - ns, _ := channelz.GetServerSockets(svrSktID, 0) - sktData = ns[0].SocketData - if sktData.LocalFlowControlWindow != 65536 || sktData.RemoteFlowControlWindow != 65486 { - return false, fmt.Errorf("Server: (LocalFlowControlWindow, RemoteFlowControlWindow) size should be (65536, 65486), not (%d, %d)", sktData.LocalFlowControlWindow, sktData.RemoteFlowControlWindow) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZClientSocketMetricsKeepAlive(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.cliKeepAlive = &keepalive.ClientParameters{Time: 500 * time.Millisecond, Timeout: 500 * time.Millisecond} - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - doIdleCallToInvokeKeepAlive(tc, t) - - if err := verifyResultWithDelay(func() (bool, error) { - tchan, _ := channelz.GetTopChannels(0) - if len(tchan) != 1 { - return false, fmt.Errorf("There should only be one top channel, not %d", len(tchan)) - } - if len(tchan[0].SubChans) != 1 { - return false, fmt.Errorf("There should only be one subchannel under top channel %d, not %d", tchan[0].ID, len(tchan[0].SubChans)) - } - var id int64 - for id = range tchan[0].SubChans { - break - } - sc := channelz.GetSubChannel(id) - if sc == nil { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not 0", id) - } - if len(sc.Sockets) != 1 { - return false, fmt.Errorf("There should only be one socket under subchannel %d, not %d", sc.ID, len(sc.Sockets)) - } - for id = range sc.Sockets { - break - } - skt := channelz.GetSocket(id) - if skt.SocketData.KeepAlivesSent != 2 { // doIdleCallToInvokeKeepAlive func is set up to send 2 KeepAlives. - return false, fmt.Errorf("There should be 2 KeepAlives sent, not %d", skt.SocketData.KeepAlivesSent) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.maxServerReceiveMsgSize = newInt(20) - te.maxClientReceiveMsgSize = newInt(20) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc, _ := te.clientConnWithConnControl() - tc := &testServiceClientWrapper{TestServiceClient: testpb.NewTestServiceClient(cc)} - - var svrID int64 - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should only be one server, not %d", len(ss)) - } - svrID = ss[0].ID - return true, nil - }); err != nil { - t.Fatal(err) - } - - doSuccessfulUnaryCall(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - ns, _ := channelz.GetServerSockets(svrID, 0) - sktData := ns[0].SocketData - if sktData.StreamsStarted != 1 || sktData.StreamsSucceeded != 1 || sktData.StreamsFailed != 0 || sktData.MessagesSent != 1 || sktData.MessagesReceived != 1 { - return false, fmt.Errorf("Server socket metric with ID %d, want (StreamsStarted, StreamsSucceeded, MessagesSent, MessagesReceived) = (1, 1, 1, 1), got (%d, %d, %d, %d, %d)", ns[0].ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doServerSideFailedUnaryCall(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - ns, _ := channelz.GetServerSockets(svrID, 0) - sktData := ns[0].SocketData - if sktData.StreamsStarted != 2 || sktData.StreamsSucceeded != 2 || sktData.StreamsFailed != 0 || sktData.MessagesSent != 1 || sktData.MessagesReceived != 1 { - return false, fmt.Errorf("Server socket metric with ID %d, want (StreamsStarted, StreamsSucceeded, StreamsFailed, MessagesSent, MessagesReceived) = (2, 2, 0, 1, 1), got (%d, %d, %d, %d, %d)", ns[0].ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } - - doClientSideInitiatedFailedStream(tc, t) - if err := verifyResultWithDelay(func() (bool, error) { - ns, _ := channelz.GetServerSockets(svrID, 0) - sktData := ns[0].SocketData - if sktData.StreamsStarted != 3 || sktData.StreamsSucceeded != 2 || sktData.StreamsFailed != 1 || sktData.MessagesSent != 2 || sktData.MessagesReceived != 2 { - return false, fmt.Errorf("Server socket metric with ID %d, want (StreamsStarted, StreamsSucceeded, StreamsFailed, MessagesSent, MessagesReceived) = (3, 2, 1, 2, 2), got (%d, %d, %d, %d, %d)", ns[0].ID, sktData.StreamsStarted, sktData.StreamsSucceeded, sktData.StreamsFailed, sktData.MessagesSent, sktData.MessagesReceived) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} - -func TestCZServerSocketMetricsKeepAlive(t *testing.T) { - defer leakcheck.Check(t) - channelz.NewChannelzStorage() - e := tcpClearRREnv - te := newTest(t, e) - te.svrKeepAlive = &keepalive.ServerParameters{Time: 500 * time.Millisecond, Timeout: 500 * time.Millisecond} - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - doIdleCallToInvokeKeepAlive(tc, t) - - if err := verifyResultWithDelay(func() (bool, error) { - ss, _ := channelz.GetServers(0) - if len(ss) != 1 { - return false, fmt.Errorf("There should be one server, not %d", len(ss)) - } - ns, _ := channelz.GetServerSockets(ss[0].ID, 0) - if len(ns) != 1 { - return false, fmt.Errorf("There should be one server normal socket, not %d", len(ns)) - } - if ns[0].SocketData.KeepAlivesSent != 2 { // doIdleCallToInvokeKeepAlive func is set up to send 2 KeepAlives. - return false, fmt.Errorf("There should be 2 KeepAlives sent, not %d", ns[0].SocketData.KeepAlivesSent) - } - return true, nil - }); err != nil { - t.Fatal(err) - } -} diff --git a/examples/google.golang.org/grpc/test/codec_perf/perf.pb.go b/examples/google.golang.org/grpc/test/codec_perf/perf.pb.go deleted file mode 100755 index 6bcbc3f..0000000 --- a/examples/google.golang.org/grpc/test/codec_perf/perf.pb.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: codec_perf/perf.proto - -package codec_perf - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Buffer is a message that contains a body of bytes that is used to exercise -// encoding and decoding overheads. -type Buffer struct { - Body []byte `protobuf:"bytes,1,opt,name=body,proto3" json:"body,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Buffer) Reset() { *m = Buffer{} } -func (m *Buffer) String() string { return proto.CompactTextString(m) } -func (*Buffer) ProtoMessage() {} -func (*Buffer) Descriptor() ([]byte, []int) { - return fileDescriptor_perf_6cc81a33b24d08e7, []int{0} -} -func (m *Buffer) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Buffer.Unmarshal(m, b) -} -func (m *Buffer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Buffer.Marshal(b, m, deterministic) -} -func (dst *Buffer) XXX_Merge(src proto.Message) { - xxx_messageInfo_Buffer.Merge(dst, src) -} -func (m *Buffer) XXX_Size() int { - return xxx_messageInfo_Buffer.Size(m) -} -func (m *Buffer) XXX_DiscardUnknown() { - xxx_messageInfo_Buffer.DiscardUnknown(m) -} - -var xxx_messageInfo_Buffer proto.InternalMessageInfo - -func (m *Buffer) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -func init() { - proto.RegisterType((*Buffer)(nil), "codec.perf.Buffer") -} - -func init() { proto.RegisterFile("codec_perf/perf.proto", fileDescriptor_perf_6cc81a33b24d08e7) } - -var fileDescriptor_perf_6cc81a33b24d08e7 = []byte{ - // 83 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0xce, 0x4f, 0x49, - 0x4d, 0x8e, 0x2f, 0x48, 0x2d, 0x4a, 0xd3, 0x07, 0x11, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, - 0x5c, 0x60, 0x61, 0x3d, 0x90, 0x88, 0x92, 0x0c, 0x17, 0x9b, 0x53, 0x69, 0x5a, 0x5a, 0x6a, 0x91, - 0x90, 0x10, 0x17, 0x4b, 0x52, 0x7e, 0x4a, 0xa5, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x4f, 0x10, 0x98, - 0x9d, 0xc4, 0x06, 0xd6, 0x60, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xa3, 0x5f, 0x4f, 0x3c, 0x49, - 0x00, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/test/codec_perf/perf.proto b/examples/google.golang.org/grpc/test/codec_perf/perf.proto deleted file mode 100755 index 594c6f0..0000000 --- a/examples/google.golang.org/grpc/test/codec_perf/perf.proto +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Messages used for performance tests that may not reference grpc directly for -// reasons of import cycles. -syntax = "proto3"; - -package codec.perf; - -// Buffer is a message that contains a body of bytes that is used to exercise -// encoding and decoding overheads. -message Buffer { - bytes body = 1; -} diff --git a/examples/google.golang.org/grpc/test/end2end_test.go b/examples/google.golang.org/grpc/test/end2end_test.go deleted file mode 100755 index 6574a64..0000000 --- a/examples/google.golang.org/grpc/test/end2end_test.go +++ /dev/null @@ -1,6342 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -//go:generate protoc --go_out=plugins=grpc:. codec_perf/perf.proto -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - -package test - -import ( - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "math" - "net" - "os" - "reflect" - "runtime" - "strings" - "sync" - "sync/atomic" - "syscall" - "testing" - "time" - - "github.com/golang/protobuf/proto" - anypb "github.com/golang/protobuf/ptypes/any" - "golang.org/x/net/context" - "golang.org/x/net/http2" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc" - "google.golang.org/grpc/balancer/roundrobin" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - _ "google.golang.org/grpc/encoding/gzip" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/health" - healthgrpc "google.golang.org/grpc/health/grpc_health_v1" - healthpb "google.golang.org/grpc/health/grpc_health_v1" - "google.golang.org/grpc/internal" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - _ "google.golang.org/grpc/resolver/passthrough" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" - testpb "google.golang.org/grpc/test/grpc_testing" - "google.golang.org/grpc/testdata" -) - -func init() { - grpc.RegisterChannelz() -} - -var ( - // For headers: - testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, - "key3-bin": []string{"binvalue1", string([]byte{1, 2, 3})}, - } - testMetadata2 = metadata.MD{ - "key1": []string{"value12"}, - "key2": []string{"value22"}, - } - // For trailers: - testTrailerMetadata = metadata.MD{ - "tkey1": []string{"trailerValue1"}, - "tkey2": []string{"trailerValue2"}, - "tkey3-bin": []string{"trailerbinvalue1", string([]byte{3, 2, 1})}, - } - testTrailerMetadata2 = metadata.MD{ - "tkey1": []string{"trailerValue12"}, - "tkey2": []string{"trailerValue22"}, - } - // capital "Key" is illegal in HTTP/2. - malformedHTTP2Metadata = metadata.MD{ - "Key": []string{"foo"}, - } - testAppUA = "myApp1/1.0 myApp2/0.9" - failAppUA = "fail-this-RPC" - detailedError = status.ErrorProto(&spb.Status{ - Code: int32(codes.DataLoss), - Message: "error for testing: " + failAppUA, - Details: []*anypb.Any{{ - TypeUrl: "url", - Value: []byte{6, 0, 0, 6, 1, 3}, - }}, - }) -) - -var raceMode bool // set by race.go in race mode - -type testServer struct { - security string // indicate the authentication protocol used by this server. - earlyFail bool // whether to error out the execution of a service handler prematurely. - setAndSendHeader bool // whether to call setHeader and sendHeader. - setHeaderOnly bool // whether to only call setHeader, not sendHeader. - multipleSetTrailer bool // whether to call setTrailer multiple times. - unaryCallSleepTime time.Duration -} - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); ok { - // For testing purpose, returns an error if user-agent is failAppUA. - // To test that client gets the correct error. - if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) { - return nil, detailedError - } - var str []string - for _, entry := range md["user-agent"] { - str = append(str, "ua", entry) - } - grpc.SendHeader(ctx, metadata.Pairs(str...)) - } - return new(testpb.Empty), nil -} - -func newPayload(t testpb.PayloadType, size int32) (*testpb.Payload, error) { - if size < 0 { - return nil, fmt.Errorf("Requested a response with invalid length %d", size) - } - body := make([]byte, size) - switch t { - case testpb.PayloadType_COMPRESSABLE: - case testpb.PayloadType_UNCOMPRESSABLE: - return nil, fmt.Errorf("PayloadType UNCOMPRESSABLE is not supported") - default: - return nil, fmt.Errorf("Unsupported payload type: %d", t) - } - return &testpb.Payload{ - Type: t, - Body: body, - }, nil -} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - if ok { - if _, exists := md[":authority"]; !exists { - return nil, status.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md) - } - if s.setAndSendHeader { - if err := grpc.SetHeader(ctx, md); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want ", md, err) - } - if err := grpc.SendHeader(ctx, testMetadata2); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SendHeader(_, %v) = %v, want ", testMetadata2, err) - } - } else if s.setHeaderOnly { - if err := grpc.SetHeader(ctx, md); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want ", md, err) - } - if err := grpc.SetHeader(ctx, testMetadata2); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetHeader(_, %v) = %v, want ", testMetadata2, err) - } - } else { - if err := grpc.SendHeader(ctx, md); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SendHeader(_, %v) = %v, want ", md, err) - } - } - if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetTrailer(_, %v) = %v, want ", testTrailerMetadata, err) - } - if s.multipleSetTrailer { - if err := grpc.SetTrailer(ctx, testTrailerMetadata2); err != nil { - return nil, status.Errorf(status.Code(err), "grpc.SetTrailer(_, %v) = %v, want ", testTrailerMetadata2, err) - } - } - } - pr, ok := peer.FromContext(ctx) - if !ok { - return nil, status.Error(codes.DataLoss, "failed to get peer from ctx") - } - if pr.Addr == net.Addr(nil) { - return nil, status.Error(codes.DataLoss, "failed to get peer address") - } - if s.security != "" { - // Check Auth info - var authType, serverName string - switch info := pr.AuthInfo.(type) { - case credentials.TLSInfo: - authType = info.AuthType() - serverName = info.State.ServerName - default: - return nil, status.Error(codes.Unauthenticated, "Unknown AuthInfo type") - } - if authType != s.security { - return nil, status.Errorf(codes.Unauthenticated, "Wrong auth type: got %q, want %q", authType, s.security) - } - if serverName != "x.test.youtube.com" { - return nil, status.Errorf(codes.Unauthenticated, "Unknown server name %q", serverName) - } - } - // Simulate some service delay. - time.Sleep(s.unaryCallSleepTime) - - payload, err := newPayload(in.GetResponseType(), in.GetResponseSize()) - if err != nil { - return nil, err - } - - return &testpb.SimpleResponse{ - Payload: payload, - }, nil -} - -func (s *testServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - if md, ok := metadata.FromIncomingContext(stream.Context()); ok { - if _, exists := md[":authority"]; !exists { - return status.Errorf(codes.DataLoss, "expected an :authority metadata: %v", md) - } - // For testing purpose, returns an error if user-agent is failAppUA. - // To test that client gets the correct error. - if ua, ok := md["user-agent"]; !ok || strings.HasPrefix(ua[0], failAppUA) { - return status.Error(codes.DataLoss, "error for testing: "+failAppUA) - } - } - cs := args.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(args.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - return err - } - } - return nil -} - -func (s *testServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - var sum int - for { - in, err := stream.Recv() - if err == io.EOF { - return stream.SendAndClose(&testpb.StreamingInputCallResponse{ - AggregatedPayloadSize: int32(sum), - }) - } - if err != nil { - return err - } - p := in.GetPayload().GetBody() - sum += len(p) - if s.earlyFail { - return status.Error(codes.NotFound, "not found") - } - } -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if s.setAndSendHeader { - if err := stream.SetHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want ", stream, md, err) - } - if err := stream.SendHeader(testMetadata2); err != nil { - return status.Errorf(status.Code(err), "%v.SendHeader(_, %v) = %v, want ", stream, testMetadata2, err) - } - } else if s.setHeaderOnly { - if err := stream.SetHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want ", stream, md, err) - } - if err := stream.SetHeader(testMetadata2); err != nil { - return status.Errorf(status.Code(err), "%v.SetHeader(_, %v) = %v, want ", stream, testMetadata2, err) - } - } else { - if err := stream.SendHeader(md); err != nil { - return status.Errorf(status.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - } - stream.SetTrailer(testTrailerMetadata) - if s.multipleSetTrailer { - stream.SetTrailer(testTrailerMetadata2) - } - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - // to facilitate testSvrWriteStatusEarlyWrite - if status.Code(err) == codes.ResourceExhausted { - return status.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error()) - } - return err - } - cs := in.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(in.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - // to facilitate testSvrWriteStatusEarlyWrite - if status.Code(err) == codes.ResourceExhausted { - return status.Errorf(codes.Internal, "fake error for test testSvrWriteStatusEarlyWrite. true error: %s", err.Error()) - } - return err - } - } - } -} - -func (s *testServer) HalfDuplexCall(stream testpb.TestService_HalfDuplexCallServer) error { - var msgBuf []*testpb.StreamingOutputCallRequest - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - break - } - if err != nil { - return err - } - msgBuf = append(msgBuf, in) - } - for _, m := range msgBuf { - cs := m.GetResponseParameters() - for _, c := range cs { - if us := c.GetIntervalUs(); us > 0 { - time.Sleep(time.Duration(us) * time.Microsecond) - } - - payload, err := newPayload(m.GetResponseType(), c.GetSize()) - if err != nil { - return err - } - - if err := stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: payload, - }); err != nil { - return err - } - } - } - return nil -} - -type env struct { - name string - network string // The type of network such as tcp, unix, etc. - security string // The security protocol such as TLS, SSH, etc. - httpHandler bool // whether to use the http.Handler ServerTransport; requires TLS - balancer string // One of "round_robin", "pick_first", "v1", or "". - customDialer func(string, string, time.Duration) (net.Conn, error) -} - -func (e env) runnable() bool { - if runtime.GOOS == "windows" && e.network == "unix" { - return false - } - return true -} - -func (e env) dialer(addr string, timeout time.Duration) (net.Conn, error) { - if e.customDialer != nil { - return e.customDialer(e.network, addr, timeout) - } - return net.DialTimeout(e.network, addr, timeout) -} - -var ( - tcpClearEnv = env{name: "tcp-clear-v1-balancer", network: "tcp", balancer: "v1"} - tcpTLSEnv = env{name: "tcp-tls-v1-balancer", network: "tcp", security: "tls", balancer: "v1"} - tcpClearRREnv = env{name: "tcp-clear", network: "tcp", balancer: "round_robin"} - tcpTLSRREnv = env{name: "tcp-tls", network: "tcp", security: "tls", balancer: "round_robin"} - handlerEnv = env{name: "handler-tls", network: "tcp", security: "tls", httpHandler: true, balancer: "round_robin"} - noBalancerEnv = env{name: "no-balancer", network: "tcp", security: "tls"} - allEnv = []env{tcpClearEnv, tcpTLSEnv, tcpClearRREnv, tcpTLSRREnv, handlerEnv, noBalancerEnv} -) - -var onlyEnv = flag.String("only_env", "", "If non-empty, one of 'tcp-clear', 'tcp-tls', 'unix-clear', 'unix-tls', or 'handler-tls' to only run the tests for that environment. Empty means all.") - -func listTestEnv() (envs []env) { - if *onlyEnv != "" { - for _, e := range allEnv { - if e.name == *onlyEnv { - if !e.runnable() { - panic(fmt.Sprintf("--only_env environment %q does not run on %s", *onlyEnv, runtime.GOOS)) - } - return []env{e} - } - } - panic(fmt.Sprintf("invalid --only_env value %q", *onlyEnv)) - } - for _, e := range allEnv { - if e.runnable() { - envs = append(envs, e) - } - } - return envs -} - -// test is an end-to-end test. It should be created with the newTest -// func, modified as needed, and then started with its startServer method. -// It should be cleaned up with the tearDown method. -type test struct { - t *testing.T - e env - - ctx context.Context // valid for life of test, before tearDown - cancel context.CancelFunc - - // Configurable knobs, after newTest returns: - testServer testpb.TestServiceServer // nil means none - healthServer *health.Server // nil means disabled - maxStream uint32 - tapHandle tap.ServerInHandle - maxMsgSize *int - maxClientReceiveMsgSize *int - maxClientSendMsgSize *int - maxServerReceiveMsgSize *int - maxServerSendMsgSize *int - userAgent string - // clientCompression and serverCompression are set to test the deprecated API - // WithCompressor and WithDecompressor. - clientCompression bool - serverCompression bool - // clientUseCompression is set to test the new compressor registration API UseCompressor. - clientUseCompression bool - // clientNopCompression is set to create a compressor whose type is not supported. - clientNopCompression bool - unaryClientInt grpc.UnaryClientInterceptor - streamClientInt grpc.StreamClientInterceptor - unaryServerInt grpc.UnaryServerInterceptor - streamServerInt grpc.StreamServerInterceptor - unknownHandler grpc.StreamHandler - sc <-chan grpc.ServiceConfig - customCodec grpc.Codec - serverInitialWindowSize int32 - serverInitialConnWindowSize int32 - clientInitialWindowSize int32 - clientInitialConnWindowSize int32 - perRPCCreds credentials.PerRPCCredentials - customDialOptions []grpc.DialOption - resolverScheme string - cliKeepAlive *keepalive.ClientParameters - svrKeepAlive *keepalive.ServerParameters - - // All test dialing is blocking by default. Set this to true if dial - // should be non-blocking. - nonBlockingDial bool - - // srv and srvAddr are set once startServer is called. - srv *grpc.Server - srvAddr string - - // srvs and srvAddrs are set once startServers is called. - srvs []*grpc.Server - srvAddrs []string - - cc *grpc.ClientConn // nil until requested via clientConn - restoreLogs func() // nil unless declareLogNoise is used -} - -func (te *test) tearDown() { - if te.cancel != nil { - te.cancel() - te.cancel = nil - } - - if te.cc != nil { - te.cc.Close() - te.cc = nil - } - - if te.restoreLogs != nil { - te.restoreLogs() - te.restoreLogs = nil - } - - if te.srv != nil { - te.srv.Stop() - } - if len(te.srvs) != 0 { - for _, s := range te.srvs { - s.Stop() - } - } -} - -// newTest returns a new test using the provided testing.T and -// environment. It is returned with default values. Tests should -// modify it before calling its startServer and clientConn methods. -func newTest(t *testing.T, e env) *test { - te := &test{ - t: t, - e: e, - maxStream: math.MaxUint32, - } - te.ctx, te.cancel = context.WithCancel(context.Background()) - return te -} - -func (te *test) listenAndServe(ts testpb.TestServiceServer, listen func(network, address string) (net.Listener, error)) net.Listener { - te.testServer = ts - te.t.Logf("Running test in %s environment...", te.e.name) - sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(te.maxStream)} - if te.maxMsgSize != nil { - sopts = append(sopts, grpc.MaxMsgSize(*te.maxMsgSize)) - } - if te.maxServerReceiveMsgSize != nil { - sopts = append(sopts, grpc.MaxRecvMsgSize(*te.maxServerReceiveMsgSize)) - } - if te.maxServerSendMsgSize != nil { - sopts = append(sopts, grpc.MaxSendMsgSize(*te.maxServerSendMsgSize)) - } - if te.tapHandle != nil { - sopts = append(sopts, grpc.InTapHandle(te.tapHandle)) - } - if te.serverCompression { - sopts = append(sopts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.unaryServerInt != nil { - sopts = append(sopts, grpc.UnaryInterceptor(te.unaryServerInt)) - } - if te.streamServerInt != nil { - sopts = append(sopts, grpc.StreamInterceptor(te.streamServerInt)) - } - if te.unknownHandler != nil { - sopts = append(sopts, grpc.UnknownServiceHandler(te.unknownHandler)) - } - if te.serverInitialWindowSize > 0 { - sopts = append(sopts, grpc.InitialWindowSize(te.serverInitialWindowSize)) - } - if te.serverInitialConnWindowSize > 0 { - sopts = append(sopts, grpc.InitialConnWindowSize(te.serverInitialConnWindowSize)) - } - la := "localhost:0" - switch te.e.network { - case "unix": - la = "/tmp/testsock" + fmt.Sprintf("%d", time.Now().UnixNano()) - syscall.Unlink(la) - } - lis, err := listen(te.e.network, la) - if err != nil { - te.t.Fatalf("Failed to listen: %v", err) - } - switch te.e.security { - case "tls": - creds, err := credentials.NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - te.t.Fatalf("Failed to generate credentials %v", err) - } - sopts = append(sopts, grpc.Creds(creds)) - case "clientTimeoutCreds": - sopts = append(sopts, grpc.Creds(&clientTimeoutCreds{})) - } - if te.customCodec != nil { - sopts = append(sopts, grpc.CustomCodec(te.customCodec)) - } - if te.svrKeepAlive != nil { - sopts = append(sopts, grpc.KeepaliveParams(*te.svrKeepAlive)) - } - s := grpc.NewServer(sopts...) - te.srv = s - if te.e.httpHandler { - internal.TestingUseHandlerImpl(s) - } - if te.healthServer != nil { - healthgrpc.RegisterHealthServer(s, te.healthServer) - } - if te.testServer != nil { - testpb.RegisterTestServiceServer(s, te.testServer) - } - addr := la - switch te.e.network { - case "unix": - default: - _, port, err := net.SplitHostPort(lis.Addr().String()) - if err != nil { - te.t.Fatalf("Failed to parse listener address: %v", err) - } - addr = "localhost:" + port - } - - go s.Serve(lis) - te.srvAddr = addr - return lis -} - -func (te *test) startServerWithConnControl(ts testpb.TestServiceServer) *listenerWrapper { - l := te.listenAndServe(ts, listenWithConnControl) - return l.(*listenerWrapper) -} - -// startServer starts a gRPC server listening. Callers should defer a -// call to te.tearDown to clean up. -func (te *test) startServer(ts testpb.TestServiceServer) { - te.listenAndServe(ts, net.Listen) -} - -type nopCompressor struct { - grpc.Compressor -} - -// NewNopCompressor creates a compressor to test the case that type is not supported. -func NewNopCompressor() grpc.Compressor { - return &nopCompressor{grpc.NewGZIPCompressor()} -} - -func (c *nopCompressor) Type() string { - return "nop" -} - -type nopDecompressor struct { - grpc.Decompressor -} - -// NewNopDecompressor creates a decompressor to test the case that type is not supported. -func NewNopDecompressor() grpc.Decompressor { - return &nopDecompressor{grpc.NewGZIPDecompressor()} -} - -func (d *nopDecompressor) Type() string { - return "nop" -} - -func (te *test) configDial(opts ...grpc.DialOption) ([]grpc.DialOption, string) { - opts = append(opts, grpc.WithDialer(te.e.dialer), grpc.WithUserAgent(te.userAgent)) - - if te.sc != nil { - opts = append(opts, grpc.WithServiceConfig(te.sc)) - } - - if te.clientCompression { - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.clientUseCompression { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.UseCompressor("gzip"))) - } - if te.clientNopCompression { - opts = append(opts, - grpc.WithCompressor(NewNopCompressor()), - grpc.WithDecompressor(NewNopDecompressor()), - ) - } - if te.unaryClientInt != nil { - opts = append(opts, grpc.WithUnaryInterceptor(te.unaryClientInt)) - } - if te.streamClientInt != nil { - opts = append(opts, grpc.WithStreamInterceptor(te.streamClientInt)) - } - if te.maxMsgSize != nil { - opts = append(opts, grpc.WithMaxMsgSize(*te.maxMsgSize)) - } - if te.maxClientReceiveMsgSize != nil { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(*te.maxClientReceiveMsgSize))) - } - if te.maxClientSendMsgSize != nil { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(*te.maxClientSendMsgSize))) - } - switch te.e.security { - case "tls": - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - te.t.Fatalf("Failed to load credentials: %v", err) - } - opts = append(opts, grpc.WithTransportCredentials(creds)) - case "clientTimeoutCreds": - opts = append(opts, grpc.WithTransportCredentials(&clientTimeoutCreds{})) - default: - opts = append(opts, grpc.WithInsecure()) - } - // TODO(bar) switch balancer case "pick_first". - var scheme string - if te.resolverScheme == "" { - scheme = "passthrough:///" - } else { - scheme = te.resolverScheme + ":///" - } - switch te.e.balancer { - case "v1": - opts = append(opts, grpc.WithBalancer(grpc.RoundRobin(nil))) - case "round_robin": - opts = append(opts, grpc.WithBalancerName(roundrobin.Name)) - } - if te.clientInitialWindowSize > 0 { - opts = append(opts, grpc.WithInitialWindowSize(te.clientInitialWindowSize)) - } - if te.clientInitialConnWindowSize > 0 { - opts = append(opts, grpc.WithInitialConnWindowSize(te.clientInitialConnWindowSize)) - } - if te.perRPCCreds != nil { - opts = append(opts, grpc.WithPerRPCCredentials(te.perRPCCreds)) - } - if te.customCodec != nil { - opts = append(opts, grpc.WithDefaultCallOptions(grpc.CallCustomCodec(te.customCodec))) - } - if !te.nonBlockingDial && te.srvAddr != "" { - // Only do a blocking dial if server is up. - opts = append(opts, grpc.WithBlock()) - } - if te.srvAddr == "" { - te.srvAddr = "client.side.only.test" - } - if te.cliKeepAlive != nil { - opts = append(opts, grpc.WithKeepaliveParams(*te.cliKeepAlive)) - } - opts = append(opts, te.customDialOptions...) - return opts, scheme -} - -func (te *test) clientConnWithConnControl() (*grpc.ClientConn, *dialerWrapper) { - if te.cc != nil { - return te.cc, nil - } - opts, scheme := te.configDial() - dw := &dialerWrapper{} - // overwrite the dialer before - opts = append(opts, grpc.WithDialer(dw.dialer)) - var err error - te.cc, err = grpc.Dial(scheme+te.srvAddr, opts...) - if err != nil { - te.t.Fatalf("Dial(%q) = %v", scheme+te.srvAddr, err) - } - return te.cc, dw -} - -func (te *test) clientConn(opts ...grpc.DialOption) *grpc.ClientConn { - if te.cc != nil { - return te.cc - } - var scheme string - opts, scheme = te.configDial(opts...) - var err error - te.cc, err = grpc.Dial(scheme+te.srvAddr, opts...) - if err != nil { - te.t.Fatalf("Dial(%q) = %v", scheme+te.srvAddr, err) - } - return te.cc -} - -func (te *test) declareLogNoise(phrases ...string) { - te.restoreLogs = declareLogNoise(te.t, phrases...) -} - -func (te *test) withServerTester(fn func(st *serverTester)) { - c, err := te.e.dialer(te.srvAddr, 10*time.Second) - if err != nil { - te.t.Fatal(err) - } - defer c.Close() - if te.e.security == "tls" { - c = tls.Client(c, &tls.Config{ - InsecureSkipVerify: true, - NextProtos: []string{http2.NextProtoTLS}, - }) - } - st := newServerTesterFromConn(te.t, c) - st.greet() - fn(st) -} - -type lazyConn struct { - net.Conn - beLazy int32 -} - -func (l *lazyConn) Write(b []byte) (int, error) { - if atomic.LoadInt32(&(l.beLazy)) == 1 { - time.Sleep(time.Second) - } - return l.Conn.Write(b) -} - -func TestContextDeadlineNotIgnored(t *testing.T) { - defer leakcheck.Check(t) - e := noBalancerEnv - var lc *lazyConn - e.customDialer = func(network, addr string, timeout time.Duration) (net.Conn, error) { - conn, err := net.DialTimeout(network, addr, timeout) - if err != nil { - return nil, err - } - lc = &lazyConn{Conn: conn} - return lc, nil - } - - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - atomic.StoreInt32(&(lc.beLazy), 1) - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - t1 := time.Now() - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, context.DeadlineExceeded", err) - } - if time.Since(t1) > 2*time.Second { - t.Fatalf("TestService/EmptyCall(_, _) ran over the deadline") - } -} - -func TestTimeoutOnDeadServer(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testTimeoutOnDeadServer(t, e) - } -} - -func testTimeoutOnDeadServer(t *testing.T, e env) { - te := newTest(t, e) - te.customDialOptions = []grpc.DialOption{grpc.WithWaitForHandshake()} - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - te.srv.Stop() - - // Wait for the client to notice the connection is gone. - ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) - state := cc.GetState() - for ; state == connectivity.Ready && cc.WaitForStateChange(ctx, state); state = cc.GetState() { - } - cancel() - if state == connectivity.Ready { - t.Fatalf("Timed out waiting for non-ready state") - } - ctx, cancel = context.WithTimeout(context.Background(), time.Millisecond) - _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)) - cancel() - if e.balancer != "" && status.Code(err) != codes.DeadlineExceeded { - // If e.balancer == nil, the ac will stop reconnecting because the dialer returns non-temp error, - // the error will be an internal error. - t.Fatalf("TestService/EmptyCall(%v, _) = _, %v, want _, error code: %s", ctx, err, codes.DeadlineExceeded) - } - awaitNewConnLogOutput() -} - -func TestServerGracefulStopIdempotent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGracefulStopIdempotent(t, e) - } -} - -func testServerGracefulStopIdempotent(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - for i := 0; i < 3; i++ { - te.srv.GracefulStop() - } -} - -func TestServerGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGoAway(t, e) - } -} - -func testServerGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil && status.Code(err) != codes.DeadlineExceeded { - cancel() - break - } - cancel() - } - // A new RPC should fail. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable && status.Code(err) != codes.Internal { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s or %s", err, codes.Unavailable, codes.Internal) - } - <-ch - awaitNewConnLogOutput() -} - -func TestServerGoAwayPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerGoAwayPendingRPC(t, e) - } -} - -func testServerGoAwayPendingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, ", tc, err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - start := time.Now() - errored := false - for time.Since(start) < time.Second { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)) - cancel() - if err != nil { - errored = true - break - } - } - if !errored { - t.Fatalf("GoAway never received by client") - } - respParam := []*testpb.ResponseParameters{{Size: 1}} - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - // The existing RPC should be still good to proceed. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(_) = %v, want ", stream, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, ", stream, err) - } - // The RPC will run until canceled. - cancel() - <-ch - awaitNewConnLogOutput() -} - -func TestServerMultipleGoAwayPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testServerMultipleGoAwayPendingRPC(t, e) - } -} - -func testServerMultipleGoAwayPendingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithCancel(context.Background()) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, ", tc, err) - } - ch1 := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch1) - }() - ch2 := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch2) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err != nil { - cancel() - break - } - cancel() - } - select { - case <-ch1: - t.Fatal("GracefulStop() terminated early") - case <-ch2: - t.Fatal("GracefulStop() terminated early") - default: - } - respParam := []*testpb.ResponseParameters{ - { - Size: 1, - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - // The existing RPC should be still good to proceed. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, ", stream, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() = %v, want ", stream, err) - } - <-ch1 - <-ch2 - cancel() - awaitNewConnLogOutput() -} - -func TestConcurrentClientConnCloseAndServerGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testConcurrentClientConnCloseAndServerGoAway(t, e) - } -} - -func testConcurrentClientConnCloseAndServerGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, ", tc, err) - } - ch := make(chan struct{}) - // Close ClientConn and Server concurrently. - go func() { - te.srv.GracefulStop() - close(ch) - }() - go func() { - cc.Close() - }() - <-ch -} - -func TestConcurrentServerStopAndGoAway(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testConcurrentServerStopAndGoAway(t, e) - } -} - -func testConcurrentServerStopAndGoAway(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - stream, err := tc.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - // Finish an RPC to make sure the connection is good. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _, _) = _, %v, want _, ", tc, err) - } - ch := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(ch) - }() - // Loop until the server side GoAway signal is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); err != nil { - cancel() - break - } - cancel() - } - // Stop the server and close all the connections. - te.srv.Stop() - respParam := []*testpb.ResponseParameters{ - { - Size: 1, - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(100)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - sendStart := time.Now() - for { - if err := stream.Send(req); err == io.EOF { - // stream.Send should eventually send io.EOF - break - } else if err != nil { - // Send should never return a transport-level error. - t.Fatalf("stream.Send(%v) = %v; want ", req, err) - } - if time.Since(sendStart) > 2*time.Second { - t.Fatalf("stream.Send(_) did not return io.EOF after 2s") - } - time.Sleep(time.Millisecond) - } - if _, err := stream.Recv(); err == nil || err == io.EOF { - t.Fatalf("%v.Recv() = _, %v, want _, ", stream, err) - } - <-ch - awaitNewConnLogOutput() -} - -func TestClientConnCloseAfterGoAwayWithActiveStream(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testClientConnCloseAfterGoAwayWithActiveStream(t, e) - } -} - -func testClientConnCloseAfterGoAwayWithActiveStream(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - if _, err := tc.FullDuplexCall(ctx); err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want _, ", tc, err) - } - done := make(chan struct{}) - go func() { - te.srv.GracefulStop() - close(done) - }() - time.Sleep(50 * time.Millisecond) - cc.Close() - timeout := time.NewTimer(time.Second) - select { - case <-done: - case <-timeout.C: - t.Fatalf("Test timed-out.") - } -} - -func TestFailFast(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testFailFast(t, e) - } -} - -func testFailFast(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - // Stop the server and tear down all the existing connections. - te.srv.Stop() - // Loop until the server teardown is propagated to the client. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - _, err := tc.EmptyCall(ctx, &testpb.Empty{}) - cancel() - if status.Code(err) == codes.Unavailable { - break - } - t.Logf("%v.EmptyCall(_, _) = _, %v", tc, err) - time.Sleep(10 * time.Millisecond) - } - // The client keeps reconnecting and ongoing fail-fast RPCs should fail with code.Unavailable. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _, _) = _, %v, want _, error code: %s", err, codes.Unavailable) - } - if _, err := tc.StreamingInputCall(context.Background()); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/StreamingInputCall(_) = _, %v, want _, error code: %s", err, codes.Unavailable) - } - - awaitNewConnLogOutput() -} - -func testServiceConfigSetup(t *testing.T, e env) *test { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - return te -} - -func newBool(b bool) (a *bool) { - return &b -} - -func newInt(b int) (a *int) { - return &b -} - -func newDuration(b time.Duration) (a *time.Duration) { - a = new(time.Duration) - *a = b - return -} - -func TestGetMethodConfig(t *testing.T) { - te := testServiceConfigSetup(t, tcpClearRREnv) - defer te.tearDown() - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - te.resolverScheme = r.Scheme() - cc := te.clientConn() - r.NewAddress([]resolver.Address{{Addr: te.srvAddr}}) - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "EmptyCall" - } - ], - "waitForReady": true, - "timeout": ".001s" - }, - { - "name": [ - { - "service": "grpc.testing.TestService" - } - ], - "waitForReady": false - } - ] -}`) - - tc := testpb.NewTestServiceClient(cc) - - // Make sure service config has been processed by grpc. - for { - if cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall").WaitForReady != nil { - break - } - time.Sleep(time.Millisecond) - } - - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - var err error - if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "UnaryCall" - } - ], - "waitForReady": true, - "timeout": ".001s" - }, - { - "name": [ - { - "service": "grpc.testing.TestService" - } - ], - "waitForReady": false - } - ] -}`) - - // Make sure service config has been processed by grpc. - for { - if mc := cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall"); mc.WaitForReady != nil && !*mc.WaitForReady { - break - } - time.Sleep(time.Millisecond) - } - // The following RPCs are expected to become fail-fast. - if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.Unavailable) - } -} - -func TestServiceConfigWaitForReady(t *testing.T) { - te := testServiceConfigSetup(t, tcpClearRREnv) - defer te.tearDown() - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - // Case1: Client API set failfast to be false, and service config set wait_for_ready to be false, Client API should win, and the rpc will wait until deadline exceeds. - te.resolverScheme = r.Scheme() - cc := te.clientConn() - r.NewAddress([]resolver.Address{{Addr: te.srvAddr}}) - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "EmptyCall" - }, - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "waitForReady": false, - "timeout": ".001s" - } - ] -}`) - - tc := testpb.NewTestServiceClient(cc) - - // Make sure service config has been processed by grpc. - for { - if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").WaitForReady != nil { - break - } - time.Sleep(time.Millisecond) - } - - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - var err error - if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background(), grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - - // Generate a service config update. - // Case2:Client API set failfast to be false, and service config set wait_for_ready to be true, and the rpc will wait until deadline exceeds. - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "EmptyCall" - }, - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "waitForReady": true, - "timeout": ".001s" - } - ] -}`) - - // Wait for the new service config to take effect. - for { - if mc := cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall"); mc.WaitForReady != nil && *mc.WaitForReady { - break - } - time.Sleep(time.Millisecond) - } - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background()); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } -} - -func TestServiceConfigTimeout(t *testing.T) { - te := testServiceConfigSetup(t, tcpClearRREnv) - defer te.tearDown() - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - // Case1: Client API sets timeout to be 1ns and ServiceConfig sets timeout to be 1hr. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - te.resolverScheme = r.Scheme() - cc := te.clientConn() - r.NewAddress([]resolver.Address{{Addr: te.srvAddr}}) - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "EmptyCall" - }, - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "waitForReady": true, - "timeout": "3600s" - } - ] -}`) - - tc := testpb.NewTestServiceClient(cc) - - // Make sure service config has been processed by grpc. - for { - if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").Timeout != nil { - break - } - time.Sleep(time.Millisecond) - } - - // The following RPCs are expected to become non-fail-fast ones with 1ns deadline. - var err error - ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) - if _, err = tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - - ctx, cancel = context.WithTimeout(context.Background(), time.Nanosecond) - if _, err = tc.FullDuplexCall(ctx, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() - - // Generate a service config update. - // Case2: Client API sets timeout to be 1hr and ServiceConfig sets timeout to be 1ns. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "EmptyCall" - }, - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "waitForReady": true, - "timeout": ".000000001s" - } - ] -}`) - - // Wait for the new service config to take effect. - for { - if mc := cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall"); mc.Timeout != nil && *mc.Timeout == time.Nanosecond { - break - } - time.Sleep(time.Millisecond) - } - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err = tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err = tc.FullDuplexCall(ctx, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() -} - -func TestServiceConfigMaxMsgSize(t *testing.T) { - e := tcpClearRREnv - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - // Setting up values and objects shared across all test cases. - const smallSize = 1 - const largeSize = 1024 - const extraLargeSize = 2048 - - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize) - if err != nil { - t.Fatal(err) - } - - scjs := `{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "UnaryCall" - }, - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "maxRequestMessageBytes": 2048, - "maxResponseMessageBytes": 2048 - } - ] -}` - - // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te1 := testServiceConfigSetup(t, e) - defer te1.tearDown() - - te1.resolverScheme = r.Scheme() - te1.nonBlockingDial = true - te1.startServer(&testServer{security: e.security}) - cc1 := te1.clientConn() - - r.NewAddress([]resolver.Address{{Addr: te1.srvAddr}}) - r.NewServiceConfig(scjs) - tc := testpb.NewTestServiceClient(cc1) - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(extraLargeSize), - Payload: smallPayload, - } - - for { - if cc1.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil { - break - } - time.Sleep(time.Millisecond) - } - - // Test for unary RPC recv. - if _, err = tc.UnaryCall(context.Background(), req, grpc.FailFast(false)); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = extraLargePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - respParam := []*testpb.ResponseParameters{ - { - Size: int32(extraLargeSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: smallPayload, - } - stream, err := tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = extraLargePayload - stream, err = tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case2: Client API set maxReqSize to 1024 (send), maxRespSize to 1024 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te2 := testServiceConfigSetup(t, e) - te2.resolverScheme = r.Scheme() - te2.nonBlockingDial = true - te2.maxClientReceiveMsgSize = newInt(1024) - te2.maxClientSendMsgSize = newInt(1024) - - te2.startServer(&testServer{security: e.security}) - defer te2.tearDown() - cc2 := te2.clientConn() - r.NewAddress([]resolver.Address{{Addr: te2.srvAddr}}) - r.NewServiceConfig(scjs) - tc = testpb.NewTestServiceClient(cc2) - - for { - if cc2.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil { - break - } - time.Sleep(time.Millisecond) - } - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = int32(largeSize) - - if _, err = tc.UnaryCall(context.Background(), req, grpc.FailFast(false)); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te2.ctx) - respParam[0].Size = int32(largeSize) - sreq.Payload = smallPayload - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te2.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case3: Client API set maxReqSize to 4096 (send), maxRespSize to 4096 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te3 := testServiceConfigSetup(t, e) - te3.resolverScheme = r.Scheme() - te3.nonBlockingDial = true - te3.maxClientReceiveMsgSize = newInt(4096) - te3.maxClientSendMsgSize = newInt(4096) - - te3.startServer(&testServer{security: e.security}) - defer te3.tearDown() - - cc3 := te3.clientConn() - r.NewAddress([]resolver.Address{{Addr: te3.srvAddr}}) - r.NewServiceConfig(scjs) - tc = testpb.NewTestServiceClient(cc3) - - for { - if cc3.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").MaxReqSize != nil { - break - } - time.Sleep(time.Millisecond) - } - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = int32(largeSize) - - if _, err = tc.UnaryCall(context.Background(), req, grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want ", err) - } - - req.ResponseSize = int32(extraLargeSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want ", err) - } - - req.Payload = extraLargePayload - if _, err = tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam[0].Size = int32(largeSize) - sreq.Payload = smallPayload - - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err = stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want ", stream, err) - } - - respParam[0].Size = int32(extraLargeSize) - - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - sreq.Payload = extraLargePayload - if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } -} - -// Reading from a streaming RPC may fail with context canceled if timeout was -// set by service config (https://github.com/grpc/grpc-go/issues/1818). This -// test makes sure read from streaming RPC doesn't fail in this case. -func TestStreamingRPCWithTimeoutInServiceConfigRecv(t *testing.T) { - te := testServiceConfigSetup(t, tcpClearRREnv) - te.startServer(&testServer{security: tcpClearRREnv.security}) - defer te.tearDown() - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - te.resolverScheme = r.Scheme() - te.nonBlockingDial = true - fmt.Println("1") - cc := te.clientConn() - fmt.Println("10") - tc := testpb.NewTestServiceClient(cc) - - r.NewAddress([]resolver.Address{{Addr: te.srvAddr}}) - r.NewServiceConfig(`{ - "methodConfig": [ - { - "name": [ - { - "service": "grpc.testing.TestService", - "method": "FullDuplexCall" - } - ], - "waitForReady": true, - "timeout": "10s" - } - ] - }`) - // Make sure service config has been processed by grpc. - for { - if cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall").Timeout != nil { - break - } - time.Sleep(time.Millisecond) - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want ", err) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 0) - if err != nil { - t.Fatalf("failed to newPayload: %v", err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{{Size: 0}}, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("stream.Send(%v) = %v, want ", req, err) - } - stream.CloseSend() - time.Sleep(time.Second) - // Sleep 1 second before recv to make sure the final status is received - // before the recv. - if _, err := stream.Recv(); err != nil { - t.Fatalf("stream.Recv = _, %v, want _, ", err) - } - // Keep reading to drain the stream. - for { - if _, err := stream.Recv(); err != nil { - break - } - } -} - -func TestMaxMsgSizeClientDefault(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeClientDefault(t, e) - } -} - -func testMaxMsgSizeClientDefault(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 4 * 1024 * 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeSize), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: int32(largeSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC recv. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} - -func TestMaxMsgSizeClientAPI(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeClientAPI(t, e) - } -} - -func testMaxMsgSizeClientAPI(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - // To avoid error on server side. - te.maxServerSendMsgSize = newInt(5 * 1024 * 1024) - te.maxClientReceiveMsgSize = newInt(1024) - te.maxClientSendMsgSize = newInt(1024) - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeSize), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: int32(largeSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC recv. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } -} - -func TestMaxMsgSizeServerAPI(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMaxMsgSizeServerAPI(t, e) - } -} - -func testMaxMsgSizeServerAPI(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.maxServerReceiveMsgSize = newInt(1024) - te.maxServerSendMsgSize = newInt(1024) - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const smallSize = 1 - const largeSize = 1024 - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(largeSize), - Payload: smallPayload, - } - // Test for unary RPC send. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC recv. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - respParam := []*testpb.ResponseParameters{ - { - Size: int32(largeSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: smallPayload, - } - - // Test for streaming RPC send. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} - -func TestTap(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testTap(t, e) - } -} - -type myTap struct { - cnt int -} - -func (t *myTap) handle(ctx context.Context, info *tap.Info) (context.Context, error) { - if info != nil { - if info.FullMethodName == "/grpc.testing.TestService/EmptyCall" { - t.cnt++ - } else if info.FullMethodName == "/grpc.testing.TestService/UnaryCall" { - return nil, fmt.Errorf("tap error") - } - } - return ctx, nil -} - -func testTap(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - ttap := &myTap{} - te.tapHandle = ttap.handle - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - ) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - if ttap.cnt != 1 { - t.Fatalf("Get the count in ttap %d, want 1", ttap.cnt) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 31) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: 45, - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, %s", err, codes.Unavailable) - } -} - -func healthCheck(d time.Duration, cc *grpc.ClientConn, serviceName string) (*healthpb.HealthCheckResponse, error) { - ctx, cancel := context.WithTimeout(context.Background(), d) - defer cancel() - hc := healthgrpc.NewHealthClient(cc) - req := &healthpb.HealthCheckRequest{ - Service: serviceName, - } - return hc.Check(ctx, req) -} - -func TestHealthCheckOnSuccess(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckOnSuccess(t, e) - } -} - -func testHealthCheckOnSuccess(t *testing.T, e env) { - te := newTest(t, e) - hs := health.NewServer() - hs.SetServingStatus("grpc.health.v1.Health", 1) - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, ", err) - } -} - -func TestHealthCheckOnFailure(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckOnFailure(t, e) - } -} - -func testHealthCheckOnFailure(t *testing.T, e env) { - defer leakcheck.Check(t) - te := newTest(t, e) - te.declareLogNoise( - "Failed to dial ", - "grpc: the client connection is closing; please retry", - ) - hs := health.NewServer() - hs.SetServingStatus("grpc.health.v1.HealthCheck", 1) - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - wantErr := status.Error(codes.DeadlineExceeded, "context deadline exceeded") - if _, err := healthCheck(0*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.DeadlineExceeded) - } - awaitNewConnLogOutput() -} - -func TestHealthCheckOff(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testHealthCheckOff(t, e) - } -} - -func testHealthCheckOff(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - want := status.Error(codes.Unimplemented, "unknown service grpc.health.v1.Health") - if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want) - } -} - -func TestUnknownHandler(t *testing.T) { - defer leakcheck.Check(t) - // An example unknownHandler that returns a different code and a different method, making sure that we do not - // expose what methods are implemented to a client that is not authenticated. - unknownHandler := func(srv interface{}, stream grpc.ServerStream) error { - return status.Error(codes.Unauthenticated, "user unauthenticated") - } - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testUnknownHandler(t, e, unknownHandler) - } -} - -func testUnknownHandler(t *testing.T, e env, unknownHandler grpc.StreamHandler) { - te := newTest(t, e) - te.unknownHandler = unknownHandler - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - want := status.Error(codes.Unauthenticated, "user unauthenticated") - if _, err := healthCheck(1*time.Second, te.clientConn(), ""); !reflect.DeepEqual(err, want) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, %v", err, want) - } -} - -func TestHealthCheckServingStatus(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testHealthCheckServingStatus(t, e) - } -} - -func testHealthCheckServingStatus(t *testing.T, e env) { - te := newTest(t, e) - hs := health.NewServer() - te.healthServer = hs - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - out, err := healthCheck(1*time.Second, cc, "") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, ", err) - } - if out.Status != healthpb.HealthCheckResponse_SERVING { - t.Fatalf("Got the serving status %v, want SERVING", out.Status) - } - wantErr := status.Error(codes.NotFound, "unknown service") - if _, err := healthCheck(1*time.Second, cc, "grpc.health.v1.Health"); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("Health/Check(_, _) = _, %v, want _, error code %s", err, codes.NotFound) - } - hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_SERVING) - out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, ", err) - } - if out.Status != healthpb.HealthCheckResponse_SERVING { - t.Fatalf("Got the serving status %v, want SERVING", out.Status) - } - hs.SetServingStatus("grpc.health.v1.Health", healthpb.HealthCheckResponse_NOT_SERVING) - out, err = healthCheck(1*time.Second, cc, "grpc.health.v1.Health") - if err != nil { - t.Fatalf("Health/Check(_, _) = _, %v, want _, ", err) - } - if out.Status != healthpb.HealthCheckResponse_NOT_SERVING { - t.Fatalf("Got the serving status %v, want NOT_SERVING", out.Status) - } - -} - -func TestEmptyUnaryWithUserAgent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testEmptyUnaryWithUserAgent(t, e) - } -} - -func testEmptyUnaryWithUserAgent(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - var header metadata.MD - reply, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Header(&header)) - if err != nil || !proto.Equal(&testpb.Empty{}, reply) { - t.Fatalf("TestService/EmptyCall(_, _) = %v, %v, want %v, ", reply, err, &testpb.Empty{}) - } - if v, ok := header["ua"]; !ok || !strings.HasPrefix(v[0], testAppUA) { - t.Fatalf("header[\"ua\"] = %q, %t, want string with prefix %q, true", v, ok, testAppUA) - } - - te.srv.Stop() -} - -func TestFailedEmptyUnary(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // This test covers status details, but - // Grpc-Status-Details-Bin is not support in handler_server. - continue - } - testFailedEmptyUnary(t, e) - } -} - -func testFailedEmptyUnary(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = failAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - wantErr := detailedError - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %v", err, wantErr) - } -} - -func TestLargeUnary(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testLargeUnary(t, e) - } -} - -func testLargeUnary(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 271828 - const respSize = 314159 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - reply, err := tc.UnaryCall(context.Background(), req) - if err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, ", err) - } - pt := reply.GetPayload().GetType() - ps := len(reply.GetPayload().GetBody()) - if pt != testpb.PayloadType_COMPRESSABLE || ps != respSize { - t.Fatalf("Got the reply with type %d len %d; want %d, %d", pt, ps, testpb.PayloadType_COMPRESSABLE, respSize) - } -} - -// Test backward-compatibility API for setting msg size limit. -func TestExceedMsgLimit(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testExceedMsgLimit(t, e) - } -} - -func testExceedMsgLimit(t *testing.T, e env) { - te := newTest(t, e) - te.maxMsgSize = newInt(1024) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - argSize := int32(*te.maxMsgSize + 1) - const smallSize = 1 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - - // Test on server side for unary RPC. - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: smallSize, - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - // Test on client side for unary RPC. - req.ResponseSize = int32(*te.maxMsgSize) + 1 - req.Payload = smallPayload - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test on server side for streaming RPC. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: 1, - }, - } - - spayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(*te.maxMsgSize+1)) - if err != nil { - t.Fatal(err) - } - - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: spayload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test on client side for streaming RPC. - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam[0].Size = int32(*te.maxMsgSize) + 1 - sreq.Payload = smallPayload - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - -} - -func TestPeerClientSide(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerClientSide(t, e) - } -} - -func testPeerClientSide(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - peer := new(peer.Peer) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Peer(peer), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - pa := peer.Addr.String() - if e.network == "unix" { - if pa != te.srvAddr { - t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr) - } - return - } - _, pp, err := net.SplitHostPort(pa) - if err != nil { - t.Fatalf("Failed to parse address from peer.") - } - _, sp, err := net.SplitHostPort(te.srvAddr) - if err != nil { - t.Fatalf("Failed to parse address of test server.") - } - if pp != sp { - t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp) - } -} - -// TestPeerNegative tests that if call fails setting peer -// doesn't cause a segmentation fault. -// issue#1141 https://github.com/grpc/grpc-go/issues/1141 -func TestPeerNegative(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerNegative(t, e) - } -} - -func testPeerNegative(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - peer := new(peer.Peer) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - tc.EmptyCall(ctx, &testpb.Empty{}, grpc.Peer(peer)) -} - -func TestPeerFailedRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPeerFailedRPC(t, e) - } -} - -func testPeerFailedRPC(t *testing.T, e env) { - te := newTest(t, e) - te.maxServerReceiveMsgSize = newInt(1 * 1024) - te.startServer(&testServer{security: e.security}) - - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // first make a successful request to the server - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, ", err) - } - - // make a second request that will be rejected by the server - const largeSize = 5 * 1024 - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - Payload: largePayload, - } - - peer := new(peer.Peer) - if _, err := tc.UnaryCall(context.Background(), req, grpc.Peer(peer)); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } else { - pa := peer.Addr.String() - if e.network == "unix" { - if pa != te.srvAddr { - t.Fatalf("peer.Addr = %v, want %v", pa, te.srvAddr) - } - return - } - _, pp, err := net.SplitHostPort(pa) - if err != nil { - t.Fatalf("Failed to parse address from peer.") - } - _, sp, err := net.SplitHostPort(te.srvAddr) - if err != nil { - t.Fatalf("Failed to parse address of test server.") - } - if pp != sp { - t.Fatalf("peer.Addr = localhost:%v, want localhost:%v", pp, sp) - } - } -} - -func TestMetadataUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMetadataUnaryRPC(t, e) - } -} - -func testMetadataUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - var header, trailer metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.Trailer(&trailer)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, ", ctx, err) - } - // Ignore optional response headers that Servers may set: - if header != nil { - delete(header, "trailer") // RFC 2616 says server SHOULD (but optional) declare trailers - delete(header, "date") // the Date header is also optional - delete(header, "user-agent") - delete(header, "content-type") - } - if !reflect.DeepEqual(header, testMetadata) { - t.Fatalf("Received header metadata %v, want %v", header, testMetadata) - } - if !reflect.DeepEqual(trailer, testTrailerMetadata) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, testTrailerMetadata) - } -} - -func TestMultipleSetTrailerUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMultipleSetTrailerUnaryRPC(t, e) - } -} - -func testMultipleSetTrailerUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - var trailer metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Trailer(&trailer), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, ", ctx, err) - } - expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2) - if !reflect.DeepEqual(trailer, expectedTrailer) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer) - } -} - -func TestMultipleSetTrailerStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMultipleSetTrailerStreamingRPC(t, e) - } -} - -func testMultipleSetTrailerStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, multipleSetTrailer: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - trailer := stream.Trailer() - expectedTrailer := metadata.Join(testTrailerMetadata, testTrailerMetadata2) - if !reflect.DeepEqual(trailer, expectedTrailer) { - t.Fatalf("Received trailer metadata %v, want %v", trailer, expectedTrailer) - } -} - -func TestSetAndSendHeaderUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testSetAndSendHeaderUnaryRPC(t, e) - } -} - -// To test header metadata is sent on SendHeader(). -func testSetAndSendHeaderUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setAndSendHeader: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, ", ctx, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderUnaryRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderUnaryRPC(t, e) - } -} - -// To test header metadata is sent when sending response. -func testMultipleSetHeaderUnaryRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err != nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, ", ctx, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderUnaryRPCError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderUnaryRPCError(t, e) - } -} - -// To test header metadata is sent when sending status. -func testMultipleSetHeaderUnaryRPCError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = -1 // Invalid respSize to make RPC fail. - ) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - var header metadata.MD - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - if _, err := tc.UnaryCall(ctx, req, grpc.Header(&header), grpc.FailFast(false)); err == nil { - t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, ", ctx, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestSetAndSendHeaderStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testSetAndSendHeaderStreamingRPC(t, e) - } -} - -// To test header metadata is sent on SendHeader(). -func testSetAndSendHeaderStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setAndSendHeader: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, ", stream, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } -} - -func TestMultipleSetHeaderStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderStreamingRPC(t, e) - } -} - -// To test header metadata is sent when sending response. -func testMultipleSetHeaderStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = 1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{ - {Size: respSize}, - }, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the FullDuplexCall: %v", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, ", stream, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } - -} - -func TestMultipleSetHeaderStreamingRPCError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testMultipleSetHeaderStreamingRPCError(t, e) - } -} - -// To test header metadata is sent when sending status. -func testMultipleSetHeaderStreamingRPCError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, setHeaderOnly: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const ( - argSize = 1 - respSize = -1 - ) - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{ - {Size: respSize}, - }, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - if _, err := stream.Recv(); err == nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - - header, err := stream.Header() - if err != nil { - t.Fatalf("%v.Header() = _, %v, want _, ", stream, err) - } - delete(header, "user-agent") - delete(header, "content-type") - expectedHeader := metadata.Join(testMetadata, testMetadata2) - if !reflect.DeepEqual(header, expectedHeader) { - t.Fatalf("Received header metadata %v, want %v", header, expectedHeader) - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } -} - -// TestMalformedHTTP2Metedata verfies the returned error when the client -// sends an illegal metadata. -func TestMalformedHTTP2Metadata(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // Failed with "server stops accepting new RPCs". - // Server stops accepting new RPCs when the client sends an illegal http2 header. - continue - } - testMalformedHTTP2Metadata(t, e) - } -} - -func testMalformedHTTP2Metadata(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 2718) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: 314, - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), malformedHTTP2Metadata) - if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.Internal { - t.Fatalf("TestService.UnaryCall(%v, _) = _, %v; want _, %s", ctx, err, codes.Internal) - } -} - -func TestRetry(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - // Fails with RST_STREAM / FLOW_CONTROL_ERROR - continue - } - testRetry(t, e) - } -} - -// This test make sure RPCs are retried times when they receive a RST_STREAM -// with the REFUSED_STREAM error code, which the InTapHandle provokes. -func testRetry(t *testing.T, e env) { - te := newTest(t, e) - attempts := 0 - successAttempt := 2 - te.tapHandle = func(ctx context.Context, _ *tap.Info) (context.Context, error) { - attempts++ - if attempts < successAttempt { - return nil, errors.New("not now") - } - return ctx, nil - } - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tsc := testpb.NewTestServiceClient(cc) - testCases := []struct { - successAttempt int - failFast bool - errCode codes.Code - }{{ - successAttempt: 1, - }, { - successAttempt: 2, - }, { - successAttempt: 3, - errCode: codes.Unavailable, - }, { - successAttempt: 1, - failFast: true, - }, { - successAttempt: 2, - failFast: true, - errCode: codes.Unavailable, // We won't retry on fail fast. - }} - for _, tc := range testCases { - attempts = 0 - successAttempt = tc.successAttempt - - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - _, err := tsc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(tc.failFast)) - cancel() - if status.Code(err) != tc.errCode { - t.Errorf("%+v: tsc.EmptyCall(_, _) = _, %v, want _, Code=%v", tc, err, tc.errCode) - } - } -} - -func TestCancel(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCancel(t, e) - } -} - -func testCancel(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("grpc: the client connection is closing; please retry") - te.startServer(&testServer{security: e.security, unaryCallSleepTime: time.Second}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - ctx, cancel := context.WithCancel(context.Background()) - time.AfterFunc(1*time.Millisecond, cancel) - if r, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.Canceled { - t.Fatalf("TestService/UnaryCall(_, _) = %v, %v; want _, error code: %s", r, err, codes.Canceled) - } - awaitNewConnLogOutput() -} - -func TestCancelNoIO(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCancelNoIO(t, e) - } -} - -func testCancelNoIO(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("http2Client.notifyError got notified that the client transport was broken") - te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - // Start one blocked RPC for which we'll never send streaming - // input. This will consume the 1 maximum concurrent streams, - // causing future RPCs to hang. - ctx, cancelFirst := context.WithCancel(context.Background()) - _, err := tc.StreamingInputCall(ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, ", tc, err) - } - - // Loop until the ClientConn receives the initial settings - // frame from the server, notifying it about the maximum - // concurrent streams. We know when it's received it because - // an RPC will fail with codes.DeadlineExceeded instead of - // succeeding. - // TODO(bradfitz): add internal test hook for this (Issue 534) - for { - ctx, cancelSecond := context.WithTimeout(context.Background(), 50*time.Millisecond) - _, err := tc.StreamingInputCall(ctx) - cancelSecond() - if err == nil { - continue - } - if status.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } - // If there are any RPCs in flight before the client receives - // the max streams setting, let them be expired. - // TODO(bradfitz): add internal test hook for this (Issue 534) - time.Sleep(50 * time.Millisecond) - - go func() { - time.Sleep(50 * time.Millisecond) - cancelFirst() - }() - - // This should be blocked until the 1st is canceled, then succeed. - ctx, cancelThird := context.WithTimeout(context.Background(), 500*time.Millisecond) - if _, err := tc.StreamingInputCall(ctx); err != nil { - t.Errorf("%v.StreamingInputCall(_) = _, %v, want _, ", tc, err) - } - cancelThird() -} - -// The following tests the gRPC streaming RPC implementations. -// TODO(zhaoq): Have better coverage on error cases. -var ( - reqSizes = []int{27182, 8, 1828, 45904} - respSizes = []int{31415, 9, 2653, 58979} -) - -func TestNoService(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testNoService(t, e) - } -} - -func testNoService(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(nil) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - stream, err := tc.FullDuplexCall(te.ctx, grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if _, err := stream.Recv(); status.Code(err) != codes.Unimplemented { - t.Fatalf("stream.Recv() = _, %v, want _, error code %s", err, codes.Unimplemented) - } -} - -func TestPingPong(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPingPong(t, e) - } -} - -func testPingPong(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - var index int - for index < len(reqSizes) { - respParam := []*testpb.ResponseParameters{ - { - Size: int32(respSizes[index]), - }, - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index])) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - reply, err := stream.Recv() - if err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - pt := reply.GetPayload().GetType() - if pt != testpb.PayloadType_COMPRESSABLE { - t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() got %v, want %v", stream, err, nil) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v failed to complele the ping pong test: %v", stream, err) - } -} - -func TestMetadataStreamingRPC(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testMetadataStreamingRPC(t, e) - } -} - -func testMetadataStreamingRPC(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx := metadata.NewOutgoingContext(te.ctx, testMetadata) - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - go func() { - headerMD, err := stream.Header() - if e.security == "tls" { - delete(headerMD, "transport_security_type") - } - delete(headerMD, "trailer") // ignore if present - delete(headerMD, "user-agent") - delete(headerMD, "content-type") - if err != nil || !reflect.DeepEqual(testMetadata, headerMD) { - t.Errorf("#1 %v.Header() = %v, %v, want %v, ", stream, headerMD, err, testMetadata) - } - // test the cached value. - headerMD, err = stream.Header() - delete(headerMD, "trailer") // ignore if present - delete(headerMD, "user-agent") - delete(headerMD, "content-type") - if err != nil || !reflect.DeepEqual(testMetadata, headerMD) { - t.Errorf("#2 %v.Header() = %v, %v, want %v, ", stream, headerMD, err, testMetadata) - } - err = func() error { - for index := 0; index < len(reqSizes); index++ { - respParam := []*testpb.ResponseParameters{ - { - Size: int32(respSizes[index]), - }, - } - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(reqSizes[index])) - if err != nil { - return err - } - - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(req); err != nil { - return fmt.Errorf("%v.Send(%v) = %v, want ", stream, req, err) - } - } - return nil - }() - // Tell the server we're done sending args. - stream.CloseSend() - if err != nil { - t.Error(err) - } - }() - for { - if _, err := stream.Recv(); err != nil { - break - } - } - trailerMD := stream.Trailer() - if !reflect.DeepEqual(testTrailerMetadata, trailerMD) { - t.Fatalf("%v.Trailer() = %v, want %v", stream, trailerMD, testTrailerMetadata) - } -} - -func TestServerStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServerStreaming(t, e) - } -} - -func testServerStreaming(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: int32(s), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - } - stream, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want ", tc, err) - } - var rpcStatus error - var respCnt int - var index int - for { - reply, err := stream.Recv() - if err != nil { - rpcStatus = err - break - } - pt := reply.GetPayload().GetType() - if pt != testpb.PayloadType_COMPRESSABLE { - t.Fatalf("Got the reply of type %d, want %d", pt, testpb.PayloadType_COMPRESSABLE) - } - size := len(reply.GetPayload().GetBody()) - if size != int(respSizes[index]) { - t.Fatalf("Got reply body of length %d, want %d", size, respSizes[index]) - } - index++ - respCnt++ - } - if rpcStatus != io.EOF { - t.Fatalf("Failed to finish the server streaming rpc: %v, want ", rpcStatus) - } - if respCnt != len(respSizes) { - t.Fatalf("Got %d reply, want %d", len(respSizes), respCnt) - } -} - -func TestFailedServerStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testFailedServerStreaming(t, e) - } -} - -func testFailedServerStreaming(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = failAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - respParam := make([]*testpb.ResponseParameters, len(respSizes)) - for i, s := range respSizes { - respParam[i] = &testpb.ResponseParameters{ - Size: int32(s), - } - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - } - ctx := metadata.NewOutgoingContext(te.ctx, testMetadata) - stream, err := tc.StreamingOutputCall(ctx, req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want ", tc, err) - } - wantErr := status.Error(codes.DataLoss, "error for testing: "+failAppUA) - if _, err := stream.Recv(); !reflect.DeepEqual(err, wantErr) { - t.Fatalf("%v.Recv() = _, %v, want _, %v", stream, err, wantErr) - } -} - -// concurrentSendServer is a TestServiceServer whose -// StreamingOutputCall makes ten serial Send calls, sending payloads -// "0".."9", inclusive. TestServerStreamingConcurrent verifies they -// were received in the correct order, and that there were no races. -// -// All other TestServiceServer methods crash if called. -type concurrentSendServer struct { - testpb.TestServiceServer -} - -func (s concurrentSendServer) StreamingOutputCall(args *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { - for i := 0; i < 10; i++ { - stream.Send(&testpb.StreamingOutputCallResponse{ - Payload: &testpb.Payload{ - Body: []byte{'0' + uint8(i)}, - }, - }) - } - return nil -} - -// Tests doing a bunch of concurrent streaming output calls. -func TestServerStreamingConcurrent(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServerStreamingConcurrent(t, e) - } -} - -func testServerStreamingConcurrent(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(concurrentSendServer{}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - doStreamingCall := func() { - req := &testpb.StreamingOutputCallRequest{} - stream, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Errorf("%v.StreamingOutputCall(_) = _, %v, want ", tc, err) - return - } - var ngot int - var buf bytes.Buffer - for { - reply, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - ngot++ - if buf.Len() > 0 { - buf.WriteByte(',') - } - buf.Write(reply.GetPayload().GetBody()) - } - if want := 10; ngot != want { - t.Errorf("Got %d replies, want %d", ngot, want) - } - if got, want := buf.String(), "0,1,2,3,4,5,6,7,8,9"; got != want { - t.Errorf("Got replies %q; want %q", got, want) - } - } - - var wg sync.WaitGroup - for i := 0; i < 20; i++ { - wg.Add(1) - go func() { - defer wg.Done() - doStreamingCall() - }() - } - wg.Wait() - -} - -func generatePayloadSizes() [][]int { - reqSizes := [][]int{ - {27182, 8, 1828, 45904}, - } - - num8KPayloads := 1024 - eightKPayloads := []int{} - for i := 0; i < num8KPayloads; i++ { - eightKPayloads = append(eightKPayloads, (1 << 13)) - } - reqSizes = append(reqSizes, eightKPayloads) - - num2MPayloads := 8 - twoMPayloads := []int{} - for i := 0; i < num2MPayloads; i++ { - twoMPayloads = append(twoMPayloads, (1 << 21)) - } - reqSizes = append(reqSizes, twoMPayloads) - - return reqSizes -} - -func TestClientStreaming(t *testing.T) { - defer leakcheck.Check(t) - for _, s := range generatePayloadSizes() { - for _, e := range listTestEnv() { - testClientStreaming(t, e, s) - } - } -} - -func testClientStreaming(t *testing.T, e env, sizes []int) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - ctx, cancel := context.WithTimeout(te.ctx, time.Second*30) - defer cancel() - stream, err := tc.StreamingInputCall(ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want ", tc, err) - } - - var sum int - for _, s := range sizes { - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(s)) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingInputCallRequest{ - Payload: payload, - } - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(_) = %v, want ", stream, err) - } - sum += s - } - reply, err := stream.CloseAndRecv() - if err != nil { - t.Fatalf("%v.CloseAndRecv() got error %v, want %v", stream, err, nil) - } - if reply.GetAggregatedPayloadSize() != int32(sum) { - t.Fatalf("%v.CloseAndRecv().GetAggregatePayloadSize() = %v; want %v", stream, reply.GetAggregatedPayloadSize(), sum) - } -} - -func TestClientStreamingError(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.name == "handler-tls" { - continue - } - testClientStreamingError(t, e) - } -} - -func testClientStreamingError(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, earlyFail: true}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - stream, err := tc.StreamingInputCall(te.ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want ", tc, err) - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1) - if err != nil { - t.Fatal(err) - } - - req := &testpb.StreamingInputCallRequest{ - Payload: payload, - } - // The 1st request should go through. - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - for { - if err := stream.Send(req); err != io.EOF { - continue - } - if _, err := stream.CloseAndRecv(); status.Code(err) != codes.NotFound { - t.Fatalf("%v.CloseAndRecv() = %v, want error %s", stream, err, codes.NotFound) - } - break - } -} - -func TestExceedMaxStreamsLimit(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testExceedMaxStreamsLimit(t, e) - } -} - -func testExceedMaxStreamsLimit(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise( - "http2Client.notifyError got notified that the client transport was broken", - "Conn.resetTransport failed to create client transport", - "grpc: the connection is closing", - ) - te.maxStream = 1 // Only allows 1 live stream per server transport. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - _, err := tc.StreamingInputCall(te.ctx) - if err != nil { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, ", tc, err) - } - // Loop until receiving the new max stream setting from the server. - for { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - _, err := tc.StreamingInputCall(ctx) - if err == nil { - time.Sleep(50 * time.Millisecond) - continue - } - if status.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, %s", tc, err, codes.DeadlineExceeded) - } -} - -func TestStreamsQuotaRecovery(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testStreamsQuotaRecovery(t, e) - } -} - -func testStreamsQuotaRecovery(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise( - "http2Client.notifyError got notified that the client transport was broken", - "Conn.resetTransport failed to create client transport", - "grpc: the connection is closing", - ) - te.maxStream = 1 // Allows 1 live stream. - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - if _, err := tc.StreamingInputCall(ctx); err != nil { - t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, ", err) - } - // Loop until the new max stream setting is effective. - for { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - _, err := tc.StreamingInputCall(ctx) - cancel() - if err == nil { - time.Sleep(5 * time.Millisecond) - continue - } - if status.Code(err) == codes.DeadlineExceeded { - break - } - t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 314) - if err != nil { - t.Error(err) - return - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: 1592, - Payload: payload, - } - // No rpc should go through due to the max streams limit. - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - defer cancel() - if _, err := tc.UnaryCall(ctx, req, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Errorf("tc.UnaryCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - }() - } - wg.Wait() - - cancel() - // A new stream should be allowed after canceling the first one. - ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if _, err := tc.StreamingInputCall(ctx); err != nil { - t.Fatalf("tc.StreamingInputCall(_) = _, %v, want _, %v", err, nil) - } -} - -func TestCompressServerHasNoSupport(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCompressServerHasNoSupport(t, e) - } -} - -func testCompressServerHasNoSupport(t *testing.T, e env) { - te := newTest(t, e) - te.serverCompression = false - te.clientCompression = false - te.clientNopCompression = true - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - const argSize = 271828 - const respSize = 314159 - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.Unimplemented { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code %s", err, codes.Unimplemented) - } - // Streaming RPC - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.Unimplemented { - t.Fatalf("%v.Recv() = %v, want error code %s", stream, err, codes.Unimplemented) - } -} - -func TestCompressOK(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCompressOK(t, e) - } -} - -func testCompressOK(t *testing.T, e env) { - te := newTest(t, e) - te.serverCompression = true - te.clientCompression = true - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // Unary call - const argSize = 271828 - const respSize = 314159 - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something")) - if _, err := tc.UnaryCall(ctx, req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, ", err) - } - // Streaming RPC - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: 31415, - }, - } - payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415)) - if err != nil { - t.Fatal(err) - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - stream.CloseSend() - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v.Recv() = %v, want io.EOF", stream, err) - } -} - -func TestIdentityEncoding(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testIdentityEncoding(t, e) - } -} - -func testIdentityEncoding(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // Unary call - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 5) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: 10, - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something")) - if _, err := tc.UnaryCall(ctx, req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, ", err) - } - // Streaming RPC - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := tc.FullDuplexCall(ctx, grpc.UseCompressor("identity")) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415)) - if err != nil { - t.Fatal(err) - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: []*testpb.ResponseParameters{{Size: 10}}, - Payload: payload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - stream.CloseSend() - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("%v.Recv() = %v, want io.EOF", stream, err) - } -} - -func TestUnaryClientInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testUnaryClientInterceptor(t, e) - } -} - -func failOkayRPC(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - err := invoker(ctx, method, req, reply, cc, opts...) - if err == nil { - return status.Error(codes.NotFound, "") - } - return err -} - -func testUnaryClientInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.unaryClientInt = failOkayRPC - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.NotFound { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.NotFound) - } -} - -func TestStreamClientInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testStreamClientInterceptor(t, e) - } -} - -func failOkayStream(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - s, err := streamer(ctx, desc, cc, method, opts...) - if err == nil { - return nil, status.Error(codes.NotFound, "") - } - return s, nil -} - -func testStreamClientInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.streamClientInt = failOkayStream - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: int32(1), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - if _, err := tc.StreamingOutputCall(context.Background(), req); status.Code(err) != codes.NotFound { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, error code %s", tc, err, codes.NotFound) - } -} - -func TestUnaryServerInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testUnaryServerInterceptor(t, e) - } -} - -func errInjector(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - return nil, status.Error(codes.PermissionDenied, "") -} - -func testUnaryServerInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.unaryServerInt = errInjector - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.PermissionDenied { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied) - } -} - -func TestStreamServerInterceptor(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - // TODO(bradfitz): Temporarily skip this env due to #619. - if e.name == "handler-tls" { - continue - } - testStreamServerInterceptor(t, e) - } -} - -func fullDuplexOnly(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - if info.FullMethod == "/grpc.testing.TestService/FullDuplexCall" { - return handler(srv, ss) - } - // Reject the other methods. - return status.Error(codes.PermissionDenied, "") -} - -func testStreamServerInterceptor(t *testing.T, e env) { - te := newTest(t, e) - te.streamServerInt = fullDuplexOnly - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: int32(1), - }, - } - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(1)) - if err != nil { - t.Fatal(err) - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - s1, err := tc.StreamingOutputCall(context.Background(), req) - if err != nil { - t.Fatalf("%v.StreamingOutputCall(_) = _, %v, want _, ", tc, err) - } - if _, err := s1.Recv(); status.Code(err) != codes.PermissionDenied { - t.Fatalf("%v.StreamingInputCall(_) = _, %v, want _, error code %s", tc, err, codes.PermissionDenied) - } - s2, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := s2.Send(req); err != nil { - t.Fatalf("%v.Send(_) = %v, want ", s2, err) - } - if _, err := s2.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, ", s2, err) - } -} - -// funcServer implements methods of TestServiceServer using funcs, -// similar to an http.HandlerFunc. -// Any unimplemented method will crash. Tests implement the method(s) -// they need. -type funcServer struct { - testpb.TestServiceServer - unaryCall func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) - streamingInputCall func(stream testpb.TestService_StreamingInputCallServer) error - fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error -} - -func (s *funcServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - return s.unaryCall(ctx, in) -} - -func (s *funcServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { - return s.streamingInputCall(stream) -} - -func (s *funcServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return s.fullDuplexCall(stream) -} - -func TestClientRequestBodyErrorUnexpectedEOF(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorUnexpectedEOF(t, e) - } -} - -func testClientRequestBodyErrorUnexpectedEOF(t *testing.T, e env) { - te := newTest(t, e) - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - errUnexpectedCall := errors.New("unexpected call func server method") - t.Error(errUnexpectedCall) - return nil, errUnexpectedCall - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // Say we have 5 bytes coming, but set END_STREAM flag: - st.writeData(1, true, []byte{0, 0, 0, 0, 5}) - st.wantAnyFrame() // wait for server to crash (it used to crash) - }) -} - -func TestClientRequestBodyErrorCloseAfterLength(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCloseAfterLength(t, e) - } -} - -func testClientRequestBodyErrorCloseAfterLength(t *testing.T, e env) { - te := newTest(t, e) - te.declareLogNoise("Server.processUnaryRPC failed to write status") - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - errUnexpectedCall := errors.New("unexpected call func server method") - t.Error(errUnexpectedCall) - return nil, errUnexpectedCall - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // say we're sending 5 bytes, but then close the connection instead. - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - st.cc.Close() - }) -} - -func TestClientRequestBodyErrorCancel(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCancel(t, e) - } -} - -func testClientRequestBodyErrorCancel(t *testing.T, e env) { - te := newTest(t, e) - gotCall := make(chan bool, 1) - ts := &funcServer{unaryCall: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - gotCall <- true - return new(testpb.SimpleResponse), nil - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/UnaryCall") - // Say we have 5 bytes coming, but cancel it instead. - st.writeRSTStream(1, http2.ErrCodeCancel) - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - - // Verify we didn't a call yet. - select { - case <-gotCall: - t.Fatal("unexpected call") - default: - } - - // And now send an uncanceled (but still invalid), just to get a response. - st.writeHeadersGRPC(3, "/grpc.testing.TestService/UnaryCall") - st.writeData(3, true, []byte{0, 0, 0, 0, 0}) - <-gotCall - st.wantAnyFrame() - }) -} - -func TestClientRequestBodyErrorCancelStreamingInput(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testClientRequestBodyErrorCancelStreamingInput(t, e) - } -} - -func testClientRequestBodyErrorCancelStreamingInput(t *testing.T, e env) { - te := newTest(t, e) - recvErr := make(chan error, 1) - ts := &funcServer{streamingInputCall: func(stream testpb.TestService_StreamingInputCallServer) error { - _, err := stream.Recv() - recvErr <- err - return nil - }} - te.startServer(ts) - defer te.tearDown() - te.withServerTester(func(st *serverTester) { - st.writeHeadersGRPC(1, "/grpc.testing.TestService/StreamingInputCall") - // Say we have 5 bytes coming, but cancel it instead. - st.writeData(1, false, []byte{0, 0, 0, 0, 5}) - st.writeRSTStream(1, http2.ErrCodeCancel) - - var got error - select { - case got = <-recvErr: - case <-time.After(3 * time.Second): - t.Fatal("timeout waiting for error") - } - if grpc.Code(got) != codes.Canceled { - t.Errorf("error = %#v; want error code %s", got, codes.Canceled) - } - }) -} - -func TestClientResourceExhaustedCancelFullDuplex(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.httpHandler { - // httpHandler write won't be blocked on flow control window. - continue - } - testClientResourceExhaustedCancelFullDuplex(t, e) - } -} - -func testClientResourceExhaustedCancelFullDuplex(t *testing.T, e env) { - te := newTest(t, e) - recvErr := make(chan error, 1) - ts := &funcServer{fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - defer close(recvErr) - _, err := stream.Recv() - if err != nil { - return status.Errorf(codes.Internal, "stream.Recv() got error: %v, want ", err) - } - // create a payload that's larger than the default flow control window. - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 10) - if err != nil { - return err - } - resp := &testpb.StreamingOutputCallResponse{ - Payload: payload, - } - ce := make(chan error) - go func() { - var err error - for { - if err = stream.Send(resp); err != nil { - break - } - } - ce <- err - }() - select { - case err = <-ce: - case <-time.After(10 * time.Second): - err = errors.New("10s timeout reached") - } - recvErr <- err - return err - }} - te.startServer(ts) - defer te.tearDown() - // set a low limit on receive message size to error with Resource Exhausted on - // client side when server send a large message. - te.maxClientReceiveMsgSize = newInt(10) - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - req := &testpb.StreamingOutputCallRequest{} - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - if _, err := stream.Recv(); status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - err = <-recvErr - if status.Code(err) != codes.Canceled { - t.Fatalf("server got error %v, want error code: %s", err, codes.Canceled) - } -} - -type clientTimeoutCreds struct { - timeoutReturned bool -} - -func (c *clientTimeoutCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if !c.timeoutReturned { - c.timeoutReturned = true - return nil, nil, context.DeadlineExceeded - } - return rawConn, nil, nil -} -func (c *clientTimeoutCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *clientTimeoutCreds) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *clientTimeoutCreds) Clone() credentials.TransportCredentials { - return nil -} -func (c *clientTimeoutCreds) OverrideServerName(s string) error { - return nil -} - -func TestNonFailFastRPCSucceedOnTimeoutCreds(t *testing.T) { - te := newTest(t, env{name: "timeout-cred", network: "tcp", security: "clientTimeoutCreds", balancer: "v1"}) - te.userAgent = testAppUA - te.startServer(&testServer{security: te.e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // This unary call should succeed, because ClientHandshake will succeed for the second time. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - te.t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want ", err) - } -} - -type serverDispatchCred struct { - rawConnCh chan net.Conn -} - -func newServerDispatchCred() *serverDispatchCred { - return &serverDispatchCred{ - rawConnCh: make(chan net.Conn, 1), - } -} -func (c *serverDispatchCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *serverDispatchCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - select { - case c.rawConnCh <- rawConn: - default: - } - return nil, nil, credentials.ErrConnDispatched -} -func (c *serverDispatchCred) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *serverDispatchCred) Clone() credentials.TransportCredentials { - return nil -} -func (c *serverDispatchCred) OverrideServerName(s string) error { - return nil -} -func (c *serverDispatchCred) getRawConn() net.Conn { - return <-c.rawConnCh -} - -func TestServerCredsDispatch(t *testing.T) { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - cred := newServerDispatchCred() - s := grpc.NewServer(grpc.Creds(cred)) - go s.Serve(lis) - defer s.Stop() - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(cred)) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - defer cc.Close() - - rawConn := cred.getRawConn() - // Give grpc a chance to see the error and potentially close the connection. - // And check that connection is not closed after that. - time.Sleep(100 * time.Millisecond) - // Check rawConn is not closed. - if n, err := rawConn.Write([]byte{0}); n <= 0 || err != nil { - t.Errorf("Read() = %v, %v; want n>0, ", n, err) - } -} - -type authorityCheckCreds struct { - got string -} - -func (c *authorityCheckCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *authorityCheckCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - c.got = authority - return rawConn, nil, nil -} -func (c *authorityCheckCreds) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *authorityCheckCreds) Clone() credentials.TransportCredentials { - return c -} -func (c *authorityCheckCreds) OverrideServerName(s string) error { - return nil -} - -// This test makes sure that the authority client handshake gets is the endpoint -// in dial target, not the resolved ip address. -func TestCredsHandshakeAuthority(t *testing.T) { - const testAuthority = "test.auth.ori.ty" - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - cred := &authorityCheckCreds{} - s := grpc.NewServer() - go s.Serve(lis) - defer s.Stop() - - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - cc, err := grpc.Dial(r.Scheme()+":///"+testAuthority, grpc.WithTransportCredentials(cred)) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - defer cc.Close() - r.NewAddress([]resolver.Address{{Addr: lis.Addr().String()}}) - - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - for { - s := cc.GetState() - if s == connectivity.Ready { - break - } - if !cc.WaitForStateChange(ctx, s) { - // ctx got timeout or canceled. - t.Fatalf("ClientConn is not ready after 100 ms") - } - } - - if cred.got != testAuthority { - t.Fatalf("client creds got authority: %q, want: %q", cred.got, testAuthority) - } -} - -type clientFailCreds struct { - got string -} - -func (c *clientFailCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c *clientFailCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return nil, nil, fmt.Errorf("client handshake fails with fatal error") -} -func (c *clientFailCreds) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c *clientFailCreds) Clone() credentials.TransportCredentials { - return c -} -func (c *clientFailCreds) OverrideServerName(s string) error { - return nil -} - -// This test makes sure that failfast RPCs fail if client handshake fails with -// fatal errors. -func TestFailfastRPCFailOnFatalHandshakeError(t *testing.T) { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - defer lis.Close() - - cc, err := grpc.Dial("passthrough:///"+lis.Addr().String(), grpc.WithTransportCredentials(&clientFailCreds{})) - if err != nil { - t.Fatalf("grpc.Dial(_) = %v", err) - } - defer cc.Close() - - tc := testpb.NewTestServiceClient(cc) - // This unary call should fail, but not timeout. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(true)); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want ", err) - } -} - -func TestFlowControlLogicalRace(t *testing.T) { - // Test for a regression of https://github.com/grpc/grpc-go/issues/632, - // and other flow control bugs. - - defer leakcheck.Check(t) - - const ( - itemCount = 100 - itemSize = 1 << 10 - recvCount = 2 - maxFailures = 3 - - requestTimeout = time.Second * 5 - ) - - requestCount := 10000 - if raceMode { - requestCount = 1000 - } - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - defer lis.Close() - - s := grpc.NewServer() - testpb.RegisterTestServiceServer(s, &flowControlLogicalRaceServer{ - itemCount: itemCount, - itemSize: itemSize, - }) - defer s.Stop() - - go s.Serve(lis) - - ctx := context.Background() - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock()) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - defer cc.Close() - cl := testpb.NewTestServiceClient(cc) - - failures := 0 - for i := 0; i < requestCount; i++ { - ctx, cancel := context.WithTimeout(ctx, requestTimeout) - output, err := cl.StreamingOutputCall(ctx, &testpb.StreamingOutputCallRequest{}) - if err != nil { - t.Fatalf("StreamingOutputCall; err = %q", err) - } - - j := 0 - loop: - for ; j < recvCount; j++ { - _, err := output.Recv() - if err != nil { - if err == io.EOF { - break loop - } - switch status.Code(err) { - case codes.DeadlineExceeded: - break loop - default: - t.Fatalf("Recv; err = %q", err) - } - } - } - cancel() - <-ctx.Done() - - if j < recvCount { - t.Errorf("got %d responses to request %d", j, i) - failures++ - if failures >= maxFailures { - // Continue past the first failure to see if the connection is - // entirely broken, or if only a single RPC was affected - break - } - } - } -} - -type flowControlLogicalRaceServer struct { - testpb.TestServiceServer - - itemSize int - itemCount int -} - -func (s *flowControlLogicalRaceServer) StreamingOutputCall(req *testpb.StreamingOutputCallRequest, srv testpb.TestService_StreamingOutputCallServer) error { - for i := 0; i < s.itemCount; i++ { - err := srv.Send(&testpb.StreamingOutputCallResponse{ - Payload: &testpb.Payload{ - // Sending a large stream of data which the client reject - // helps to trigger some types of flow control bugs. - // - // Reallocating memory here is inefficient, but the stress it - // puts on the GC leads to more frequent flow control - // failures. The GC likely causes more variety in the - // goroutine scheduling orders. - Body: bytes.Repeat([]byte("a"), s.itemSize), - }, - }) - if err != nil { - return err - } - } - return nil -} - -type lockingWriter struct { - mu sync.Mutex - w io.Writer -} - -func (lw *lockingWriter) Write(p []byte) (n int, err error) { - lw.mu.Lock() - defer lw.mu.Unlock() - return lw.w.Write(p) -} - -func (lw *lockingWriter) setWriter(w io.Writer) { - lw.mu.Lock() - defer lw.mu.Unlock() - lw.w = w -} - -var testLogOutput = &lockingWriter{w: os.Stderr} - -// awaitNewConnLogOutput waits for any of grpc.NewConn's goroutines to -// terminate, if they're still running. It spams logs with this -// message. We wait for it so our log filter is still -// active. Otherwise the "defer restore()" at the top of various test -// functions restores our log filter and then the goroutine spams. -func awaitNewConnLogOutput() { - awaitLogOutput(50*time.Millisecond, "grpc: the client connection is closing; please retry") -} - -func awaitLogOutput(maxWait time.Duration, phrase string) { - pb := []byte(phrase) - - timer := time.NewTimer(maxWait) - defer timer.Stop() - wakeup := make(chan bool, 1) - for { - if logOutputHasContents(pb, wakeup) { - return - } - select { - case <-timer.C: - // Too slow. Oh well. - return - case <-wakeup: - } - } -} - -func logOutputHasContents(v []byte, wakeup chan<- bool) bool { - testLogOutput.mu.Lock() - defer testLogOutput.mu.Unlock() - fw, ok := testLogOutput.w.(*filterWriter) - if !ok { - return false - } - fw.mu.Lock() - defer fw.mu.Unlock() - if bytes.Contains(fw.buf.Bytes(), v) { - return true - } - fw.wakeup = wakeup - return false -} - -var verboseLogs = flag.Bool("verbose_logs", false, "show all grpclog output, without filtering") - -func noop() {} - -// declareLogNoise declares that t is expected to emit the following noisy phrases, -// even on success. Those phrases will be filtered from grpclog output -// and only be shown if *verbose_logs or t ends up failing. -// The returned restore function should be called with defer to be run -// before the test ends. -func declareLogNoise(t *testing.T, phrases ...string) (restore func()) { - if *verboseLogs { - return noop - } - fw := &filterWriter{dst: os.Stderr, filter: phrases} - testLogOutput.setWriter(fw) - return func() { - if t.Failed() { - fw.mu.Lock() - defer fw.mu.Unlock() - if fw.buf.Len() > 0 { - t.Logf("Complete log output:\n%s", fw.buf.Bytes()) - } - } - testLogOutput.setWriter(os.Stderr) - } -} - -type filterWriter struct { - dst io.Writer - filter []string - - mu sync.Mutex - buf bytes.Buffer - wakeup chan<- bool // if non-nil, gets true on write -} - -func (fw *filterWriter) Write(p []byte) (n int, err error) { - fw.mu.Lock() - fw.buf.Write(p) - if fw.wakeup != nil { - select { - case fw.wakeup <- true: - default: - } - } - fw.mu.Unlock() - - ps := string(p) - for _, f := range fw.filter { - if strings.Contains(ps, f) { - return len(p), nil - } - } - return fw.dst.Write(p) -} - -// stubServer is a server that is easy to customize within individual test -// cases. -type stubServer struct { - // Guarantees we satisfy this interface; panics if unimplemented methods are called. - testpb.TestServiceServer - - // Customizable implementations of server handlers. - emptyCall func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) - fullDuplexCall func(stream testpb.TestService_FullDuplexCallServer) error - - // A client connected to this service the test may use. Created in Start(). - client testpb.TestServiceClient - - cleanups []func() // Lambdas executed in Stop(); populated by Start(). -} - -func (ss *stubServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return ss.emptyCall(ctx, in) -} - -func (ss *stubServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return ss.fullDuplexCall(stream) -} - -// Start starts the server and creates a client connected to it. -func (ss *stubServer) Start(sopts []grpc.ServerOption) error { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - return fmt.Errorf(`net.Listen("tcp", "localhost:0") = %v`, err) - } - ss.cleanups = append(ss.cleanups, func() { lis.Close() }) - - s := grpc.NewServer(sopts...) - testpb.RegisterTestServiceServer(s, ss) - go s.Serve(lis) - ss.cleanups = append(ss.cleanups, s.Stop) - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock()) - if err != nil { - return fmt.Errorf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - ss.cleanups = append(ss.cleanups, func() { cc.Close() }) - - ss.client = testpb.NewTestServiceClient(cc) - return nil -} - -func (ss *stubServer) Stop() { - for i := len(ss.cleanups) - 1; i >= 0; i-- { - ss.cleanups[i]() - } -} - -func TestGRPCMethod(t *testing.T) { - defer leakcheck.Check(t) - var method string - var ok bool - - ss := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - method, ok = grpc.Method(ctx) - return &testpb.Empty{}, nil - }, - } - if err := ss.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer ss.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - if _, err := ss.client.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("ss.client.EmptyCall(_, _) = _, %v; want _, nil", err) - } - - if want := "/grpc.testing.TestService/EmptyCall"; !ok || method != want { - t.Fatalf("grpc.Method(_) = %q, %v; want %q, true", method, ok, want) - } -} - -func TestUnaryProxyDoesNotForwardMetadata(t *testing.T) { - const mdkey = "somedata" - - // endpoint ensures mdkey is NOT in metadata and returns an error if it is. - endpoint := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil { - return nil, status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return &testpb.Empty{}, nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint - // without explicitly copying the metadata. - proxy := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil { - return nil, status.Errorf(codes.Internal, "proxy: md=%v; want contains(%q)", md, mdkey) - } - return endpoint.client.EmptyCall(ctx, in) - }, - } - if err := proxy.Start(nil); err != nil { - t.Fatalf("Error starting proxy server: %v", err) - } - defer proxy.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - md := metadata.Pairs(mdkey, "val") - ctx = metadata.NewOutgoingContext(ctx, md) - - // Sanity check that endpoint properly errors when it sees mdkey. - _, err := endpoint.client.EmptyCall(ctx, &testpb.Empty{}) - if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal { - t.Fatalf("endpoint.client.EmptyCall(_, _) = _, %v; want _, ", err) - } - - if _, err := proxy.client.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatal(err.Error()) - } -} - -func TestStreamingProxyDoesNotForwardMetadata(t *testing.T) { - const mdkey = "somedata" - - // doFDC performs a FullDuplexCall with client and returns the error from the - // first stream.Recv call, or nil if that error is io.EOF. Calls t.Fatal if - // the stream cannot be established. - doFDC := func(ctx context.Context, client testpb.TestServiceClient) error { - stream, err := client.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("Unwanted error: %v", err) - } - if _, err := stream.Recv(); err != io.EOF { - return err - } - return nil - } - - // endpoint ensures mdkey is NOT in metadata and returns an error if it is. - endpoint := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - ctx := stream.Context() - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] != nil { - return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - // proxy ensures mdkey IS in metadata, then forwards the RPC to endpoint - // without explicitly copying the metadata. - proxy := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - ctx := stream.Context() - if md, ok := metadata.FromIncomingContext(ctx); !ok || md[mdkey] == nil { - return status.Errorf(codes.Internal, "endpoint: md=%v; want !contains(%q)", md, mdkey) - } - return doFDC(ctx, endpoint.client) - }, - } - if err := proxy.Start(nil); err != nil { - t.Fatalf("Error starting proxy server: %v", err) - } - defer proxy.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - md := metadata.Pairs(mdkey, "val") - ctx = metadata.NewOutgoingContext(ctx, md) - - // Sanity check that endpoint properly errors when it sees mdkey in ctx. - err := doFDC(ctx, endpoint.client) - if s, ok := status.FromError(err); !ok || s.Code() != codes.Internal { - t.Fatalf("stream.Recv() = _, %v; want _, ", err) - } - - if err := doFDC(ctx, proxy.client); err != nil { - t.Fatalf("doFDC(_, proxy.client) = %v; want nil", err) - } -} - -func TestStatsTagsAndTrace(t *testing.T) { - // Data added to context by client (typically in a stats handler). - tags := []byte{1, 5, 2, 4, 3} - trace := []byte{5, 2, 1, 3, 4} - - // endpoint ensures Tags() and Trace() in context match those that were added - // by the client and returns an error if not. - endpoint := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - md, _ := metadata.FromIncomingContext(ctx) - if tg := stats.Tags(ctx); !reflect.DeepEqual(tg, tags) { - return nil, status.Errorf(codes.Internal, "stats.Tags(%v)=%v; want %v", ctx, tg, tags) - } - if !reflect.DeepEqual(md["grpc-tags-bin"], []string{string(tags)}) { - return nil, status.Errorf(codes.Internal, "md['grpc-tags-bin']=%v; want %v", md["grpc-tags-bin"], tags) - } - if tr := stats.Trace(ctx); !reflect.DeepEqual(tr, trace) { - return nil, status.Errorf(codes.Internal, "stats.Trace(%v)=%v; want %v", ctx, tr, trace) - } - if !reflect.DeepEqual(md["grpc-trace-bin"], []string{string(trace)}) { - return nil, status.Errorf(codes.Internal, "md['grpc-trace-bin']=%v; want %v", md["grpc-trace-bin"], trace) - } - return &testpb.Empty{}, nil - }, - } - if err := endpoint.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer endpoint.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - testCases := []struct { - ctx context.Context - want codes.Code - }{ - {ctx: ctx, want: codes.Internal}, - {ctx: stats.SetTags(ctx, tags), want: codes.Internal}, - {ctx: stats.SetTrace(ctx, trace), want: codes.Internal}, - {ctx: stats.SetTags(stats.SetTrace(ctx, tags), tags), want: codes.Internal}, - {ctx: stats.SetTags(stats.SetTrace(ctx, trace), tags), want: codes.OK}, - } - - for _, tc := range testCases { - _, err := endpoint.client.EmptyCall(tc.ctx, &testpb.Empty{}) - if tc.want == codes.OK && err != nil { - t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, nil", tc.ctx, err) - } - if s, ok := status.FromError(err); !ok || s.Code() != tc.want { - t.Fatalf("endpoint.client.EmptyCall(%v, _) = _, %v; want _, ", tc.ctx, err, tc.want) - } - } -} - -func TestTapTimeout(t *testing.T) { - sopts := []grpc.ServerOption{ - grpc.InTapHandle(func(ctx context.Context, _ *tap.Info) (context.Context, error) { - c, cancel := context.WithCancel(ctx) - // Call cancel instead of setting a deadline so we can detect which error - // occurred -- this cancellation (desired) or the client's deadline - // expired (indicating this cancellation did not affect the RPC). - time.AfterFunc(10*time.Millisecond, cancel) - return c, nil - }), - } - - ss := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - <-ctx.Done() - return nil, status.Errorf(codes.Canceled, ctx.Err().Error()) - }, - } - if err := ss.Start(sopts); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer ss.Stop() - - // This was known to be flaky; test several times. - for i := 0; i < 10; i++ { - // Set our own deadline in case the server hangs. - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - res, err := ss.client.EmptyCall(ctx, &testpb.Empty{}) - cancel() - if s, ok := status.FromError(err); !ok || s.Code() != codes.Canceled { - t.Fatalf("ss.client.EmptyCall(context.Background(), _) = %v, %v; want nil, ", res, err) - } - } - -} - -func TestClientWriteFailsAfterServerClosesStream(t *testing.T) { - ss := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - return status.Errorf(codes.Internal, "") - }, - } - sopts := []grpc.ServerOption{} - if err := ss.Start(sopts); err != nil { - t.Fatalf("Error starting endpoing server: %v", err) - } - defer ss.Stop() - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - stream, err := ss.client.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("Error while creating stream: %v", err) - } - for { - if err := stream.Send(&testpb.StreamingOutputCallRequest{}); err == nil { - time.Sleep(5 * time.Millisecond) - } else if err == io.EOF { - break // Success. - } else { - t.Fatalf("stream.Send(_) = %v, want io.EOF", err) - } - } - -} - -type windowSizeConfig struct { - serverStream int32 - serverConn int32 - clientStream int32 - clientConn int32 -} - -func max(a, b int32) int32 { - if a > b { - return a - } - return b -} - -func TestConfigurableWindowSizeWithLargeWindow(t *testing.T) { - defer leakcheck.Check(t) - wc := windowSizeConfig{ - serverStream: 8 * 1024 * 1024, - serverConn: 12 * 1024 * 1024, - clientStream: 6 * 1024 * 1024, - clientConn: 8 * 1024 * 1024, - } - for _, e := range listTestEnv() { - testConfigurableWindowSize(t, e, wc) - } -} - -func TestConfigurableWindowSizeWithSmallWindow(t *testing.T) { - defer leakcheck.Check(t) - wc := windowSizeConfig{ - serverStream: 1, - serverConn: 1, - clientStream: 1, - clientConn: 1, - } - for _, e := range listTestEnv() { - testConfigurableWindowSize(t, e, wc) - } -} - -func testConfigurableWindowSize(t *testing.T, e env, wc windowSizeConfig) { - te := newTest(t, e) - te.serverInitialWindowSize = wc.serverStream - te.serverInitialConnWindowSize = wc.serverConn - te.clientInitialWindowSize = wc.clientStream - te.clientInitialConnWindowSize = wc.clientConn - - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - stream, err := tc.FullDuplexCall(context.Background()) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - numOfIter := 11 - // Set message size to exhaust largest of window sizes. - messageSize := max(max(wc.serverStream, wc.serverConn), max(wc.clientStream, wc.clientConn)) / int32(numOfIter-1) - messageSize = max(messageSize, 64*1024) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, messageSize) - if err != nil { - t.Fatal(err) - } - respParams := []*testpb.ResponseParameters{ - { - Size: messageSize, - }, - } - req := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParams, - Payload: payload, - } - for i := 0; i < numOfIter; i++ { - if err := stream.Send(req); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, req, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want _, ", stream, err) - } - } - if err := stream.CloseSend(); err != nil { - t.Fatalf("%v.CloseSend() = %v, want ", stream, err) - } -} - -var ( - // test authdata - authdata = map[string]string{ - "test-key": "test-value", - "test-key2-bin": string([]byte{1, 2, 3}), - } -) - -type testPerRPCCredentials struct{} - -func (cr testPerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return authdata, nil -} - -func (cr testPerRPCCredentials) RequireTransportSecurity() bool { - return false -} - -func authHandle(ctx context.Context, info *tap.Info) (context.Context, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return ctx, fmt.Errorf("didn't find metadata in context") - } - for k, vwant := range authdata { - vgot, ok := md[k] - if !ok { - return ctx, fmt.Errorf("didn't find authdata key %v in context", k) - } - if vgot[0] != vwant { - return ctx, fmt.Errorf("for key %v, got value %v, want %v", k, vgot, vwant) - } - } - return ctx, nil -} - -func TestPerRPCCredentialsViaDialOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaDialOptions(t, e) - } -} - -func testPerRPCCredentialsViaDialOptions(t *testing.T, e env) { - te := newTest(t, e) - te.tapHandle = authHandle - te.perRPCCreds = testPerRPCCredentials{} - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestPerRPCCredentialsViaCallOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaCallOptions(t, e) - } -} - -func testPerRPCCredentialsViaCallOptions(t *testing.T, e env) { - te := newTest(t, e) - te.tapHandle = authHandle - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testPerRPCCredentialsViaDialOptionsAndCallOptions(t, e) - } -} - -func testPerRPCCredentialsViaDialOptionsAndCallOptions(t *testing.T, e env) { - te := newTest(t, e) - te.perRPCCreds = testPerRPCCredentials{} - // When credentials are provided via both dial options and call options, - // we apply both sets. - te.tapHandle = func(ctx context.Context, _ *tap.Info) (context.Context, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return ctx, fmt.Errorf("couldn't find metadata in context") - } - for k, vwant := range authdata { - vgot, ok := md[k] - if !ok { - return ctx, fmt.Errorf("couldn't find metadata for key %v", k) - } - if len(vgot) != 2 { - return ctx, fmt.Errorf("len of value for key %v was %v, want 2", k, len(vgot)) - } - if vgot[0] != vwant || vgot[1] != vwant { - return ctx, fmt.Errorf("value for %v was %v, want [%v, %v]", k, vgot, vwant, vwant) - } - } - return ctx, nil - } - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.PerRPCCredentials(testPerRPCCredentials{})); err != nil { - t.Fatalf("Test failed. Reason: %v", err) - } -} - -func TestWaitForReadyConnection(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testWaitForReadyConnection(t, e) - } - -} - -func testWaitForReadyConnection(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - cc := te.clientConn() // Non-blocking dial. - tc := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - state := cc.GetState() - // Wait for connection to be Ready. - for ; state != connectivity.Ready && cc.WaitForStateChange(ctx, state); state = cc.GetState() { - } - if state != connectivity.Ready { - t.Fatalf("Want connection state to be Ready, got %v", state) - } - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - defer cancel() - // Make a fail-fast RPC. - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("TestService/EmptyCall(_,_) = _, %v, want _, nil", err) - } -} - -type errCodec struct { - noError bool -} - -func (c *errCodec) Marshal(v interface{}) ([]byte, error) { - if c.noError { - return []byte{}, nil - } - return nil, fmt.Errorf("3987^12 + 4365^12 = 4472^12") -} - -func (c *errCodec) Unmarshal(data []byte, v interface{}) error { - return nil -} - -func (c *errCodec) String() string { - return "Fermat's near-miss." -} - -func TestEncodeDoesntPanic(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testEncodeDoesntPanic(t, e) - } -} - -func testEncodeDoesntPanic(t *testing.T, e env) { - te := newTest(t, e) - erc := &errCodec{} - te.customCodec = erc - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - te.customCodec = nil - tc := testpb.NewTestServiceClient(te.clientConn()) - // Failure case, should not panic. - tc.EmptyCall(context.Background(), &testpb.Empty{}) - erc.noError = true - // Passing case. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("EmptyCall(_, _) = _, %v, want _, ", err) - } -} - -func TestSvrWriteStatusEarlyWrite(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testSvrWriteStatusEarlyWrite(t, e) - } -} - -func testSvrWriteStatusEarlyWrite(t *testing.T, e env) { - te := newTest(t, e) - const smallSize = 1024 - const largeSize = 2048 - const extraLargeSize = 4096 - te.maxServerReceiveMsgSize = newInt(largeSize) - te.maxServerSendMsgSize = newInt(largeSize) - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize) - if err != nil { - t.Fatal(err) - } - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - respParam := []*testpb.ResponseParameters{ - { - Size: int32(smallSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: extraLargePayload, - } - // Test recv case: server receives a message larger than maxServerReceiveMsgSize. - stream, err := tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send() = _, %v, want ", stream, err) - } - if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - // Test send case: server sends a message larger than maxServerSendMsgSize. - sreq.Payload = smallPayload - respParam[0].Size = int32(extraLargeSize) - - stream, err = tc.FullDuplexCall(te.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err = stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err = stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } -} - -// The following functions with function name ending with TD indicates that they -// should be deleted after old service config API is deprecated and deleted. -func testServiceConfigSetupTD(t *testing.T, e env) (*test, chan grpc.ServiceConfig) { - te := newTest(t, e) - // We write before read. - ch := make(chan grpc.ServiceConfig, 1) - te.sc = ch - te.userAgent = testAppUA - te.declareLogNoise( - "transport: http2Client.notifyError got notified that the client transport was broken EOF", - "grpc: addrConn.transportMonitor exits due to: grpc: the connection is closing", - "grpc: addrConn.resetTransport failed to create client transport: connection error", - "Failed to dial : context canceled; please retry.", - ) - return te, ch -} - -func TestServiceConfigGetMethodConfigTD(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testGetMethodConfigTD(t, e) - } -} - -func testGetMethodConfigTD(t *testing.T, e env) { - te, ch := testServiceConfigSetupTD(t, e) - defer te.tearDown() - - mc1 := grpc.MethodConfig{ - WaitForReady: newBool(true), - Timeout: newDuration(time.Millisecond), - } - mc2 := grpc.MethodConfig{WaitForReady: newBool(false)} - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc1 - m["/grpc.testing.TestService/"] = mc2 - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/UnaryCall"] = mc1 - m["/grpc.testing.TestService/"] = mc2 - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - // Wait for the new service config to propagate. - for { - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) == codes.DeadlineExceeded { - continue - } - break - } - // The following RPCs are expected to become fail-fast. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.Unavailable { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.Unavailable) - } -} - -func TestServiceConfigWaitForReadyTD(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigWaitForReadyTD(t, e) - } -} - -func testServiceConfigWaitForReadyTD(t *testing.T, e env) { - te, ch := testServiceConfigSetupTD(t, e) - defer te.tearDown() - - // Case1: Client API set failfast to be false, and service config set wait_for_ready to be false, Client API should win, and the rpc will wait until deadline exceeds. - mc := grpc.MethodConfig{ - WaitForReady: newBool(false), - Timeout: newDuration(time.Millisecond), - } - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background(), grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - - // Generate a service config update. - // Case2: Client API does not set failfast, and service config set wait_for_ready to be true, and the rpc will wait until deadline exceeds. - mc.WaitForReady = newBool(true) - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - // Wait for the new service config to take effect. - mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall") - for { - if !*mc.WaitForReady { - time.Sleep(100 * time.Millisecond) - mc = cc.GetMethodConfig("/grpc.testing.TestService/EmptyCall") - continue - } - break - } - // The following RPCs are expected to become non-fail-fast ones with 1ms deadline. - if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - if _, err := tc.FullDuplexCall(context.Background()); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } -} - -func TestServiceConfigTimeoutTD(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigTimeoutTD(t, e) - } -} - -func testServiceConfigTimeoutTD(t *testing.T, e env) { - te, ch := testServiceConfigSetupTD(t, e) - defer te.tearDown() - - // Case1: Client API sets timeout to be 1ns and ServiceConfig sets timeout to be 1hr. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - mc := grpc.MethodConfig{ - Timeout: newDuration(time.Hour), - } - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - // The following RPCs are expected to become non-fail-fast ones with 1ns deadline. - ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - ctx, cancel = context.WithTimeout(context.Background(), time.Nanosecond) - if _, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() - - // Generate a service config update. - // Case2: Client API sets timeout to be 1hr and ServiceConfig sets timeout to be 1ns. Timeout should be 1ns (min of 1ns and 1hr) and the rpc will wait until deadline exceeds. - mc.Timeout = newDuration(time.Nanosecond) - m = make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/EmptyCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc = grpc.ServiceConfig{ - Methods: m, - } - ch <- sc - - // Wait for the new service config to take effect. - mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall") - for { - if *mc.Timeout != time.Nanosecond { - time.Sleep(100 * time.Millisecond) - mc = cc.GetMethodConfig("/grpc.testing.TestService/FullDuplexCall") - continue - } - break - } - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err := tc.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %s", err, codes.DeadlineExceeded) - } - cancel() - - ctx, cancel = context.WithTimeout(context.Background(), time.Hour) - if _, err := tc.FullDuplexCall(ctx, grpc.FailFast(false)); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/FullDuplexCall(_) = _, %v, want %s", err, codes.DeadlineExceeded) - } - cancel() -} - -func TestServiceConfigMaxMsgSizeTD(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testServiceConfigMaxMsgSizeTD(t, e) - } -} - -func testServiceConfigMaxMsgSizeTD(t *testing.T, e env) { - // Setting up values and objects shared across all test cases. - const smallSize = 1 - const largeSize = 1024 - const extraLargeSize = 2048 - - smallPayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, smallSize) - if err != nil { - t.Fatal(err) - } - largePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, largeSize) - if err != nil { - t.Fatal(err) - } - extraLargePayload, err := newPayload(testpb.PayloadType_COMPRESSABLE, extraLargeSize) - if err != nil { - t.Fatal(err) - } - - mc := grpc.MethodConfig{ - MaxReqSize: newInt(extraLargeSize), - MaxRespSize: newInt(extraLargeSize), - } - - m := make(map[string]grpc.MethodConfig) - m["/grpc.testing.TestService/UnaryCall"] = mc - m["/grpc.testing.TestService/FullDuplexCall"] = mc - sc := grpc.ServiceConfig{ - Methods: m, - } - // Case1: sc set maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te1, ch1 := testServiceConfigSetupTD(t, e) - te1.startServer(&testServer{security: e.security}) - defer te1.tearDown() - - ch1 <- sc - tc := testpb.NewTestServiceClient(te1.clientConn()) - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: int32(extraLargeSize), - Payload: smallPayload, - } - // Test for unary RPC recv. - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = extraLargePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - respParam := []*testpb.ResponseParameters{ - { - Size: int32(extraLargeSize), - }, - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: smallPayload, - } - stream, err := tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = extraLargePayload - stream, err = tc.FullDuplexCall(te1.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case2: Client API set maxReqSize to 1024 (send), maxRespSize to 1024 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te2, ch2 := testServiceConfigSetupTD(t, e) - te2.maxClientReceiveMsgSize = newInt(1024) - te2.maxClientSendMsgSize = newInt(1024) - te2.startServer(&testServer{security: e.security}) - defer te2.tearDown() - ch2 <- sc - tc = testpb.NewTestServiceClient(te2.clientConn()) - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = int32(largeSize) - - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te2.ctx) - respParam[0].Size = int32(largeSize) - sreq.Payload = smallPayload - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te2.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } - - // Case3: Client API set maxReqSize to 4096 (send), maxRespSize to 4096 (recv). Sc sets maxReqSize to 2048 (send), maxRespSize to 2048 (recv). - te3, ch3 := testServiceConfigSetupTD(t, e) - te3.maxClientReceiveMsgSize = newInt(4096) - te3.maxClientSendMsgSize = newInt(4096) - te3.startServer(&testServer{security: e.security}) - defer te3.tearDown() - ch3 <- sc - tc = testpb.NewTestServiceClient(te3.clientConn()) - - // Test for unary RPC recv. - req.Payload = smallPayload - req.ResponseSize = int32(largeSize) - - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want ", err) - } - - req.ResponseSize = int32(extraLargeSize) - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for unary RPC send. - req.Payload = largePayload - req.ResponseSize = int32(smallSize) - if _, err := tc.UnaryCall(context.Background(), req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want ", err) - } - - req.Payload = extraLargePayload - if _, err := tc.UnaryCall(context.Background(), req); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, error code: %s", err, codes.ResourceExhausted) - } - - // Test for streaming RPC recv. - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam[0].Size = int32(largeSize) - sreq.Payload = smallPayload - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = _, %v, want ", stream, err) - } - - respParam[0].Size = int32(extraLargeSize) - - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Recv() = _, %v, want _, error code: %s", stream, err, codes.ResourceExhausted) - } - - // Test for streaming RPC send. - respParam[0].Size = int32(smallSize) - sreq.Payload = largePayload - stream, err = tc.FullDuplexCall(te3.ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - sreq.Payload = extraLargePayload - if err := stream.Send(sreq); err == nil || status.Code(err) != codes.ResourceExhausted { - t.Fatalf("%v.Send(%v) = %v, want _, error code: %s", stream, sreq, err, codes.ResourceExhausted) - } -} - -func TestMethodFromServerStream(t *testing.T) { - defer leakcheck.Check(t) - const testMethod = "/package.service/method" - e := tcpClearRREnv - te := newTest(t, e) - var method string - var ok bool - te.unknownHandler = func(srv interface{}, stream grpc.ServerStream) error { - method, ok = grpc.MethodFromServerStream(stream) - return nil - } - - te.startServer(nil) - defer te.tearDown() - _ = te.clientConn().Invoke(context.Background(), testMethod, nil, nil) - if !ok || method != testMethod { - t.Fatalf("Invoke with method %q, got %q, %v, want %q, true", testMethod, method, ok, testMethod) - } -} - -func TestInterceptorCanAccessCallOptions(t *testing.T) { - defer leakcheck.Check(t) - e := tcpClearRREnv - te := newTest(t, e) - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - - type observedOptions struct { - headers []*metadata.MD - trailers []*metadata.MD - peer []*peer.Peer - creds []credentials.PerRPCCredentials - failFast []bool - maxRecvSize []int - maxSendSize []int - compressor []string - subtype []string - } - var observedOpts observedOptions - populateOpts := func(opts []grpc.CallOption) { - for _, o := range opts { - switch o := o.(type) { - case grpc.HeaderCallOption: - observedOpts.headers = append(observedOpts.headers, o.HeaderAddr) - case grpc.TrailerCallOption: - observedOpts.trailers = append(observedOpts.trailers, o.TrailerAddr) - case grpc.PeerCallOption: - observedOpts.peer = append(observedOpts.peer, o.PeerAddr) - case grpc.PerRPCCredsCallOption: - observedOpts.creds = append(observedOpts.creds, o.Creds) - case grpc.FailFastCallOption: - observedOpts.failFast = append(observedOpts.failFast, o.FailFast) - case grpc.MaxRecvMsgSizeCallOption: - observedOpts.maxRecvSize = append(observedOpts.maxRecvSize, o.MaxRecvMsgSize) - case grpc.MaxSendMsgSizeCallOption: - observedOpts.maxSendSize = append(observedOpts.maxSendSize, o.MaxSendMsgSize) - case grpc.CompressorCallOption: - observedOpts.compressor = append(observedOpts.compressor, o.CompressorType) - case grpc.ContentSubtypeCallOption: - observedOpts.subtype = append(observedOpts.subtype, o.ContentSubtype) - } - } - } - - te.unaryClientInt = func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - populateOpts(opts) - return nil - } - te.streamClientInt = func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - populateOpts(opts) - return nil, nil - } - - defaults := []grpc.CallOption{ - grpc.FailFast(false), - grpc.MaxCallRecvMsgSize(1010), - } - tc := testpb.NewTestServiceClient(te.clientConn(grpc.WithDefaultCallOptions(defaults...))) - - var headers metadata.MD - var trailers metadata.MD - var pr peer.Peer - tc.UnaryCall(context.Background(), &testpb.SimpleRequest{}, - grpc.MaxCallRecvMsgSize(100), - grpc.MaxCallSendMsgSize(200), - grpc.PerRPCCredentials(testPerRPCCredentials{}), - grpc.Header(&headers), - grpc.Trailer(&trailers), - grpc.Peer(&pr)) - expected := observedOptions{ - failFast: []bool{false}, - maxRecvSize: []int{1010, 100}, - maxSendSize: []int{200}, - creds: []credentials.PerRPCCredentials{testPerRPCCredentials{}}, - headers: []*metadata.MD{&headers}, - trailers: []*metadata.MD{&trailers}, - peer: []*peer.Peer{&pr}, - } - - if !reflect.DeepEqual(expected, observedOpts) { - t.Errorf("unary call did not observe expected options: expected %#v, got %#v", expected, observedOpts) - } - - observedOpts = observedOptions{} // reset - - tc.StreamingInputCall(context.Background(), - grpc.FailFast(true), - grpc.MaxCallSendMsgSize(2020), - grpc.UseCompressor("comp-type"), - grpc.CallContentSubtype("json")) - expected = observedOptions{ - failFast: []bool{false, true}, - maxRecvSize: []int{1010}, - maxSendSize: []int{2020}, - compressor: []string{"comp-type"}, - subtype: []string{"json"}, - } - - if !reflect.DeepEqual(expected, observedOpts) { - t.Errorf("streaming call did not observe expected options: expected %#v, got %#v", expected, observedOpts) - } -} - -func TestCompressorRegister(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testCompressorRegister(t, e) - } -} - -func testCompressorRegister(t *testing.T, e env) { - te := newTest(t, e) - te.clientCompression = false - te.serverCompression = false - te.clientUseCompression = true - - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - - // Unary call - const argSize = 271828 - const respSize = 314159 - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("something", "something")) - if _, err := tc.UnaryCall(ctx, req); err != nil { - t.Fatalf("TestService/UnaryCall(_, _) = _, %v, want _, ", err) - } - // Streaming RPC - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := tc.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_) = _, %v, want ", tc, err) - } - respParam := []*testpb.ResponseParameters{ - { - Size: 31415, - }, - } - payload, err = newPayload(testpb.PayloadType_COMPRESSABLE, int32(31415)) - if err != nil { - t.Fatal(err) - } - sreq := &testpb.StreamingOutputCallRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseParameters: respParam, - Payload: payload, - } - if err := stream.Send(sreq); err != nil { - t.Fatalf("%v.Send(%v) = %v, want ", stream, sreq, err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("%v.Recv() = %v, want ", stream, err) - } -} - -func TestServeExitsWhenListenerClosed(t *testing.T) { - defer leakcheck.Check(t) - - ss := &stubServer{ - emptyCall: func(context.Context, *testpb.Empty) (*testpb.Empty, error) { - return &testpb.Empty{}, nil - }, - } - - s := grpc.NewServer() - testpb.RegisterTestServiceServer(s, ss) - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to create listener: %v", err) - } - - done := make(chan struct{}) - go func() { - s.Serve(lis) - close(done) - }() - - cc, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure(), grpc.WithBlock()) - if err != nil { - t.Fatalf("Failed to dial server: %v", err) - } - defer cc.Close() - c := testpb.NewTestServiceClient(cc) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if _, err := c.EmptyCall(ctx, &testpb.Empty{}); err != nil { - t.Fatalf("Failed to send test RPC to server: %v", err) - } - - if err := lis.Close(); err != nil { - t.Fatalf("Failed to close listener: %v", err) - } - const timeout = 5 * time.Second - timer := time.NewTimer(timeout) - select { - case <-done: - return - case <-timer.C: - t.Fatalf("Serve did not return after %v", timeout) - } -} - -// Service handler returns status with invalid utf8 message. -func TestStatusInvalidUTF8Message(t *testing.T) { - defer leakcheck.Check(t) - - var ( - origMsg = string([]byte{0xff, 0xfe, 0xfd}) - wantMsg = "���" - ) - - ss := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - return nil, status.Errorf(codes.Internal, origMsg) - }, - } - if err := ss.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer ss.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - if _, err := ss.client.EmptyCall(ctx, &testpb.Empty{}); status.Convert(err).Message() != wantMsg { - t.Fatalf("ss.client.EmptyCall(_, _) = _, %v (msg %q); want _, err with msg %q", err, status.Convert(err).Message(), wantMsg) - } -} - -// Service handler returns status with details and invalid utf8 message. Proto -// will fail to marshal the status because of the invalid utf8 message. Details -// will be dropped when sending. -func TestStatusInvalidUTF8Details(t *testing.T) { - defer leakcheck.Check(t) - - var ( - origMsg = string([]byte{0xff, 0xfe, 0xfd}) - wantMsg = "���" - ) - - ss := &stubServer{ - emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - st := status.New(codes.Internal, origMsg) - st, err := st.WithDetails(&testpb.Empty{}) - if err != nil { - return nil, err - } - return nil, st.Err() - }, - } - if err := ss.Start(nil); err != nil { - t.Fatalf("Error starting endpoint server: %v", err) - } - defer ss.Stop() - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - _, err := ss.client.EmptyCall(ctx, &testpb.Empty{}) - st := status.Convert(err) - if st.Message() != wantMsg { - t.Fatalf("ss.client.EmptyCall(_, _) = _, %v (msg %q); want _, err with msg %q", err, st.Message(), wantMsg) - } - if len(st.Details()) != 0 { - // Details should be dropped on the server side. - t.Fatalf("RPC status contain details: %v, want no details", st.Details()) - } -} - -func TestClientDoesntDeadlockWhileWritingErrornousLargeMessages(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - if e.httpHandler { - continue - } - testClientDoesntDeadlockWhileWritingErrornousLargeMessages(t, e) - } -} - -func testClientDoesntDeadlockWhileWritingErrornousLargeMessages(t *testing.T, e env) { - te := newTest(t, e) - te.userAgent = testAppUA - smallSize := 1024 - te.maxServerReceiveMsgSize = &smallSize - te.startServer(&testServer{security: e.security}) - defer te.tearDown() - tc := testpb.NewTestServiceClient(te.clientConn()) - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, 1048576) - if err != nil { - t.Fatal(err) - } - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - Payload: payload, - } - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for j := 0; j < 100; j++ { - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10)) - defer cancel() - if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.ResourceExhausted { - t.Errorf("TestService/UnaryCall(_,_) = _. %v, want code: %s", err, codes.ResourceExhausted) - return - } - } - }() - } - wg.Wait() -} - -const clientAlwaysFailCredErrorMsg = "clientAlwaysFailCred always fails" - -var errClientAlwaysFailCred = errors.New(clientAlwaysFailCredErrorMsg) - -type clientAlwaysFailCred struct{} - -func (c clientAlwaysFailCred) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return nil, nil, errClientAlwaysFailCred -} -func (c clientAlwaysFailCred) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - return rawConn, nil, nil -} -func (c clientAlwaysFailCred) Info() credentials.ProtocolInfo { - return credentials.ProtocolInfo{} -} -func (c clientAlwaysFailCred) Clone() credentials.TransportCredentials { - return nil -} -func (c clientAlwaysFailCred) OverrideServerName(s string) error { - return nil -} - -func TestFailFastRPCErrorOnBadCertificates(t *testing.T) { - te := newTest(t, env{name: "bad-cred", network: "tcp", security: "clientAlwaysFailCred", balancer: "round_robin"}) - te.startServer(&testServer{security: te.e.security}) - defer te.tearDown() - - opts := []grpc.DialOption{grpc.WithTransportCredentials(clientAlwaysFailCred{})} - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, te.srvAddr, opts...) - if err != nil { - t.Fatalf("Dial(_) = %v, want %v", err, nil) - } - defer cc.Close() - - tc := testpb.NewTestServiceClient(cc) - for i := 0; i < 1000; i++ { - // This loop runs for at most 1 second. The first several RPCs will fail - // with Unavailable because the connection hasn't started. When the - // first connection failed with creds error, the next RPC should also - // fail with the expected error. - if _, err = tc.EmptyCall(context.Background(), &testpb.Empty{}); strings.Contains(err.Error(), clientAlwaysFailCredErrorMsg) { - return - } - time.Sleep(time.Millisecond) - } - te.t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want err.Error() contains %q", err, clientAlwaysFailCredErrorMsg) -} - -func TestRPCTimeout(t *testing.T) { - defer leakcheck.Check(t) - for _, e := range listTestEnv() { - testRPCTimeout(t, e) - } -} - -func testRPCTimeout(t *testing.T, e env) { - te := newTest(t, e) - te.startServer(&testServer{security: e.security, unaryCallSleepTime: 500 * time.Millisecond}) - defer te.tearDown() - - cc := te.clientConn() - tc := testpb.NewTestServiceClient(cc) - - const argSize = 2718 - const respSize = 314 - - payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, argSize) - if err != nil { - t.Fatal(err) - } - - req := &testpb.SimpleRequest{ - ResponseType: testpb.PayloadType_COMPRESSABLE, - ResponseSize: respSize, - Payload: payload, - } - for i := -1; i <= 10; i++ { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i)*time.Millisecond) - if _, err := tc.UnaryCall(ctx, req); status.Code(err) != codes.DeadlineExceeded { - t.Fatalf("TestService/UnaryCallv(_, _) = _, %v; want , error code: %s", err, codes.DeadlineExceeded) - } - cancel() - } -} diff --git a/examples/google.golang.org/grpc/test/gracefulstop_test.go b/examples/google.golang.org/grpc/test/gracefulstop_test.go deleted file mode 100755 index 5602358..0000000 --- a/examples/google.golang.org/grpc/test/gracefulstop_test.go +++ /dev/null @@ -1,212 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package test - -import ( - "fmt" - "io" - "net" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/internal/leakcheck" - - testpb "google.golang.org/grpc/test/grpc_testing" -) - -type delayListener struct { - net.Listener - closeCalled chan struct{} - acceptCalled chan struct{} - allowCloseCh chan struct{} - cc *delayConn - dialed bool -} - -func (d *delayListener) Accept() (net.Conn, error) { - select { - case <-d.acceptCalled: - // On the second call, block until closed, then return an error. - <-d.closeCalled - <-d.allowCloseCh - return nil, fmt.Errorf("listener is closed") - default: - close(d.acceptCalled) - conn, err := d.Listener.Accept() - // Allow closing of listener only after accept. - // Note: Dial can return successfully, yet Accept - // might now have finished. - d.allowClose() - return conn, err - } -} - -func (d *delayListener) allowClose() { - close(d.allowCloseCh) -} -func (d *delayListener) Close() error { - close(d.closeCalled) - go func() { - <-d.allowCloseCh - d.Listener.Close() - }() - return nil -} - -func (d *delayListener) allowClientRead() { - d.cc.allowRead() -} - -func (d *delayListener) Dial(to time.Duration) (net.Conn, error) { - if d.dialed { - // Only hand out one connection (net.Dial can return more even after the - // listener is closed). This is not thread-safe, but Dial should never be - // called concurrently in this environment. - return nil, fmt.Errorf("no more conns") - } - d.dialed = true - c, err := net.DialTimeout("tcp", d.Listener.Addr().String(), to) - if err != nil { - return nil, err - } - d.cc = &delayConn{Conn: c, blockRead: make(chan struct{})} - return d.cc, nil -} - -type delayConn struct { - net.Conn - blockRead chan struct{} -} - -func (d *delayConn) allowRead() { - close(d.blockRead) -} - -func (d *delayConn) Read(b []byte) (n int, err error) { - <-d.blockRead - return d.Conn.Read(b) -} - -func TestGracefulStop(t *testing.T) { - defer leakcheck.Check(t) - // This test ensures GracefulStop cannot race and break RPCs on new - // connections created after GracefulStop was called but before - // listener.Accept() returns a "closing" error. - // - // Steps of this test: - // 1. Start Server - // 2. GracefulStop() Server after listener's Accept is called, but don't - // allow Accept() to exit when Close() is called on it. - // 3. Create a new connection to the server after listener.Close() is called. - // Server will want to send a GoAway on the new conn, but we delay client - // reads until 5. - // 4. Send an RPC on the new connection. - // 5. Allow the client to read the GoAway. The RPC should complete - // successfully. - - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error listenening: %v", err) - } - dlis := &delayListener{ - Listener: lis, - acceptCalled: make(chan struct{}), - closeCalled: make(chan struct{}), - allowCloseCh: make(chan struct{}), - } - d := func(_ string, to time.Duration) (net.Conn, error) { return dlis.Dial(to) } - serverGotReq := make(chan struct{}) - - ss := &stubServer{ - fullDuplexCall: func(stream testpb.TestService_FullDuplexCallServer) error { - close(serverGotReq) - _, err := stream.Recv() - if err != nil { - return err - } - return stream.Send(&testpb.StreamingOutputCallResponse{}) - }, - } - s := grpc.NewServer() - testpb.RegisterTestServiceServer(s, ss) - - // 1. Start Server - wg := sync.WaitGroup{} - wg.Add(1) - go func() { - s.Serve(dlis) - wg.Done() - }() - - // 2. GracefulStop() Server after listener's Accept is called, but don't - // allow Accept() to exit when Close() is called on it. - <-dlis.acceptCalled - wg.Add(1) - go func() { - s.GracefulStop() - wg.Done() - }() - - // 3. Create a new connection to the server after listener.Close() is called. - // Server will want to send a GoAway on the new conn, but we delay it - // until 5. - - <-dlis.closeCalled // Block until GracefulStop calls dlis.Close() - - // Now dial. The listener's Accept method will return a valid connection, - // even though GracefulStop has closed the listener. - ctx, dialCancel := context.WithTimeout(context.Background(), 5*time.Second) - defer dialCancel() - cc, err := grpc.DialContext(ctx, "", grpc.WithInsecure(), grpc.WithBlock(), grpc.WithDialer(d)) - if err != nil { - t.Fatalf("grpc.Dial(%q) = %v", lis.Addr().String(), err) - } - client := testpb.NewTestServiceClient(cc) - defer cc.Close() - - // 4. Send an RPC on the new connection. - // The server would send a GOAWAY first, but we are delaying the server's - // writes for now until the client writes more than the preface. - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - stream, err := client.FullDuplexCall(ctx) - if err != nil { - t.Fatalf("FullDuplexCall= _, %v; want _, ", err) - } - go func() { - // 5. Allow the client to read the GoAway. The RPC should complete - // successfully. - <-serverGotReq - dlis.allowClientRead() - }() - if err := stream.Send(&testpb.StreamingOutputCallRequest{}); err != nil { - t.Fatalf("stream.Send(_) = %v, want ", err) - } - if _, err := stream.Recv(); err != nil { - t.Fatalf("stream.Recv() = _, %v, want _, ", err) - } - if _, err := stream.Recv(); err != io.EOF { - t.Fatalf("stream.Recv() = _, %v, want _, io.EOF", err) - } - // 5. happens above, then we finish the call. - cancel() - wg.Wait() -} diff --git a/examples/google.golang.org/grpc/test/grpc_testing/test.pb.go b/examples/google.golang.org/grpc/test/grpc_testing/test.pb.go deleted file mode 100755 index 871f7cc..0000000 --- a/examples/google.golang.org/grpc/test/grpc_testing/test.pb.go +++ /dev/null @@ -1,949 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc_testing/test.proto - -package grpc_testing - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// The type of payload that should be returned. -type PayloadType int32 - -const ( - // Compressable text format. - PayloadType_COMPRESSABLE PayloadType = 0 - // Uncompressable binary format. - PayloadType_UNCOMPRESSABLE PayloadType = 1 - // Randomly chosen from all other formats defined in this enum. - PayloadType_RANDOM PayloadType = 2 -) - -var PayloadType_name = map[int32]string{ - 0: "COMPRESSABLE", - 1: "UNCOMPRESSABLE", - 2: "RANDOM", -} -var PayloadType_value = map[string]int32{ - "COMPRESSABLE": 0, - "UNCOMPRESSABLE": 1, - "RANDOM": 2, -} - -func (x PayloadType) String() string { - return proto.EnumName(PayloadType_name, int32(x)) -} -func (PayloadType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{0} -} - -type Empty struct { - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Empty) Reset() { *m = Empty{} } -func (m *Empty) String() string { return proto.CompactTextString(m) } -func (*Empty) ProtoMessage() {} -func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{0} -} -func (m *Empty) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Empty.Unmarshal(m, b) -} -func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Empty.Marshal(b, m, deterministic) -} -func (dst *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(dst, src) -} -func (m *Empty) XXX_Size() int { - return xxx_messageInfo_Empty.Size(m) -} -func (m *Empty) XXX_DiscardUnknown() { - xxx_messageInfo_Empty.DiscardUnknown(m) -} - -var xxx_messageInfo_Empty proto.InternalMessageInfo - -// A block of data, to simply increase gRPC message size. -type Payload struct { - // The type of data in body. - Type PayloadType `protobuf:"varint,1,opt,name=type,proto3,enum=grpc.testing.PayloadType" json:"type,omitempty"` - // Primary contents of payload. - Body []byte `protobuf:"bytes,2,opt,name=body,proto3" json:"body,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Payload) Reset() { *m = Payload{} } -func (m *Payload) String() string { return proto.CompactTextString(m) } -func (*Payload) ProtoMessage() {} -func (*Payload) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{1} -} -func (m *Payload) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Payload.Unmarshal(m, b) -} -func (m *Payload) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Payload.Marshal(b, m, deterministic) -} -func (dst *Payload) XXX_Merge(src proto.Message) { - xxx_messageInfo_Payload.Merge(dst, src) -} -func (m *Payload) XXX_Size() int { - return xxx_messageInfo_Payload.Size(m) -} -func (m *Payload) XXX_DiscardUnknown() { - xxx_messageInfo_Payload.DiscardUnknown(m) -} - -var xxx_messageInfo_Payload proto.InternalMessageInfo - -func (m *Payload) GetType() PayloadType { - if m != nil { - return m.Type - } - return PayloadType_COMPRESSABLE -} - -func (m *Payload) GetBody() []byte { - if m != nil { - return m.Body - } - return nil -} - -// Unary request. -type SimpleRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - ResponseSize int32 `protobuf:"varint,2,opt,name=response_size,json=responseSize,proto3" json:"response_size,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - // Whether SimpleResponse should include username. - FillUsername bool `protobuf:"varint,4,opt,name=fill_username,json=fillUsername,proto3" json:"fill_username,omitempty"` - // Whether SimpleResponse should include OAuth scope. - FillOauthScope bool `protobuf:"varint,5,opt,name=fill_oauth_scope,json=fillOauthScope,proto3" json:"fill_oauth_scope,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleRequest) Reset() { *m = SimpleRequest{} } -func (m *SimpleRequest) String() string { return proto.CompactTextString(m) } -func (*SimpleRequest) ProtoMessage() {} -func (*SimpleRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{2} -} -func (m *SimpleRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleRequest.Unmarshal(m, b) -} -func (m *SimpleRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleRequest.Marshal(b, m, deterministic) -} -func (dst *SimpleRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleRequest.Merge(dst, src) -} -func (m *SimpleRequest) XXX_Size() int { - return xxx_messageInfo_SimpleRequest.Size(m) -} -func (m *SimpleRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleRequest proto.InternalMessageInfo - -func (m *SimpleRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *SimpleRequest) GetResponseSize() int32 { - if m != nil { - return m.ResponseSize - } - return 0 -} - -func (m *SimpleRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleRequest) GetFillUsername() bool { - if m != nil { - return m.FillUsername - } - return false -} - -func (m *SimpleRequest) GetFillOauthScope() bool { - if m != nil { - return m.FillOauthScope - } - return false -} - -// Unary response, as configured by the request. -type SimpleResponse struct { - // Payload to increase message size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - // The user the request came from, for verifying authentication was - // successful when the client expected it. - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - // OAuth scope. - OauthScope string `protobuf:"bytes,3,opt,name=oauth_scope,json=oauthScope,proto3" json:"oauth_scope,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } -func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } -func (*SimpleResponse) ProtoMessage() {} -func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{3} -} -func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) -} -func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) -} -func (dst *SimpleResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_SimpleResponse.Merge(dst, src) -} -func (m *SimpleResponse) XXX_Size() int { - return xxx_messageInfo_SimpleResponse.Size(m) -} -func (m *SimpleResponse) XXX_DiscardUnknown() { - xxx_messageInfo_SimpleResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo - -func (m *SimpleResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func (m *SimpleResponse) GetUsername() string { - if m != nil { - return m.Username - } - return "" -} - -func (m *SimpleResponse) GetOauthScope() string { - if m != nil { - return m.OauthScope - } - return "" -} - -// Client-streaming request. -type StreamingInputCallRequest struct { - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallRequest) Reset() { *m = StreamingInputCallRequest{} } -func (m *StreamingInputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallRequest) ProtoMessage() {} -func (*StreamingInputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{4} -} -func (m *StreamingInputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallRequest.Unmarshal(m, b) -} -func (m *StreamingInputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallRequest.Merge(dst, src) -} -func (m *StreamingInputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallRequest.Size(m) -} -func (m *StreamingInputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallRequest proto.InternalMessageInfo - -func (m *StreamingInputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Client-streaming response. -type StreamingInputCallResponse struct { - // Aggregated size of payloads received from the client. - AggregatedPayloadSize int32 `protobuf:"varint,1,opt,name=aggregated_payload_size,json=aggregatedPayloadSize,proto3" json:"aggregated_payload_size,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingInputCallResponse) Reset() { *m = StreamingInputCallResponse{} } -func (m *StreamingInputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingInputCallResponse) ProtoMessage() {} -func (*StreamingInputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{5} -} -func (m *StreamingInputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingInputCallResponse.Unmarshal(m, b) -} -func (m *StreamingInputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingInputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingInputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingInputCallResponse.Merge(dst, src) -} -func (m *StreamingInputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingInputCallResponse.Size(m) -} -func (m *StreamingInputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingInputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingInputCallResponse proto.InternalMessageInfo - -func (m *StreamingInputCallResponse) GetAggregatedPayloadSize() int32 { - if m != nil { - return m.AggregatedPayloadSize - } - return 0 -} - -// Configuration for a particular response. -type ResponseParameters struct { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - Size int32 `protobuf:"varint,1,opt,name=size,proto3" json:"size,omitempty"` - // Desired interval between consecutive responses in the response stream in - // microseconds. - IntervalUs int32 `protobuf:"varint,2,opt,name=interval_us,json=intervalUs,proto3" json:"interval_us,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ResponseParameters) Reset() { *m = ResponseParameters{} } -func (m *ResponseParameters) String() string { return proto.CompactTextString(m) } -func (*ResponseParameters) ProtoMessage() {} -func (*ResponseParameters) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{6} -} -func (m *ResponseParameters) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResponseParameters.Unmarshal(m, b) -} -func (m *ResponseParameters) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResponseParameters.Marshal(b, m, deterministic) -} -func (dst *ResponseParameters) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResponseParameters.Merge(dst, src) -} -func (m *ResponseParameters) XXX_Size() int { - return xxx_messageInfo_ResponseParameters.Size(m) -} -func (m *ResponseParameters) XXX_DiscardUnknown() { - xxx_messageInfo_ResponseParameters.DiscardUnknown(m) -} - -var xxx_messageInfo_ResponseParameters proto.InternalMessageInfo - -func (m *ResponseParameters) GetSize() int32 { - if m != nil { - return m.Size - } - return 0 -} - -func (m *ResponseParameters) GetIntervalUs() int32 { - if m != nil { - return m.IntervalUs - } - return 0 -} - -// Server-streaming request. -type StreamingOutputCallRequest struct { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - ResponseType PayloadType `protobuf:"varint,1,opt,name=response_type,json=responseType,proto3,enum=grpc.testing.PayloadType" json:"response_type,omitempty"` - // Configuration for each expected response message. - ResponseParameters []*ResponseParameters `protobuf:"bytes,2,rep,name=response_parameters,json=responseParameters,proto3" json:"response_parameters,omitempty"` - // Optional input payload sent along with the request. - Payload *Payload `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallRequest) Reset() { *m = StreamingOutputCallRequest{} } -func (m *StreamingOutputCallRequest) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallRequest) ProtoMessage() {} -func (*StreamingOutputCallRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{7} -} -func (m *StreamingOutputCallRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallRequest.Unmarshal(m, b) -} -func (m *StreamingOutputCallRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallRequest.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallRequest.Merge(dst, src) -} -func (m *StreamingOutputCallRequest) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallRequest.Size(m) -} -func (m *StreamingOutputCallRequest) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallRequest proto.InternalMessageInfo - -func (m *StreamingOutputCallRequest) GetResponseType() PayloadType { - if m != nil { - return m.ResponseType - } - return PayloadType_COMPRESSABLE -} - -func (m *StreamingOutputCallRequest) GetResponseParameters() []*ResponseParameters { - if m != nil { - return m.ResponseParameters - } - return nil -} - -func (m *StreamingOutputCallRequest) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -// Server-streaming response, as configured by the request and parameters. -type StreamingOutputCallResponse struct { - // Payload to increase response size. - Payload *Payload `protobuf:"bytes,1,opt,name=payload,proto3" json:"payload,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *StreamingOutputCallResponse) Reset() { *m = StreamingOutputCallResponse{} } -func (m *StreamingOutputCallResponse) String() string { return proto.CompactTextString(m) } -func (*StreamingOutputCallResponse) ProtoMessage() {} -func (*StreamingOutputCallResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_test_c9f6c5af4267cb88, []int{8} -} -func (m *StreamingOutputCallResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_StreamingOutputCallResponse.Unmarshal(m, b) -} -func (m *StreamingOutputCallResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_StreamingOutputCallResponse.Marshal(b, m, deterministic) -} -func (dst *StreamingOutputCallResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_StreamingOutputCallResponse.Merge(dst, src) -} -func (m *StreamingOutputCallResponse) XXX_Size() int { - return xxx_messageInfo_StreamingOutputCallResponse.Size(m) -} -func (m *StreamingOutputCallResponse) XXX_DiscardUnknown() { - xxx_messageInfo_StreamingOutputCallResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_StreamingOutputCallResponse proto.InternalMessageInfo - -func (m *StreamingOutputCallResponse) GetPayload() *Payload { - if m != nil { - return m.Payload - } - return nil -} - -func init() { - proto.RegisterType((*Empty)(nil), "grpc.testing.Empty") - proto.RegisterType((*Payload)(nil), "grpc.testing.Payload") - proto.RegisterType((*SimpleRequest)(nil), "grpc.testing.SimpleRequest") - proto.RegisterType((*SimpleResponse)(nil), "grpc.testing.SimpleResponse") - proto.RegisterType((*StreamingInputCallRequest)(nil), "grpc.testing.StreamingInputCallRequest") - proto.RegisterType((*StreamingInputCallResponse)(nil), "grpc.testing.StreamingInputCallResponse") - proto.RegisterType((*ResponseParameters)(nil), "grpc.testing.ResponseParameters") - proto.RegisterType((*StreamingOutputCallRequest)(nil), "grpc.testing.StreamingOutputCallRequest") - proto.RegisterType((*StreamingOutputCallResponse)(nil), "grpc.testing.StreamingOutputCallResponse") - proto.RegisterEnum("grpc.testing.PayloadType", PayloadType_name, PayloadType_value) -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// TestServiceClient is the client API for TestService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TestServiceClient interface { - // One empty request followed by one empty response. - EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) -} - -type testServiceClient struct { - cc *grpc.ClientConn -} - -func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { - return &testServiceClient{cc} -} - -func (c *testServiceClient) EmptyCall(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*Empty, error) { - out := new(Empty) - err := c.cc.Invoke(ctx, "/grpc.testing.TestService/EmptyCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) { - out := new(SimpleResponse) - err := c.cc.Invoke(ctx, "/grpc.testing.TestService/UnaryCall", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *testServiceClient) StreamingOutputCall(ctx context.Context, in *StreamingOutputCallRequest, opts ...grpc.CallOption) (TestService_StreamingOutputCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[0], "/grpc.testing.TestService/StreamingOutputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingOutputCallClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type TestService_StreamingOutputCallClient interface { - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingOutputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingOutputCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) StreamingInputCall(ctx context.Context, opts ...grpc.CallOption) (TestService_StreamingInputCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[1], "/grpc.testing.TestService/StreamingInputCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceStreamingInputCallClient{stream} - return x, nil -} - -type TestService_StreamingInputCallClient interface { - Send(*StreamingInputCallRequest) error - CloseAndRecv() (*StreamingInputCallResponse, error) - grpc.ClientStream -} - -type testServiceStreamingInputCallClient struct { - grpc.ClientStream -} - -func (x *testServiceStreamingInputCallClient) Send(m *StreamingInputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallClient) CloseAndRecv() (*StreamingInputCallResponse, error) { - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - m := new(StreamingInputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) FullDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_FullDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[2], "/grpc.testing.TestService/FullDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceFullDuplexCallClient{stream} - return x, nil -} - -type TestService_FullDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceFullDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceFullDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *testServiceClient) HalfDuplexCall(ctx context.Context, opts ...grpc.CallOption) (TestService_HalfDuplexCallClient, error) { - stream, err := c.cc.NewStream(ctx, &_TestService_serviceDesc.Streams[3], "/grpc.testing.TestService/HalfDuplexCall", opts...) - if err != nil { - return nil, err - } - x := &testServiceHalfDuplexCallClient{stream} - return x, nil -} - -type TestService_HalfDuplexCallClient interface { - Send(*StreamingOutputCallRequest) error - Recv() (*StreamingOutputCallResponse, error) - grpc.ClientStream -} - -type testServiceHalfDuplexCallClient struct { - grpc.ClientStream -} - -func (x *testServiceHalfDuplexCallClient) Send(m *StreamingOutputCallRequest) error { - return x.ClientStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallClient) Recv() (*StreamingOutputCallResponse, error) { - m := new(StreamingOutputCallResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// TestServiceServer is the server API for TestService service. -type TestServiceServer interface { - // One empty request followed by one empty response. - EmptyCall(context.Context, *Empty) (*Empty, error) - // One request followed by one response. - // The server returns the client payload as-is. - UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - StreamingOutputCall(*StreamingOutputCallRequest, TestService_StreamingOutputCallServer) error - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - StreamingInputCall(TestService_StreamingInputCallServer) error - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - FullDuplexCall(TestService_FullDuplexCallServer) error - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - HalfDuplexCall(TestService_HalfDuplexCallServer) error -} - -func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { - s.RegisterService(&_TestService_serviceDesc, srv) -} - -func _TestService_EmptyCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Empty) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).EmptyCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/EmptyCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).EmptyCall(ctx, req.(*Empty)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SimpleRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TestServiceServer).UnaryCall(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.testing.TestService/UnaryCall", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TestServiceServer).UnaryCall(ctx, req.(*SimpleRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _TestService_StreamingOutputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(StreamingOutputCallRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(TestServiceServer).StreamingOutputCall(m, &testServiceStreamingOutputCallServer{stream}) -} - -type TestService_StreamingOutputCallServer interface { - Send(*StreamingOutputCallResponse) error - grpc.ServerStream -} - -type testServiceStreamingOutputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingOutputCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func _TestService_StreamingInputCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).StreamingInputCall(&testServiceStreamingInputCallServer{stream}) -} - -type TestService_StreamingInputCallServer interface { - SendAndClose(*StreamingInputCallResponse) error - Recv() (*StreamingInputCallRequest, error) - grpc.ServerStream -} - -type testServiceStreamingInputCallServer struct { - grpc.ServerStream -} - -func (x *testServiceStreamingInputCallServer) SendAndClose(m *StreamingInputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceStreamingInputCallServer) Recv() (*StreamingInputCallRequest, error) { - m := new(StreamingInputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_FullDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).FullDuplexCall(&testServiceFullDuplexCallServer{stream}) -} - -type TestService_FullDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceFullDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceFullDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceFullDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func _TestService_HalfDuplexCall_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(TestServiceServer).HalfDuplexCall(&testServiceHalfDuplexCallServer{stream}) -} - -type TestService_HalfDuplexCallServer interface { - Send(*StreamingOutputCallResponse) error - Recv() (*StreamingOutputCallRequest, error) - grpc.ServerStream -} - -type testServiceHalfDuplexCallServer struct { - grpc.ServerStream -} - -func (x *testServiceHalfDuplexCallServer) Send(m *StreamingOutputCallResponse) error { - return x.ServerStream.SendMsg(m) -} - -func (x *testServiceHalfDuplexCallServer) Recv() (*StreamingOutputCallRequest, error) { - m := new(StreamingOutputCallRequest) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -var _TestService_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.testing.TestService", - HandlerType: (*TestServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "EmptyCall", - Handler: _TestService_EmptyCall_Handler, - }, - { - MethodName: "UnaryCall", - Handler: _TestService_UnaryCall_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "StreamingOutputCall", - Handler: _TestService_StreamingOutputCall_Handler, - ServerStreams: true, - }, - { - StreamName: "StreamingInputCall", - Handler: _TestService_StreamingInputCall_Handler, - ClientStreams: true, - }, - { - StreamName: "FullDuplexCall", - Handler: _TestService_FullDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - { - StreamName: "HalfDuplexCall", - Handler: _TestService_HalfDuplexCall_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "grpc_testing/test.proto", -} - -func init() { proto.RegisterFile("grpc_testing/test.proto", fileDescriptor_test_c9f6c5af4267cb88) } - -var fileDescriptor_test_c9f6c5af4267cb88 = []byte{ - // 587 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0xdb, 0x6e, 0xd3, 0x40, - 0x10, 0x65, 0xdb, 0xf4, 0x36, 0x49, 0xad, 0x68, 0xab, 0xaa, 0xae, 0x8b, 0x84, 0x65, 0x1e, 0x30, - 0x48, 0xa4, 0x28, 0x08, 0x1e, 0x41, 0xa5, 0x17, 0x51, 0x29, 0x4d, 0x82, 0x9d, 0x3c, 0x47, 0xdb, - 0x64, 0x6b, 0x2c, 0x39, 0xf6, 0xb2, 0x5e, 0x57, 0xa4, 0x0f, 0xfc, 0x18, 0x3f, 0xc3, 0x47, 0xf0, - 0x01, 0x68, 0xd7, 0x76, 0xe2, 0x24, 0xae, 0x48, 0x41, 0xf0, 0x14, 0x7b, 0xe6, 0xcc, 0x99, 0x73, - 0x3c, 0xb3, 0x1b, 0x38, 0xf0, 0x38, 0x1b, 0x0e, 0x04, 0x8d, 0x85, 0x1f, 0x7a, 0xc7, 0xf2, 0xb7, - 0xc1, 0x78, 0x24, 0x22, 0x5c, 0x93, 0x89, 0x46, 0x96, 0xb0, 0xb6, 0x60, 0xe3, 0x7c, 0xcc, 0xc4, - 0xc4, 0x6a, 0xc1, 0x56, 0x97, 0x4c, 0x82, 0x88, 0x8c, 0xf0, 0x4b, 0xa8, 0x88, 0x09, 0xa3, 0x3a, - 0x32, 0x91, 0xad, 0x35, 0x0f, 0x1b, 0xc5, 0x82, 0x46, 0x06, 0xea, 0x4d, 0x18, 0x75, 0x14, 0x0c, - 0x63, 0xa8, 0x5c, 0x47, 0xa3, 0x89, 0xbe, 0x66, 0x22, 0xbb, 0xe6, 0xa8, 0x67, 0xeb, 0x27, 0x82, - 0x5d, 0xd7, 0x1f, 0xb3, 0x80, 0x3a, 0xf4, 0x4b, 0x42, 0x63, 0x81, 0xdf, 0xc1, 0x2e, 0xa7, 0x31, - 0x8b, 0xc2, 0x98, 0x0e, 0x56, 0x63, 0xaf, 0xe5, 0x78, 0xf9, 0x86, 0x9f, 0x16, 0xea, 0x63, 0xff, - 0x8e, 0xaa, 0x76, 0x1b, 0x33, 0x90, 0xeb, 0xdf, 0x51, 0x7c, 0x0c, 0x5b, 0x2c, 0x65, 0xd0, 0xd7, - 0x4d, 0x64, 0x57, 0x9b, 0xfb, 0xa5, 0xf4, 0x4e, 0x8e, 0x92, 0xac, 0x37, 0x7e, 0x10, 0x0c, 0x92, - 0x98, 0xf2, 0x90, 0x8c, 0xa9, 0x5e, 0x31, 0x91, 0xbd, 0xed, 0xd4, 0x64, 0xb0, 0x9f, 0xc5, 0xb0, - 0x0d, 0x75, 0x05, 0x8a, 0x48, 0x22, 0x3e, 0x0f, 0xe2, 0x61, 0xc4, 0xa8, 0xbe, 0xa1, 0x70, 0x9a, - 0x8c, 0x77, 0x64, 0xd8, 0x95, 0x51, 0xeb, 0x1b, 0x68, 0xb9, 0xeb, 0x54, 0x55, 0x51, 0x11, 0x5a, - 0x49, 0x91, 0x01, 0xdb, 0x53, 0x31, 0xd2, 0xe2, 0x8e, 0x33, 0x7d, 0xc7, 0x4f, 0xa0, 0x5a, 0xd4, - 0xb0, 0xae, 0xd2, 0x10, 0xcd, 0xfa, 0xb7, 0xe0, 0xd0, 0x15, 0x9c, 0x92, 0xb1, 0x1f, 0x7a, 0x97, - 0x21, 0x4b, 0xc4, 0x29, 0x09, 0x82, 0x7c, 0x02, 0x0f, 0x95, 0x62, 0xf5, 0xc0, 0x28, 0x63, 0xcb, - 0x9c, 0xbd, 0x85, 0x03, 0xe2, 0x79, 0x9c, 0x7a, 0x44, 0xd0, 0xd1, 0x20, 0xab, 0x49, 0x47, 0x83, - 0xd4, 0x68, 0xf6, 0x67, 0xe9, 0x8c, 0x5a, 0xce, 0xc8, 0xba, 0x04, 0x9c, 0x73, 0x74, 0x09, 0x27, - 0x63, 0x2a, 0x28, 0x8f, 0xe5, 0x12, 0x15, 0x4a, 0xd5, 0xb3, 0xb4, 0xeb, 0x87, 0x82, 0xf2, 0x5b, - 0x22, 0x07, 0x94, 0x0d, 0x1c, 0xf2, 0x50, 0x3f, 0xb6, 0x7e, 0xa0, 0x82, 0xc2, 0x4e, 0x22, 0x16, - 0x0c, 0xff, 0xed, 0xca, 0x7d, 0x82, 0xbd, 0x69, 0x3d, 0x9b, 0x4a, 0xd5, 0xd7, 0xcc, 0x75, 0xbb, - 0xda, 0x34, 0xe7, 0x59, 0x96, 0x2d, 0x39, 0x98, 0x2f, 0xdb, 0x7c, 0xe8, 0x82, 0x5a, 0x6d, 0x38, - 0x2a, 0x75, 0xf8, 0x87, 0xeb, 0xf5, 0xe2, 0x3d, 0x54, 0x0b, 0x86, 0x71, 0x1d, 0x6a, 0xa7, 0x9d, - 0xab, 0xae, 0x73, 0xee, 0xba, 0x27, 0x1f, 0x5a, 0xe7, 0xf5, 0x47, 0x18, 0x83, 0xd6, 0x6f, 0xcf, - 0xc5, 0x10, 0x06, 0xd8, 0x74, 0x4e, 0xda, 0x67, 0x9d, 0xab, 0xfa, 0x5a, 0xf3, 0x7b, 0x05, 0xaa, - 0x3d, 0x1a, 0x0b, 0x97, 0xf2, 0x5b, 0x7f, 0x48, 0xf1, 0x1b, 0xd8, 0x51, 0x17, 0x88, 0x94, 0x85, - 0xf7, 0xe6, 0xbb, 0xab, 0x84, 0x51, 0x16, 0xc4, 0x17, 0xb0, 0xd3, 0x0f, 0x09, 0x4f, 0xcb, 0x8e, - 0xe6, 0x11, 0x73, 0x17, 0x87, 0xf1, 0xb8, 0x3c, 0x99, 0x7d, 0x80, 0x00, 0xf6, 0x4a, 0xbe, 0x0f, - 0xb6, 0x17, 0x8a, 0xee, 0x5d, 0x12, 0xe3, 0xf9, 0x0a, 0xc8, 0xb4, 0xd7, 0x2b, 0x84, 0x7d, 0xc0, - 0xcb, 0x27, 0x02, 0x3f, 0xbb, 0x87, 0x62, 0xf1, 0x04, 0x1a, 0xf6, 0xef, 0x81, 0x69, 0x2b, 0x5b, - 0xb6, 0xd2, 0x2e, 0x92, 0x20, 0x38, 0x4b, 0x58, 0x40, 0xbf, 0xfe, 0x33, 0x4f, 0x36, 0x52, 0xae, - 0xb4, 0x8f, 0x24, 0xb8, 0xf9, 0x0f, 0xad, 0xae, 0x37, 0xd5, 0x7f, 0xd0, 0xeb, 0x5f, 0x01, 0x00, - 0x00, 0xff, 0xff, 0x07, 0xc7, 0x76, 0x69, 0x9e, 0x06, 0x00, 0x00, -} diff --git a/examples/google.golang.org/grpc/test/grpc_testing/test.proto b/examples/google.golang.org/grpc/test/grpc_testing/test.proto deleted file mode 100755 index 6f62f3a..0000000 --- a/examples/google.golang.org/grpc/test/grpc_testing/test.proto +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2017 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// An integration test service that covers all the method signature permutations -// of unary/streaming requests/responses. -syntax = "proto3"; - -package grpc.testing; - -message Empty {} - -// The type of payload that should be returned. -enum PayloadType { - // Compressable text format. - COMPRESSABLE = 0; - - // Uncompressable binary format. - UNCOMPRESSABLE = 1; - - // Randomly chosen from all other formats defined in this enum. - RANDOM = 2; -} - -// A block of data, to simply increase gRPC message size. -message Payload { - // The type of data in body. - PayloadType type = 1; - // Primary contents of payload. - bytes body = 2; -} - -// Unary request. -message SimpleRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, server randomly chooses one from other formats. - PayloadType response_type = 1; - - // Desired payload size in the response from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 response_size = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; - - // Whether SimpleResponse should include username. - bool fill_username = 4; - - // Whether SimpleResponse should include OAuth scope. - bool fill_oauth_scope = 5; -} - -// Unary response, as configured by the request. -message SimpleResponse { - // Payload to increase message size. - Payload payload = 1; - - // The user the request came from, for verifying authentication was - // successful when the client expected it. - string username = 2; - - // OAuth scope. - string oauth_scope = 3; -} - -// Client-streaming request. -message StreamingInputCallRequest { - // Optional input payload sent along with the request. - Payload payload = 1; - - // Not expecting any payload from the response. -} - -// Client-streaming response. -message StreamingInputCallResponse { - // Aggregated size of payloads received from the client. - int32 aggregated_payload_size = 1; -} - -// Configuration for a particular response. -message ResponseParameters { - // Desired payload sizes in responses from the server. - // If response_type is COMPRESSABLE, this denotes the size before compression. - int32 size = 1; - - // Desired interval between consecutive responses in the response stream in - // microseconds. - int32 interval_us = 2; -} - -// Server-streaming request. -message StreamingOutputCallRequest { - // Desired payload type in the response from the server. - // If response_type is RANDOM, the payload from each response in the stream - // might be of different types. This is to simulate a mixed type of payload - // stream. - PayloadType response_type = 1; - - // Configuration for each expected response message. - repeated ResponseParameters response_parameters = 2; - - // Optional input payload sent along with the request. - Payload payload = 3; -} - -// Server-streaming response, as configured by the request and parameters. -message StreamingOutputCallResponse { - // Payload to increase response size. - Payload payload = 1; -} - -// A simple service to test the various types of RPCs and experiment with -// performance with various types of payload. -service TestService { - // One empty request followed by one empty response. - rpc EmptyCall(Empty) returns (Empty); - - // One request followed by one response. - // The server returns the client payload as-is. - rpc UnaryCall(SimpleRequest) returns (SimpleResponse); - - // One request followed by a sequence of responses (streamed download). - // The server returns the payload with client desired type and sizes. - rpc StreamingOutputCall(StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by one response (streamed upload). - // The server returns the aggregated size of client payload as the result. - rpc StreamingInputCall(stream StreamingInputCallRequest) - returns (StreamingInputCallResponse); - - // A sequence of requests with each request served by the server immediately. - // As one request could lead to multiple responses, this interface - // demonstrates the idea of full duplexing. - rpc FullDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); - - // A sequence of requests followed by a sequence of responses. - // The server buffers all the client requests and then serves them in order. A - // stream of responses are returned to the client when the server starts with - // first request. - rpc HalfDuplexCall(stream StreamingOutputCallRequest) - returns (stream StreamingOutputCallResponse); -} diff --git a/examples/google.golang.org/grpc/test/race.go b/examples/google.golang.org/grpc/test/race.go deleted file mode 100755 index acfa0df..0000000 --- a/examples/google.golang.org/grpc/test/race.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build race - -/* - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package test - -func init() { - raceMode = true -} diff --git a/examples/google.golang.org/grpc/test/rawConnWrapper.go b/examples/google.golang.org/grpc/test/rawConnWrapper.go deleted file mode 100755 index 8d4ee02..0000000 --- a/examples/google.golang.org/grpc/test/rawConnWrapper.go +++ /dev/null @@ -1,345 +0,0 @@ -/* - * 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. - */ - -package test - -import ( - "bytes" - "fmt" - "io" - "net" - "strings" - "sync" - "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -type listenerWrapper struct { - net.Listener - mu sync.Mutex - rcw *rawConnWrapper -} - -func listenWithConnControl(network, address string) (net.Listener, error) { - l, err := net.Listen(network, address) - if err != nil { - return nil, err - } - return &listenerWrapper{Listener: l}, nil -} - -// Accept blocks until Dial is called, then returns a net.Conn for the server -// half of the connection. -func (l *listenerWrapper) Accept() (net.Conn, error) { - c, err := l.Listener.Accept() - if err != nil { - return nil, err - } - l.mu.Lock() - l.rcw = newRawConnWrapperFromConn(c) - l.mu.Unlock() - return c, nil -} - -func (l *listenerWrapper) getLastConn() *rawConnWrapper { - l.mu.Lock() - defer l.mu.Unlock() - return l.rcw -} - -type dialerWrapper struct { - c net.Conn - rcw *rawConnWrapper -} - -func (d *dialerWrapper) dialer(target string, t time.Duration) (net.Conn, error) { - c, err := net.DialTimeout("tcp", target, t) - d.c = c - d.rcw = newRawConnWrapperFromConn(c) - return c, err -} - -func (d *dialerWrapper) getRawConnWrapper() *rawConnWrapper { - return d.rcw -} - -type rawConnWrapper struct { - cc io.ReadWriteCloser - fr *http2.Framer - - // writing headers: - headerBuf bytes.Buffer - hpackEnc *hpack.Encoder - - // reading frames: - frc chan http2.Frame - frErrc chan error - readTimer *time.Timer -} - -func newRawConnWrapperFromConn(cc io.ReadWriteCloser) *rawConnWrapper { - rcw := &rawConnWrapper{ - cc: cc, - frc: make(chan http2.Frame, 1), - frErrc: make(chan error, 1), - } - rcw.hpackEnc = hpack.NewEncoder(&rcw.headerBuf) - rcw.fr = http2.NewFramer(cc, cc) - rcw.fr.ReadMetaHeaders = hpack.NewDecoder(4096 /*initialHeaderTableSize*/, nil) - - return rcw -} - -func (rcw *rawConnWrapper) Close() error { - return rcw.cc.Close() -} - -func (rcw *rawConnWrapper) readFrame() (http2.Frame, error) { - go func() { - fr, err := rcw.fr.ReadFrame() - if err != nil { - rcw.frErrc <- err - } else { - rcw.frc <- fr - } - }() - t := time.NewTimer(2 * time.Second) - defer t.Stop() - select { - case f := <-rcw.frc: - return f, nil - case err := <-rcw.frErrc: - return nil, err - case <-t.C: - return nil, fmt.Errorf("timeout waiting for frame") - } -} - -// greet initiates the client's HTTP/2 connection into a state where -// frames may be sent. -func (rcw *rawConnWrapper) greet() error { - rcw.writePreface() - rcw.writeInitialSettings() - rcw.wantSettings() - rcw.writeSettingsAck() - for { - f, err := rcw.readFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *http2.WindowUpdateFrame: - // grpc's transport/http2_server sends this - // before the settings ack. The Go http2 - // server uses a setting instead. - case *http2.SettingsFrame: - if f.IsAck() { - return nil - } - return fmt.Errorf("during greet, got non-ACK settings frame") - default: - return fmt.Errorf("during greet, unexpected frame type %T", f) - } - } -} - -func (rcw *rawConnWrapper) writePreface() error { - n, err := rcw.cc.Write([]byte(http2.ClientPreface)) - if err != nil { - return fmt.Errorf("Error writing client preface: %v", err) - } - if n != len(http2.ClientPreface) { - return fmt.Errorf("Writing client preface, wrote %d bytes; want %d", n, len(http2.ClientPreface)) - } - return nil -} - -func (rcw *rawConnWrapper) writeInitialSettings() error { - if err := rcw.fr.WriteSettings(); err != nil { - return fmt.Errorf("Error writing initial SETTINGS frame from client to server: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeSettingsAck() error { - if err := rcw.fr.WriteSettingsAck(); err != nil { - return fmt.Errorf("Error writing ACK of server's SETTINGS: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) wantSettings() (*http2.SettingsFrame, error) { - f, err := rcw.readFrame() - if err != nil { - return nil, fmt.Errorf("Error while expecting a SETTINGS frame: %v", err) - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - return nil, fmt.Errorf("got a %T; want *SettingsFrame", f) - } - return sf, nil -} - -func (rcw *rawConnWrapper) wantSettingsAck() error { - f, err := rcw.readFrame() - if err != nil { - return err - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - return fmt.Errorf("Wanting a settings ACK, received a %T", f) - } - if !sf.IsAck() { - return fmt.Errorf("Settings Frame didn't have ACK set") - } - return nil -} - -// wait for any activity from the server -func (rcw *rawConnWrapper) wantAnyFrame() (http2.Frame, error) { - f, err := rcw.fr.ReadFrame() - if err != nil { - return nil, err - } - return f, nil -} - -func (rcw *rawConnWrapper) encodeHeaderField(k, v string) error { - err := rcw.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - return fmt.Errorf("HPACK encoding error for %q/%q: %v", k, v, err) - } - return nil -} - -// encodeHeader encodes headers and returns their HPACK bytes. headers -// must contain an even number of key/value pairs. There may be -// multiple pairs for keys (e.g. "cookie"). The :method, :path, and -// :scheme headers default to GET, / and https. -func (rcw *rawConnWrapper) encodeHeader(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - - rcw.headerBuf.Reset() - - if len(headers) == 0 { - // Fast path, mostly for benchmarks, so test code doesn't pollute - // profiles when we're looking to improve server allocations. - rcw.encodeHeaderField(":method", "GET") - rcw.encodeHeaderField(":path", "/") - rcw.encodeHeaderField(":scheme", "https") - return rcw.headerBuf.Bytes() - } - - if len(headers) == 2 && headers[0] == ":method" { - // Another fast path for benchmarks. - rcw.encodeHeaderField(":method", headers[1]) - rcw.encodeHeaderField(":path", "/") - rcw.encodeHeaderField(":scheme", "https") - return rcw.headerBuf.Bytes() - } - - pseudoCount := map[string]int{} - keys := []string{":method", ":path", ":scheme"} - vals := map[string][]string{ - ":method": {"GET"}, - ":path": {"/"}, - ":scheme": {"https"}, - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if _, ok := vals[k]; !ok { - keys = append(keys, k) - } - if strings.HasPrefix(k, ":") { - pseudoCount[k]++ - if pseudoCount[k] == 1 { - vals[k] = []string{v} - } else { - // Allows testing of invalid headers w/ dup pseudo fields. - vals[k] = append(vals[k], v) - } - } else { - vals[k] = append(vals[k], v) - } - } - for _, k := range keys { - for _, v := range vals[k] { - rcw.encodeHeaderField(k, v) - } - } - return rcw.headerBuf.Bytes() -} - -func (rcw *rawConnWrapper) writeHeadersGRPC(streamID uint32, path string) { - rcw.writeHeaders(http2.HeadersFrameParam{ - StreamID: streamID, - BlockFragment: rcw.encodeHeader( - ":method", "POST", - ":path", path, - "content-type", "application/grpc", - "te", "trailers", - ), - EndStream: false, - EndHeaders: true, - }) -} - -func (rcw *rawConnWrapper) writeHeaders(p http2.HeadersFrameParam) error { - if err := rcw.fr.WriteHeaders(p); err != nil { - return fmt.Errorf("Error writing HEADERS: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeData(streamID uint32, endStream bool, data []byte) error { - if err := rcw.fr.WriteData(streamID, endStream, data); err != nil { - return fmt.Errorf("Error writing DATA: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeRSTStream(streamID uint32, code http2.ErrCode) error { - if err := rcw.fr.WriteRSTStream(streamID, code); err != nil { - return fmt.Errorf("Error writing RST_STREAM: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeDataPadded(streamID uint32, endStream bool, data, padding []byte) error { - if err := rcw.fr.WriteDataPadded(streamID, endStream, data, padding); err != nil { - return fmt.Errorf("Error writing DATA with padding: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeGoAway(maxStreamID uint32, code http2.ErrCode, debugData []byte) error { - if err := rcw.fr.WriteGoAway(maxStreamID, code, debugData); err != nil { - return fmt.Errorf("Error writing GoAway: %v", err) - } - return nil -} - -func (rcw *rawConnWrapper) writeRawFrame(t http2.FrameType, flags http2.Flags, streamID uint32, payload []byte) error { - if err := rcw.fr.WriteRawFrame(t, flags, streamID, payload); err != nil { - return fmt.Errorf("Error writing Raw Frame: %v", err) - } - return nil -} diff --git a/examples/google.golang.org/grpc/test/servertester.go b/examples/google.golang.org/grpc/test/servertester.go deleted file mode 100755 index daeca06..0000000 --- a/examples/google.golang.org/grpc/test/servertester.go +++ /dev/null @@ -1,280 +0,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. - */ - -package test - -import ( - "bytes" - "errors" - "io" - "strings" - "testing" - "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -// This is a subset of http2's serverTester type. -// -// serverTester wraps a io.ReadWriter (acting like the underlying -// network connection) and provides utility methods to read and write -// http2 frames. -// -// NOTE(bradfitz): this could eventually be exported somewhere. Others -// have asked for it too. For now I'm still experimenting with the -// API and don't feel like maintaining a stable testing API. - -type serverTester struct { - cc io.ReadWriteCloser // client conn - t testing.TB - fr *http2.Framer - - // writing headers: - headerBuf bytes.Buffer - hpackEnc *hpack.Encoder - - // reading frames: - frc chan http2.Frame - frErrc chan error - readTimer *time.Timer -} - -func newServerTesterFromConn(t testing.TB, cc io.ReadWriteCloser) *serverTester { - st := &serverTester{ - t: t, - cc: cc, - frc: make(chan http2.Frame, 1), - frErrc: make(chan error, 1), - } - st.hpackEnc = hpack.NewEncoder(&st.headerBuf) - st.fr = http2.NewFramer(cc, cc) - st.fr.ReadMetaHeaders = hpack.NewDecoder(4096 /*initialHeaderTableSize*/, nil) - - return st -} - -func (st *serverTester) readFrame() (http2.Frame, error) { - go func() { - fr, err := st.fr.ReadFrame() - if err != nil { - st.frErrc <- err - } else { - st.frc <- fr - } - }() - t := time.NewTimer(2 * time.Second) - defer t.Stop() - select { - case f := <-st.frc: - return f, nil - case err := <-st.frErrc: - return nil, err - case <-t.C: - return nil, errors.New("timeout waiting for frame") - } -} - -// greet initiates the client's HTTP/2 connection into a state where -// frames may be sent. -func (st *serverTester) greet() { - st.writePreface() - st.writeInitialSettings() - st.wantSettings() - st.writeSettingsAck() - for { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - switch f := f.(type) { - case *http2.WindowUpdateFrame: - // grpc's transport/http2_server sends this - // before the settings ack. The Go http2 - // server uses a setting instead. - case *http2.SettingsFrame: - if f.IsAck() { - return - } - st.t.Fatalf("during greet, got non-ACK settings frame") - default: - st.t.Fatalf("during greet, unexpected frame type %T", f) - } - } -} - -func (st *serverTester) writePreface() { - n, err := st.cc.Write([]byte(http2.ClientPreface)) - if err != nil { - st.t.Fatalf("Error writing client preface: %v", err) - } - if n != len(http2.ClientPreface) { - st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(http2.ClientPreface)) - } -} - -func (st *serverTester) writeInitialSettings() { - if err := st.fr.WriteSettings(); err != nil { - st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) - } -} - -func (st *serverTester) writeSettingsAck() { - if err := st.fr.WriteSettingsAck(); err != nil { - st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) - } -} - -func (st *serverTester) wantSettings() *http2.SettingsFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - st.t.Fatalf("got a %T; want *SettingsFrame", f) - } - return sf -} - -func (st *serverTester) wantSettingsAck() { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - sf, ok := f.(*http2.SettingsFrame) - if !ok { - st.t.Fatalf("Wanting a settings ACK, received a %T", f) - } - if !sf.IsAck() { - st.t.Fatal("Settings Frame didn't have ACK set") - } -} - -// wait for any activity from the server -func (st *serverTester) wantAnyFrame() http2.Frame { - f, err := st.fr.ReadFrame() - if err != nil { - st.t.Fatal(err) - } - return f -} - -func (st *serverTester) encodeHeaderField(k, v string) { - err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } -} - -// encodeHeader encodes headers and returns their HPACK bytes. headers -// must contain an even number of key/value pairs. There may be -// multiple pairs for keys (e.g. "cookie"). The :method, :path, and -// :scheme headers default to GET, / and https. -func (st *serverTester) encodeHeader(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - - st.headerBuf.Reset() - - if len(headers) == 0 { - // Fast path, mostly for benchmarks, so test code doesn't pollute - // profiles when we're looking to improve server allocations. - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - return st.headerBuf.Bytes() - } - - if len(headers) == 2 && headers[0] == ":method" { - // Another fast path for benchmarks. - st.encodeHeaderField(":method", headers[1]) - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - return st.headerBuf.Bytes() - } - - pseudoCount := map[string]int{} - keys := []string{":method", ":path", ":scheme"} - vals := map[string][]string{ - ":method": {"GET"}, - ":path": {"/"}, - ":scheme": {"https"}, - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if _, ok := vals[k]; !ok { - keys = append(keys, k) - } - if strings.HasPrefix(k, ":") { - pseudoCount[k]++ - if pseudoCount[k] == 1 { - vals[k] = []string{v} - } else { - // Allows testing of invalid headers w/ dup pseudo fields. - vals[k] = append(vals[k], v) - } - } else { - vals[k] = append(vals[k], v) - } - } - for _, k := range keys { - for _, v := range vals[k] { - st.encodeHeaderField(k, v) - } - } - return st.headerBuf.Bytes() -} - -func (st *serverTester) writeHeadersGRPC(streamID uint32, path string) { - st.writeHeaders(http2.HeadersFrameParam{ - StreamID: streamID, - BlockFragment: st.encodeHeader( - ":method", "POST", - ":path", path, - "content-type", "application/grpc", - "te", "trailers", - ), - EndStream: false, - EndHeaders: true, - }) -} - -func (st *serverTester) writeHeaders(p http2.HeadersFrameParam) { - if err := st.fr.WriteHeaders(p); err != nil { - st.t.Fatalf("Error writing HEADERS: %v", err) - } -} - -func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { - if err := st.fr.WriteData(streamID, endStream, data); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func (st *serverTester) writeRSTStream(streamID uint32, code http2.ErrCode) { - if err := st.fr.WriteRSTStream(streamID, code); err != nil { - st.t.Fatalf("Error writing RST_STREAM: %v", err) - } -} - -func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, padding []byte) { - if err := st.fr.WriteDataPadded(streamID, endStream, data, padding); err != nil { - st.t.Fatalf("Error writing DATA with padding: %v", err) - } -} diff --git a/examples/google.golang.org/grpc/testdata/ca.pem b/examples/google.golang.org/grpc/testdata/ca.pem deleted file mode 100755 index 6c8511a..0000000 --- a/examples/google.golang.org/grpc/testdata/ca.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICSjCCAbOgAwIBAgIJAJHGGR4dGioHMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxDzANBgNVBAMTBnRlc3RjYTAeFw0xNDExMTEyMjMxMjla -Fw0yNDExMDgyMjMxMjlaMFYxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0 -YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMT -BnRlc3RjYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwEDfBV5MYdlHVHJ7 -+L4nxrZy7mBfAVXpOc5vMYztssUI7mL2/iYujiIXM+weZYNTEpLdjyJdu7R5gGUu -g1jSVK/EPHfc74O7AyZU34PNIP4Sh33N+/A5YexrNgJlPY+E3GdVYi4ldWJjgkAd -Qah2PH5ACLrIIC6tRka9hcaBlIECAwEAAaMgMB4wDAYDVR0TBAUwAwEB/zAOBgNV -HQ8BAf8EBAMCAgQwDQYJKoZIhvcNAQELBQADgYEAHzC7jdYlzAVmddi/gdAeKPau -sPBG/C2HCWqHzpCUHcKuvMzDVkY/MP2o6JIW2DBbY64bO/FceExhjcykgaYtCH/m -oIU63+CFOTtR7otyQAWHqXa7q4SbCDlG7DyRFxqG0txPtGvy12lgldA2+RgcigQG -Dfcog5wrJytaQ6UA0wE= ------END CERTIFICATE----- diff --git a/examples/google.golang.org/grpc/testdata/server1.key b/examples/google.golang.org/grpc/testdata/server1.key deleted file mode 100755 index 143a5b8..0000000 --- a/examples/google.golang.org/grpc/testdata/server1.key +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOHDFScoLCVJpYDD -M4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1BgzkWF+slf -3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd9N8YwbBY -AckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAECgYAn7qGnM2vbjJNBm0VZCkOkTIWm -V10okw7EPJrdL2mkre9NasghNXbE1y5zDshx5Nt3KsazKOxTT8d0Jwh/3KbaN+YY -tTCbKGW0pXDRBhwUHRcuRzScjli8Rih5UOCiZkhefUTcRb6xIhZJuQy71tjaSy0p -dHZRmYyBYO2YEQ8xoQJBAPrJPhMBkzmEYFtyIEqAxQ/o/A6E+E4w8i+KM7nQCK7q -K4JXzyXVAjLfyBZWHGM2uro/fjqPggGD6QH1qXCkI4MCQQDmdKeb2TrKRh5BY1LR -81aJGKcJ2XbcDu6wMZK4oqWbTX2KiYn9GB0woM6nSr/Y6iy1u145YzYxEV/iMwff -DJULAkB8B2MnyzOg0pNFJqBJuH29bKCcHa8gHJzqXhNO5lAlEbMK95p/P2Wi+4Hd -aiEIAF1BF326QJcvYKmwSmrORp85AkAlSNxRJ50OWrfMZnBgzVjDx3xG6KsFQVk2 -ol6VhqL6dFgKUORFUWBvnKSyhjJxurlPEahV6oo6+A+mPhFY8eUvAkAZQyTdupP3 -XEFQKctGz+9+gKkemDp7LBBMEMBXrGTLPhpEfcjv/7KPdnFHYmhYeBTBnuVmTVWe -F98XJ7tIFfJq ------END PRIVATE KEY----- diff --git a/examples/google.golang.org/grpc/testdata/server1.pem b/examples/google.golang.org/grpc/testdata/server1.pem deleted file mode 100755 index f3d43fc..0000000 --- a/examples/google.golang.org/grpc/testdata/server1.pem +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICnDCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTET -MBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQ -dHkgTHRkMQ8wDQYDVQQDEwZ0ZXN0Y2EwHhcNMTUxMTA0MDIyMDI0WhcNMjUxMTAx -MDIyMDI0WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNV -BAcTB0NoaWNhZ28xFTATBgNVBAoTDEV4YW1wbGUsIENvLjEaMBgGA1UEAxQRKi50 -ZXN0Lmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOHDFSco -LCVJpYDDM4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1Bg -zkWF+slf3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd -9N8YwbBYAckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAGjazBpMAkGA1UdEwQCMAAw -CwYDVR0PBAQDAgXgME8GA1UdEQRIMEaCECoudGVzdC5nb29nbGUuZnKCGHdhdGVy -em9vaS50ZXN0Lmdvb2dsZS5iZYISKi50ZXN0LnlvdXR1YmUuY29thwTAqAEDMA0G -CSqGSIb3DQEBCwUAA4GBAJFXVifQNub1LUP4JlnX5lXNlo8FxZ2a12AFQs+bzoJ6 -hM044EDjqyxUqSbVePK0ni3w1fHQB5rY9yYC5f8G7aqqTY1QOhoUk8ZTSTRpnkTh -y4jjdvTZeLDVBlueZUTDRmy2feY5aZIU18vFDK08dTG0A87pppuv1LNIR3loveU8 ------END CERTIFICATE----- diff --git a/examples/google.golang.org/grpc/testdata/testdata.go b/examples/google.golang.org/grpc/testdata/testdata.go deleted file mode 100755 index 5609b19..0000000 --- a/examples/google.golang.org/grpc/testdata/testdata.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package testdata - -import ( - "log" - "os" - "path/filepath" -) - -// Path returns the absolute path the given relative file or directory path, -// relative to the google.golang.org/grpc/testdata directory in the user's GOPATH. -// If rel is already absolute, it is returned unmodified. -func Path(rel string) string { - if filepath.IsAbs(rel) { - return rel - } - - v, err := goPackagePath("google.golang.org/grpc/testdata") - if err != nil { - log.Fatalf("Error finding google.golang.org/grpc/testdata directory: %v", err) - } - - return filepath.Join(v, rel) -} - -func goPackagePath(pkg string) (path string, err error) { - gp := os.Getenv("GOPATH") - if gp == "" { - return path, os.ErrNotExist - } - - for _, p := range filepath.SplitList(gp) { - dir := filepath.Join(p, "src", filepath.FromSlash(pkg)) - fi, err := os.Stat(dir) - if os.IsNotExist(err) { - continue - } - if err != nil { - return "", err - } - if !fi.IsDir() { - continue - } - return dir, nil - } - return path, os.ErrNotExist -} diff --git a/examples/google.golang.org/grpc/trace.go b/examples/google.golang.org/grpc/trace.go deleted file mode 100755 index c1c96de..0000000 --- a/examples/google.golang.org/grpc/trace.go +++ /dev/null @@ -1,113 +0,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. - * - */ - -package grpc - -import ( - "bytes" - "fmt" - "io" - "net" - "strings" - "time" - - "golang.org/x/net/trace" -) - -// EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. -// This should only be set before any RPCs are sent or received by this program. -var EnableTracing bool - -// methodFamily returns the trace family for the given method. -// It turns "/pkg.Service/GetFoo" into "pkg.Service". -func methodFamily(m string) string { - m = strings.TrimPrefix(m, "/") // remove leading slash - if i := strings.Index(m, "/"); i >= 0 { - m = m[:i] // remove everything from second slash - } - if i := strings.LastIndex(m, "."); i >= 0 { - m = m[i+1:] // cut down to last dotted component - } - return m -} - -// traceInfo contains tracing information for an RPC. -type traceInfo struct { - tr trace.Trace - firstLine firstLine -} - -// firstLine is the first line of an RPC trace. -type firstLine struct { - client bool // whether this is a client (outgoing) RPC - remoteAddr net.Addr - deadline time.Duration // may be zero -} - -func (f *firstLine) String() string { - var line bytes.Buffer - io.WriteString(&line, "RPC: ") - if f.client { - io.WriteString(&line, "to") - } else { - io.WriteString(&line, "from") - } - fmt.Fprintf(&line, " %v deadline:", f.remoteAddr) - if f.deadline != 0 { - fmt.Fprint(&line, f.deadline) - } else { - io.WriteString(&line, "none") - } - return line.String() -} - -const truncateSize = 100 - -func truncate(x string, l int) string { - if l > len(x) { - return x - } - return x[:l] -} - -// payload represents an RPC request or response payload. -type payload struct { - sent bool // whether this is an outgoing payload - msg interface{} // e.g. a proto.Message - // TODO(dsymonds): add stringifying info to codec, and limit how much we hold here? -} - -func (p payload) String() string { - if p.sent { - return truncate(fmt.Sprintf("sent: %v", p.msg), truncateSize) - } - return truncate(fmt.Sprintf("recv: %v", p.msg), truncateSize) -} - -type fmtStringer struct { - format string - a []interface{} -} - -func (f *fmtStringer) String() string { - return fmt.Sprintf(f.format, f.a...) -} - -type stringer string - -func (s stringer) String() string { return string(s) } diff --git a/examples/google.golang.org/grpc/transport/bdp_estimator.go b/examples/google.golang.org/grpc/transport/bdp_estimator.go deleted file mode 100755 index 63cd262..0000000 --- a/examples/google.golang.org/grpc/transport/bdp_estimator.go +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "sync" - "time" -) - -const ( - // bdpLimit is the maximum value the flow control windows - // will be increased to. - bdpLimit = (1 << 20) * 4 - // alpha is a constant factor used to keep a moving average - // of RTTs. - alpha = 0.9 - // If the current bdp sample is greater than or equal to - // our beta * our estimated bdp and the current bandwidth - // sample is the maximum bandwidth observed so far, we - // increase our bbp estimate by a factor of gamma. - beta = 0.66 - // To put our bdp to be smaller than or equal to twice the real BDP, - // we should multiply our current sample with 4/3, however to round things out - // we use 2 as the multiplication factor. - gamma = 2 -) - -// Adding arbitrary data to ping so that its ack can be identified. -// Easter-egg: what does the ping message say? -var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} - -type bdpEstimator struct { - // sentAt is the time when the ping was sent. - sentAt time.Time - - mu sync.Mutex - // bdp is the current bdp estimate. - bdp uint32 - // sample is the number of bytes received in one measurement cycle. - sample uint32 - // bwMax is the maximum bandwidth noted so far (bytes/sec). - bwMax float64 - // bool to keep track of the beginning of a new measurement cycle. - isSent bool - // Callback to update the window sizes. - updateFlowControl func(n uint32) - // sampleCount is the number of samples taken so far. - sampleCount uint64 - // round trip time (seconds) - rtt float64 -} - -// timesnap registers the time bdp ping was sent out so that -// network rtt can be calculated when its ack is received. -// It is called (by controller) when the bdpPing is -// being written on the wire. -func (b *bdpEstimator) timesnap(d [8]byte) { - if bdpPing.data != d { - return - } - b.sentAt = time.Now() -} - -// add adds bytes to the current sample for calculating bdp. -// It returns true only if a ping must be sent. This can be used -// by the caller (handleData) to make decision about batching -// a window update with it. -func (b *bdpEstimator) add(n uint32) bool { - b.mu.Lock() - defer b.mu.Unlock() - if b.bdp == bdpLimit { - return false - } - if !b.isSent { - b.isSent = true - b.sample = n - b.sentAt = time.Time{} - b.sampleCount++ - return true - } - b.sample += n - return false -} - -// calculate is called when an ack for a bdp ping is received. -// Here we calculate the current bdp and bandwidth sample and -// decide if the flow control windows should go up. -func (b *bdpEstimator) calculate(d [8]byte) { - // Check if the ping acked for was the bdp ping. - if bdpPing.data != d { - return - } - b.mu.Lock() - rttSample := time.Since(b.sentAt).Seconds() - if b.sampleCount < 10 { - // Bootstrap rtt with an average of first 10 rtt samples. - b.rtt += (rttSample - b.rtt) / float64(b.sampleCount) - } else { - // Heed to the recent past more. - b.rtt += (rttSample - b.rtt) * float64(alpha) - } - b.isSent = false - // The number of bytes accumulated so far in the sample is smaller - // than or equal to 1.5 times the real BDP on a saturated connection. - bwCurrent := float64(b.sample) / (b.rtt * float64(1.5)) - if bwCurrent > b.bwMax { - b.bwMax = bwCurrent - } - // If the current sample (which is smaller than or equal to the 1.5 times the real BDP) is - // greater than or equal to 2/3rd our perceived bdp AND this is the maximum bandwidth seen so far, we - // should update our perception of the network BDP. - if float64(b.sample) >= beta*float64(b.bdp) && bwCurrent == b.bwMax && b.bdp != bdpLimit { - sampleFloat := float64(b.sample) - b.bdp = uint32(gamma * sampleFloat) - if b.bdp > bdpLimit { - b.bdp = bdpLimit - } - bdp := b.bdp - b.mu.Unlock() - b.updateFlowControl(bdp) - return - } - b.mu.Unlock() -} diff --git a/examples/google.golang.org/grpc/transport/controlbuf.go b/examples/google.golang.org/grpc/transport/controlbuf.go deleted file mode 100755 index 5c5891a..0000000 --- a/examples/google.golang.org/grpc/transport/controlbuf.go +++ /dev/null @@ -1,796 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "bytes" - "fmt" - "runtime" - "sync" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" -) - -var updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { - e.SetMaxDynamicTableSizeLimit(v) -} - -type itemNode struct { - it interface{} - next *itemNode -} - -type itemList struct { - head *itemNode - tail *itemNode -} - -func (il *itemList) enqueue(i interface{}) { - n := &itemNode{it: i} - if il.tail == nil { - il.head, il.tail = n, n - return - } - il.tail.next = n - il.tail = n -} - -// peek returns the first item in the list without removing it from the -// list. -func (il *itemList) peek() interface{} { - return il.head.it -} - -func (il *itemList) dequeue() interface{} { - if il.head == nil { - return nil - } - i := il.head.it - il.head = il.head.next - if il.head == nil { - il.tail = nil - } - return i -} - -func (il *itemList) dequeueAll() *itemNode { - h := il.head - il.head, il.tail = nil, nil - return h -} - -func (il *itemList) isEmpty() bool { - return il.head == nil -} - -// The following defines various control items which could flow through -// the control buffer of transport. They represent different aspects of -// control tasks, e.g., flow control, settings, streaming resetting, etc. - -// registerStream is used to register an incoming stream with loopy writer. -type registerStream struct { - streamID uint32 - wq *writeQuota -} - -// headerFrame is also used to register stream on the client-side. -type headerFrame struct { - streamID uint32 - hf []hpack.HeaderField - endStream bool // Valid on server side. - initStream func(uint32) (bool, error) // Used only on the client side. - onWrite func() - wq *writeQuota // write quota for the stream created. - cleanup *cleanupStream // Valid on the server side. - onOrphaned func(error) // Valid on client-side -} - -type cleanupStream struct { - streamID uint32 - idPtr *uint32 - rst bool - rstCode http2.ErrCode - onWrite func() -} - -type dataFrame struct { - streamID uint32 - endStream bool - h []byte - d []byte - // onEachWrite is called every time - // a part of d is written out. - onEachWrite func() -} - -type incomingWindowUpdate struct { - streamID uint32 - increment uint32 -} - -type outgoingWindowUpdate struct { - streamID uint32 - increment uint32 -} - -type incomingSettings struct { - ss []http2.Setting -} - -type outgoingSettings struct { - ss []http2.Setting -} - -type settingsAck struct { -} - -type incomingGoAway struct { -} - -type goAway struct { - code http2.ErrCode - debugData []byte - headsUp bool - closeConn bool -} - -type ping struct { - ack bool - data [8]byte -} - -type outFlowControlSizeRequest struct { - resp chan uint32 -} - -type outStreamState int - -const ( - active outStreamState = iota - empty - waitingOnStreamQuota -) - -type outStream struct { - id uint32 - state outStreamState - itl *itemList - bytesOutStanding int - wq *writeQuota - - next *outStream - prev *outStream -} - -func (s *outStream) deleteSelf() { - if s.prev != nil { - s.prev.next = s.next - } - if s.next != nil { - s.next.prev = s.prev - } - s.next, s.prev = nil, nil -} - -type outStreamList struct { - // Following are sentinel objects that mark the - // beginning and end of the list. They do not - // contain any item lists. All valid objects are - // inserted in between them. - // This is needed so that an outStream object can - // deleteSelf() in O(1) time without knowing which - // list it belongs to. - head *outStream - tail *outStream -} - -func newOutStreamList() *outStreamList { - head, tail := new(outStream), new(outStream) - head.next = tail - tail.prev = head - return &outStreamList{ - head: head, - tail: tail, - } -} - -func (l *outStreamList) enqueue(s *outStream) { - e := l.tail.prev - e.next = s - s.prev = e - s.next = l.tail - l.tail.prev = s -} - -// remove from the beginning of the list. -func (l *outStreamList) dequeue() *outStream { - b := l.head.next - if b == l.tail { - return nil - } - b.deleteSelf() - return b -} - -type controlBuffer struct { - ch chan struct{} - done <-chan struct{} - mu sync.Mutex - consumerWaiting bool - list *itemList - err error -} - -func newControlBuffer(done <-chan struct{}) *controlBuffer { - return &controlBuffer{ - ch: make(chan struct{}, 1), - list: &itemList{}, - done: done, - } -} - -func (c *controlBuffer) put(it interface{}) error { - _, err := c.executeAndPut(nil, it) - return err -} - -func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it interface{}) (bool, error) { - var wakeUp bool - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return false, c.err - } - if f != nil { - if !f(it) { // f wasn't successful - c.mu.Unlock() - return false, nil - } - } - if c.consumerWaiting { - wakeUp = true - c.consumerWaiting = false - } - c.list.enqueue(it) - c.mu.Unlock() - if wakeUp { - select { - case c.ch <- struct{}{}: - default: - } - } - return true, nil -} - -func (c *controlBuffer) get(block bool) (interface{}, error) { - for { - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return nil, c.err - } - if !c.list.isEmpty() { - h := c.list.dequeue() - c.mu.Unlock() - return h, nil - } - if !block { - c.mu.Unlock() - return nil, nil - } - c.consumerWaiting = true - c.mu.Unlock() - select { - case <-c.ch: - case <-c.done: - c.finish() - return nil, ErrConnClosing - } - } -} - -func (c *controlBuffer) finish() { - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return - } - c.err = ErrConnClosing - // There may be headers for streams in the control buffer. - // These streams need to be cleaned out since the transport - // is still not aware of these yet. - for head := c.list.dequeueAll(); head != nil; head = head.next { - hdr, ok := head.it.(*headerFrame) - if !ok { - continue - } - if hdr.onOrphaned != nil { // It will be nil on the server-side. - hdr.onOrphaned(ErrConnClosing) - } - } - c.mu.Unlock() -} - -type side int - -const ( - clientSide side = iota - serverSide -) - -type loopyWriter struct { - side side - cbuf *controlBuffer - sendQuota uint32 - oiws uint32 // outbound initial window size. - estdStreams map[uint32]*outStream // Established streams. - activeStreams *outStreamList // Streams that are sending data. - framer *framer - hBuf *bytes.Buffer // The buffer for HPACK encoding. - hEnc *hpack.Encoder // HPACK encoder. - bdpEst *bdpEstimator - draining bool - - // Side-specific handlers - ssGoAwayHandler func(*goAway) (bool, error) -} - -func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter { - var buf bytes.Buffer - l := &loopyWriter{ - side: s, - cbuf: cbuf, - sendQuota: defaultWindowSize, - oiws: defaultWindowSize, - estdStreams: make(map[uint32]*outStream), - activeStreams: newOutStreamList(), - framer: fr, - hBuf: &buf, - hEnc: hpack.NewEncoder(&buf), - bdpEst: bdpEst, - } - return l -} - -const minBatchSize = 1000 - -// run should be run in a separate goroutine. -func (l *loopyWriter) run() (err error) { - defer func() { - if err == ErrConnClosing { - // Don't log ErrConnClosing as error since it happens - // 1. When the connection is closed by some other known issue. - // 2. User closed the connection. - // 3. A graceful close of connection. - infof("transport: loopyWriter.run returning. %v", err) - err = nil - } - }() - for { - it, err := l.cbuf.get(true) - if err != nil { - return err - } - if err = l.handle(it); err != nil { - return err - } - if _, err = l.processData(); err != nil { - return err - } - gosched := true - hasdata: - for { - it, err := l.cbuf.get(false) - if err != nil { - return err - } - if it != nil { - if err = l.handle(it); err != nil { - return err - } - if _, err = l.processData(); err != nil { - return err - } - continue hasdata - } - isEmpty, err := l.processData() - if err != nil { - return err - } - if !isEmpty { - continue hasdata - } - if gosched { - gosched = false - if l.framer.writer.offset < minBatchSize { - runtime.Gosched() - continue hasdata - } - } - l.framer.writer.Flush() - break hasdata - - } - } -} - -func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error { - return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment) -} - -func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error { - // Otherwise update the quota. - if w.streamID == 0 { - l.sendQuota += w.increment - return nil - } - // Find the stream and update it. - if str, ok := l.estdStreams[w.streamID]; ok { - str.bytesOutStanding -= int(w.increment) - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota { - str.state = active - l.activeStreams.enqueue(str) - return nil - } - } - return nil -} - -func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { - return l.framer.fr.WriteSettings(s.ss...) -} - -func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { - if err := l.applySettings(s.ss); err != nil { - return err - } - return l.framer.fr.WriteSettingsAck() -} - -func (l *loopyWriter) registerStreamHandler(h *registerStream) error { - str := &outStream{ - id: h.streamID, - state: empty, - itl: &itemList{}, - wq: h.wq, - } - l.estdStreams[h.streamID] = str - return nil -} - -func (l *loopyWriter) headerHandler(h *headerFrame) error { - if l.side == serverSide { - str, ok := l.estdStreams[h.streamID] - if !ok { - warningf("transport: loopy doesn't recognize the stream: %d", h.streamID) - return nil - } - // Case 1.A: Server is responding back with headers. - if !h.endStream { - return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) - } - // else: Case 1.B: Server wants to close stream. - - if str.state != empty { // either active or waiting on stream quota. - // add it str's list of items. - str.itl.enqueue(h) - return nil - } - if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { - return err - } - return l.cleanupStreamHandler(h.cleanup) - } - // Case 2: Client wants to originate stream. - str := &outStream{ - id: h.streamID, - state: empty, - itl: &itemList{}, - wq: h.wq, - } - str.itl.enqueue(h) - return l.originateStream(str) -} - -func (l *loopyWriter) originateStream(str *outStream) error { - hdr := str.itl.dequeue().(*headerFrame) - sendPing, err := hdr.initStream(str.id) - if err != nil { - if err == ErrConnClosing { - return err - } - // Other errors(errStreamDrain) need not close transport. - return nil - } - if err = l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { - return err - } - l.estdStreams[str.id] = str - if sendPing { - return l.pingHandler(&ping{data: [8]byte{}}) - } - return nil -} - -func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error { - if onWrite != nil { - onWrite() - } - l.hBuf.Reset() - for _, f := range hf { - if err := l.hEnc.WriteField(f); err != nil { - warningf("transport: loopyWriter.writeHeader encountered error while encoding headers:", err) - } - } - var ( - err error - endHeaders, first bool - ) - first = true - for !endHeaders { - size := l.hBuf.Len() - if size > http2MaxFrameLen { - size = http2MaxFrameLen - } else { - endHeaders = true - } - if first { - first = false - err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{ - StreamID: streamID, - BlockFragment: l.hBuf.Next(size), - EndStream: endStream, - EndHeaders: endHeaders, - }) - } else { - err = l.framer.fr.WriteContinuation( - streamID, - endHeaders, - l.hBuf.Next(size), - ) - } - if err != nil { - return err - } - } - return nil -} - -func (l *loopyWriter) preprocessData(df *dataFrame) error { - str, ok := l.estdStreams[df.streamID] - if !ok { - return nil - } - // If we got data for a stream it means that - // stream was originated and the headers were sent out. - str.itl.enqueue(df) - if str.state == empty { - str.state = active - l.activeStreams.enqueue(str) - } - return nil -} - -func (l *loopyWriter) pingHandler(p *ping) error { - if !p.ack { - l.bdpEst.timesnap(p.data) - } - return l.framer.fr.WritePing(p.ack, p.data) - -} - -func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error { - o.resp <- l.sendQuota - return nil -} - -func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { - c.onWrite() - if str, ok := l.estdStreams[c.streamID]; ok { - // On the server side it could be a trailers-only response or - // a RST_STREAM before stream initialization thus the stream might - // not be established yet. - delete(l.estdStreams, c.streamID) - str.deleteSelf() - } - if c.rst { // If RST_STREAM needs to be sent. - if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil { - return err - } - } - if l.side == clientSide && l.draining && len(l.estdStreams) == 0 { - return ErrConnClosing - } - return nil -} - -func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { - if l.side == clientSide { - l.draining = true - if len(l.estdStreams) == 0 { - return ErrConnClosing - } - } - return nil -} - -func (l *loopyWriter) goAwayHandler(g *goAway) error { - // Handling of outgoing GoAway is very specific to side. - if l.ssGoAwayHandler != nil { - draining, err := l.ssGoAwayHandler(g) - if err != nil { - return err - } - l.draining = draining - } - return nil -} - -func (l *loopyWriter) handle(i interface{}) error { - switch i := i.(type) { - case *incomingWindowUpdate: - return l.incomingWindowUpdateHandler(i) - case *outgoingWindowUpdate: - return l.outgoingWindowUpdateHandler(i) - case *incomingSettings: - return l.incomingSettingsHandler(i) - case *outgoingSettings: - return l.outgoingSettingsHandler(i) - case *headerFrame: - return l.headerHandler(i) - case *registerStream: - return l.registerStreamHandler(i) - case *cleanupStream: - return l.cleanupStreamHandler(i) - case *incomingGoAway: - return l.incomingGoAwayHandler(i) - case *dataFrame: - return l.preprocessData(i) - case *ping: - return l.pingHandler(i) - case *goAway: - return l.goAwayHandler(i) - case *outFlowControlSizeRequest: - return l.outFlowControlSizeRequestHandler(i) - default: - return fmt.Errorf("transport: unknown control message type %T", i) - } -} - -func (l *loopyWriter) applySettings(ss []http2.Setting) error { - for _, s := range ss { - switch s.ID { - case http2.SettingInitialWindowSize: - o := l.oiws - l.oiws = s.Val - if o < l.oiws { - // If the new limit is greater make all depleted streams active. - for _, stream := range l.estdStreams { - if stream.state == waitingOnStreamQuota { - stream.state = active - l.activeStreams.enqueue(stream) - } - } - } - case http2.SettingHeaderTableSize: - updateHeaderTblSize(l.hEnc, s.Val) - } - } - return nil -} - -func (l *loopyWriter) processData() (bool, error) { - if l.sendQuota == 0 { - return true, nil - } - str := l.activeStreams.dequeue() - if str == nil { - return true, nil - } - dataItem := str.itl.peek().(*dataFrame) - if len(dataItem.h) == 0 && len(dataItem.d) == 0 { - // Client sends out empty data frame with endStream = true - if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil { - return false, err - } - str.itl.dequeue() - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, nil - } - } else { - l.activeStreams.enqueue(str) - } - return false, nil - } - var ( - idx int - buf []byte - ) - if len(dataItem.h) != 0 { // data header has not been written out yet. - buf = dataItem.h - } else { - idx = 1 - buf = dataItem.d - } - size := http2MaxFrameLen - if len(buf) < size { - size = len(buf) - } - if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { - str.state = waitingOnStreamQuota - return false, nil - } else if strQuota < size { - size = strQuota - } - - if l.sendQuota < uint32(size) { - size = int(l.sendQuota) - } - // Now that outgoing flow controls are checked we can replenish str's write quota - str.wq.replenish(size) - var endStream bool - // This last data message on this stream and all - // of it can be written in this go. - if dataItem.endStream && size == len(buf) { - // buf contains either data or it contains header but data is empty. - if idx == 1 || len(dataItem.d) == 0 { - endStream = true - } - } - if dataItem.onEachWrite != nil { - dataItem.onEachWrite() - } - if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil { - return false, err - } - buf = buf[size:] - str.bytesOutStanding += size - l.sendQuota -= uint32(size) - if idx == 0 { - dataItem.h = buf - } else { - dataItem.d = buf - } - - if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out. - str.itl.dequeue() - } - if str.itl.isEmpty() { - str.state = empty - } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. - if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { - return false, err - } - if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, err - } - } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. - str.state = waitingOnStreamQuota - } else { // Otherwise add it back to the list of active streams. - l.activeStreams.enqueue(str) - } - return false, nil -} diff --git a/examples/google.golang.org/grpc/transport/flowcontrol.go b/examples/google.golang.org/grpc/transport/flowcontrol.go deleted file mode 100755 index bbf98b6..0000000 --- a/examples/google.golang.org/grpc/transport/flowcontrol.go +++ /dev/null @@ -1,242 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "fmt" - "math" - "sync" - "sync/atomic" - "time" -) - -const ( - // The default value of flow control window size in HTTP2 spec. - defaultWindowSize = 65535 - // The initial window size for flow control. - initialWindowSize = defaultWindowSize // for an RPC - infinity = time.Duration(math.MaxInt64) - defaultClientKeepaliveTime = infinity - defaultClientKeepaliveTimeout = 20 * time.Second - defaultMaxStreamsClient = 100 - defaultMaxConnectionIdle = infinity - defaultMaxConnectionAge = infinity - defaultMaxConnectionAgeGrace = infinity - defaultServerKeepaliveTime = 2 * time.Hour - defaultServerKeepaliveTimeout = 20 * time.Second - defaultKeepalivePolicyMinTime = 5 * time.Minute - // max window limit set by HTTP2 Specs. - maxWindowSize = math.MaxInt32 - // defaultWriteQuota is the default value for number of data - // bytes that each stream can schedule before some of it being - // flushed out. - defaultWriteQuota = 64 * 1024 -) - -// writeQuota is a soft limit on the amount of data a stream can -// schedule before some of it is written out. -type writeQuota struct { - quota int32 - // get waits on read from when quota goes less than or equal to zero. - // replenish writes on it when quota goes positive again. - ch chan struct{} - // done is triggered in error case. - done <-chan struct{} - // replenish is called by loopyWriter to give quota back to. - // It is implemented as a field so that it can be updated - // by tests. - replenish func(n int) -} - -func newWriteQuota(sz int32, done <-chan struct{}) *writeQuota { - w := &writeQuota{ - quota: sz, - ch: make(chan struct{}, 1), - done: done, - } - w.replenish = w.realReplenish - return w -} - -func (w *writeQuota) get(sz int32) error { - for { - if atomic.LoadInt32(&w.quota) > 0 { - atomic.AddInt32(&w.quota, -sz) - return nil - } - select { - case <-w.ch: - continue - case <-w.done: - return errStreamDone - } - } -} - -func (w *writeQuota) realReplenish(n int) { - sz := int32(n) - a := atomic.AddInt32(&w.quota, sz) - b := a - sz - if b <= 0 && a > 0 { - select { - case w.ch <- struct{}{}: - default: - } - } -} - -type trInFlow struct { - limit uint32 - unacked uint32 - effectiveWindowSize uint32 -} - -func (f *trInFlow) newLimit(n uint32) uint32 { - d := n - f.limit - f.limit = n - f.updateEffectiveWindowSize() - return d -} - -func (f *trInFlow) onData(n uint32) uint32 { - f.unacked += n - if f.unacked >= f.limit/4 { - w := f.unacked - f.unacked = 0 - f.updateEffectiveWindowSize() - return w - } - f.updateEffectiveWindowSize() - return 0 -} - -func (f *trInFlow) reset() uint32 { - w := f.unacked - f.unacked = 0 - f.updateEffectiveWindowSize() - return w -} - -func (f *trInFlow) updateEffectiveWindowSize() { - atomic.StoreUint32(&f.effectiveWindowSize, f.limit-f.unacked) -} - -func (f *trInFlow) getSize() uint32 { - return atomic.LoadUint32(&f.effectiveWindowSize) -} - -// TODO(mmukhi): Simplify this code. -// inFlow deals with inbound flow control -type inFlow struct { - mu sync.Mutex - // The inbound flow control limit for pending data. - limit uint32 - // pendingData is the overall data which have been received but not been - // consumed by applications. - pendingData uint32 - // The amount of data the application has consumed but grpc has not sent - // window update for them. Used to reduce window update frequency. - pendingUpdate uint32 - // delta is the extra window update given by receiver when an application - // is reading data bigger in size than the inFlow limit. - delta uint32 -} - -// newLimit updates the inflow window to a new value n. -// It assumes that n is always greater than the old limit. -func (f *inFlow) newLimit(n uint32) uint32 { - f.mu.Lock() - d := n - f.limit - f.limit = n - f.mu.Unlock() - return d -} - -func (f *inFlow) maybeAdjust(n uint32) uint32 { - if n > uint32(math.MaxInt32) { - n = uint32(math.MaxInt32) - } - f.mu.Lock() - // estSenderQuota is the receiver's view of the maximum number of bytes the sender - // can send without a window update. - estSenderQuota := int32(f.limit - (f.pendingData + f.pendingUpdate)) - // estUntransmittedData is the maximum number of bytes the sends might not have put - // on the wire yet. A value of 0 or less means that we have already received all or - // more bytes than the application is requesting to read. - estUntransmittedData := int32(n - f.pendingData) // Casting into int32 since it could be negative. - // This implies that unless we send a window update, the sender won't be able to send all the bytes - // for this message. Therefore we must send an update over the limit since there's an active read - // request from the application. - if estUntransmittedData > estSenderQuota { - // Sender's window shouldn't go more than 2^31 - 1 as specified in the HTTP spec. - if f.limit+n > maxWindowSize { - f.delta = maxWindowSize - f.limit - } else { - // Send a window update for the whole message and not just the difference between - // estUntransmittedData and estSenderQuota. This will be helpful in case the message - // is padded; We will fallback on the current available window(at least a 1/4th of the limit). - f.delta = n - } - f.mu.Unlock() - return f.delta - } - f.mu.Unlock() - return 0 -} - -// onData is invoked when some data frame is received. It updates pendingData. -func (f *inFlow) onData(n uint32) error { - f.mu.Lock() - f.pendingData += n - if f.pendingData+f.pendingUpdate > f.limit+f.delta { - limit := f.limit - rcvd := f.pendingData + f.pendingUpdate - f.mu.Unlock() - return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) - } - f.mu.Unlock() - return nil -} - -// onRead is invoked when the application reads the data. It returns the window size -// to be sent to the peer. -func (f *inFlow) onRead(n uint32) uint32 { - f.mu.Lock() - if f.pendingData == 0 { - f.mu.Unlock() - return 0 - } - f.pendingData -= n - if n > f.delta { - n -= f.delta - f.delta = 0 - } else { - f.delta -= n - n = 0 - } - f.pendingUpdate += n - if f.pendingUpdate >= f.limit/4 { - wu := f.pendingUpdate - f.pendingUpdate = 0 - f.mu.Unlock() - return wu - } - f.mu.Unlock() - return 0 -} diff --git a/examples/google.golang.org/grpc/transport/go16.go b/examples/google.golang.org/grpc/transport/go16.go deleted file mode 100755 index 5babcf9..0000000 --- a/examples/google.golang.org/grpc/transport/go16.go +++ /dev/null @@ -1,51 +0,0 @@ -// +build go1.6,!go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "net" - "net/http" - - "google.golang.org/grpc/codes" - - "golang.org/x/net/context" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) -} - -// contextFromRequest returns a background context. -func contextFromRequest(r *http.Request) context.Context { - return context.Background() -} diff --git a/examples/google.golang.org/grpc/transport/go17.go b/examples/google.golang.org/grpc/transport/go17.go deleted file mode 100755 index b7fa6bd..0000000 --- a/examples/google.golang.org/grpc/transport/go17.go +++ /dev/null @@ -1,52 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "context" - "net" - "net/http" - - "google.golang.org/grpc/codes" - - netctx "golang.org/x/net/context" -) - -// dialContext connects to the address on the named network. -func dialContext(ctx context.Context, network, address string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, network, address) -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded, netctx.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled, netctx.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) -} - -// contextFromRequest returns a context from the HTTP Request. -func contextFromRequest(r *http.Request) context.Context { - return r.Context() -} diff --git a/examples/google.golang.org/grpc/transport/handler_server.go b/examples/google.golang.org/grpc/transport/handler_server.go deleted file mode 100755 index f71b748..0000000 --- a/examples/google.golang.org/grpc/transport/handler_server.go +++ /dev/null @@ -1,451 +0,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. - * - */ - -// This file is the implementation of a gRPC server using HTTP/2 which -// uses the standard Go http2 Server implementation (via the -// http.Handler interface), rather than speaking low-level HTTP/2 -// frames itself. It is the implementation of *grpc.Server.ServeHTTP. - -package transport - -import ( - "errors" - "fmt" - "io" - "net" - "net/http" - "strings" - "sync" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/net/http2" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -// NewServerHandlerTransport returns a ServerTransport handling gRPC -// from inside an http.Handler. It requires that the http Server -// supports HTTP/2. -func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats stats.Handler) (ServerTransport, error) { - if r.ProtoMajor != 2 { - return nil, errors.New("gRPC requires HTTP/2") - } - if r.Method != "POST" { - return nil, errors.New("invalid gRPC request method") - } - contentType := r.Header.Get("Content-Type") - // TODO: do we assume contentType is lowercase? we did before - contentSubtype, validContentType := contentSubtype(contentType) - if !validContentType { - return nil, errors.New("invalid gRPC request content-type") - } - if _, ok := w.(http.Flusher); !ok { - return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher") - } - if _, ok := w.(http.CloseNotifier); !ok { - return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier") - } - - st := &serverHandlerTransport{ - rw: w, - req: r, - closedCh: make(chan struct{}), - writes: make(chan func()), - contentType: contentType, - contentSubtype: contentSubtype, - stats: stats, - } - - if v := r.Header.Get("grpc-timeout"); v != "" { - to, err := decodeTimeout(v) - if err != nil { - return nil, streamErrorf(codes.Internal, "malformed time-out: %v", err) - } - st.timeoutSet = true - st.timeout = to - } - - metakv := []string{"content-type", contentType} - if r.Host != "" { - metakv = append(metakv, ":authority", r.Host) - } - for k, vv := range r.Header { - k = strings.ToLower(k) - if isReservedHeader(k) && !isWhitelistedHeader(k) { - continue - } - for _, v := range vv { - v, err := decodeMetadataHeader(k, v) - if err != nil { - return nil, streamErrorf(codes.Internal, "malformed binary metadata: %v", err) - } - metakv = append(metakv, k, v) - } - } - st.headerMD = metadata.Pairs(metakv...) - - return st, nil -} - -// serverHandlerTransport is an implementation of ServerTransport -// which replies to exactly one gRPC request (exactly one HTTP request), -// using the net/http.Handler interface. This http.Handler is guaranteed -// at this point to be speaking over HTTP/2, so it's able to speak valid -// gRPC. -type serverHandlerTransport struct { - rw http.ResponseWriter - req *http.Request - timeoutSet bool - timeout time.Duration - didCommonHeaders bool - - headerMD metadata.MD - - closeOnce sync.Once - closedCh chan struct{} // closed on Close - - // writes is a channel of code to run serialized in the - // ServeHTTP (HandleStreams) goroutine. The channel is closed - // when WriteStatus is called. - writes chan func() - - // block concurrent WriteStatus calls - // e.g. grpc/(*serverStream).SendMsg/RecvMsg - writeStatusMu sync.Mutex - - // we just mirror the request content-type - contentType string - // we store both contentType and contentSubtype so we don't keep recreating them - // TODO make sure this is consistent across handler_server and http2_server - contentSubtype string - - stats stats.Handler -} - -func (ht *serverHandlerTransport) Close() error { - ht.closeOnce.Do(ht.closeCloseChanOnce) - return nil -} - -func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) } - -func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) } - -// strAddr is a net.Addr backed by either a TCP "ip:port" string, or -// the empty string if unknown. -type strAddr string - -func (a strAddr) Network() string { - if a != "" { - // Per the documentation on net/http.Request.RemoteAddr, if this is - // set, it's set to the IP:port of the peer (hence, TCP): - // https://golang.org/pkg/net/http/#Request - // - // If we want to support Unix sockets later, we can - // add our own grpc-specific convention within the - // grpc codebase to set RemoteAddr to a different - // format, or probably better: we can attach it to the - // context and use that from serverHandlerTransport.RemoteAddr. - return "tcp" - } - return "" -} - -func (a strAddr) String() string { return string(a) } - -// do runs fn in the ServeHTTP goroutine. -func (ht *serverHandlerTransport) do(fn func()) error { - // Avoid a panic writing to closed channel. Imperfect but maybe good enough. - select { - case <-ht.closedCh: - return ErrConnClosing - default: - select { - case ht.writes <- fn: - return nil - case <-ht.closedCh: - return ErrConnClosing - } - } -} - -func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { - ht.writeStatusMu.Lock() - defer ht.writeStatusMu.Unlock() - - err := ht.do(func() { - ht.writeCommonHeaders(s) - - // And flush, in case no header or body has been sent yet. - // This forces a separation of headers and trailers if this is the - // first call (for example, in end2end tests's TestNoService). - ht.rw.(http.Flusher).Flush() - - h := ht.rw.Header() - h.Set("Grpc-Status", fmt.Sprintf("%d", st.Code())) - if m := st.Message(); m != "" { - h.Set("Grpc-Message", encodeGrpcMessage(m)) - } - - if p := st.Proto(); p != nil && len(p.Details) > 0 { - stBytes, err := proto.Marshal(p) - if err != nil { - // TODO: return error instead, when callers are able to handle it. - panic(err) - } - - h.Set("Grpc-Status-Details-Bin", encodeBinHeader(stBytes)) - } - - if md := s.Trailer(); len(md) > 0 { - for k, vv := range md { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - // http2 ResponseWriter mechanism to send undeclared Trailers after - // the headers have possibly been written. - h.Add(http2.TrailerPrefix+k, encodeMetadataHeader(k, v)) - } - } - } - }) - - if err == nil { // transport has not been closed - if ht.stats != nil { - ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) - } - ht.Close() - close(ht.writes) - } - return err -} - -// writeCommonHeaders sets common headers on the first write -// call (Write, WriteHeader, or WriteStatus). -func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { - if ht.didCommonHeaders { - return - } - ht.didCommonHeaders = true - - h := ht.rw.Header() - h["Date"] = nil // suppress Date to make tests happy; TODO: restore - h.Set("Content-Type", ht.contentType) - - // Predeclare trailers we'll set later in WriteStatus (after the body). - // This is a SHOULD in the HTTP RFC, and the way you add (known) - // Trailers per the net/http.ResponseWriter contract. - // See https://golang.org/pkg/net/http/#ResponseWriter - // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers - h.Add("Trailer", "Grpc-Status") - h.Add("Trailer", "Grpc-Message") - h.Add("Trailer", "Grpc-Status-Details-Bin") - - if s.sendCompress != "" { - h.Set("Grpc-Encoding", s.sendCompress) - } -} - -func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - return ht.do(func() { - ht.writeCommonHeaders(s) - ht.rw.Write(hdr) - ht.rw.Write(data) - if !opts.Delay { - ht.rw.(http.Flusher).Flush() - } - }) -} - -func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { - err := ht.do(func() { - ht.writeCommonHeaders(s) - h := ht.rw.Header() - for k, vv := range md { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - v = encodeMetadataHeader(k, v) - h.Add(k, v) - } - } - ht.rw.WriteHeader(200) - ht.rw.(http.Flusher).Flush() - }) - - if err == nil { - if ht.stats != nil { - ht.stats.HandleRPC(s.Context(), &stats.OutHeader{}) - } - } - return err -} - -func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { - // With this transport type there will be exactly 1 stream: this HTTP request. - - ctx := contextFromRequest(ht.req) - var cancel context.CancelFunc - if ht.timeoutSet { - ctx, cancel = context.WithTimeout(ctx, ht.timeout) - } else { - ctx, cancel = context.WithCancel(ctx) - } - - // requestOver is closed when either the request's context is done - // or the status has been written via WriteStatus. - requestOver := make(chan struct{}) - - // clientGone receives a single value if peer is gone, either - // because the underlying connection is dead or because the - // peer sends an http2 RST_STREAM. - clientGone := ht.rw.(http.CloseNotifier).CloseNotify() - go func() { - select { - case <-requestOver: - return - case <-ht.closedCh: - case <-clientGone: - } - cancel() - }() - - req := ht.req - - s := &Stream{ - id: 0, // irrelevant - requestRead: func(int) {}, - cancel: cancel, - buf: newRecvBuffer(), - st: ht, - method: req.URL.Path, - recvCompress: req.Header.Get("grpc-encoding"), - contentSubtype: ht.contentSubtype, - } - pr := &peer.Peer{ - Addr: ht.RemoteAddr(), - } - if req.TLS != nil { - pr.AuthInfo = credentials.TLSInfo{State: *req.TLS} - } - ctx = metadata.NewIncomingContext(ctx, ht.headerMD) - s.ctx = peer.NewContext(ctx, pr) - if ht.stats != nil { - s.ctx = ht.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) - inHeader := &stats.InHeader{ - FullMethod: s.method, - RemoteAddr: ht.RemoteAddr(), - Compression: s.recvCompress, - } - ht.stats.HandleRPC(s.ctx, inHeader) - } - s.trReader = &transportReader{ - reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, - windowHandler: func(int) {}, - } - - // readerDone is closed when the Body.Read-ing goroutine exits. - readerDone := make(chan struct{}) - go func() { - defer close(readerDone) - - // TODO: minimize garbage, optimize recvBuffer code/ownership - const readSize = 8196 - for buf := make([]byte, readSize); ; { - n, err := req.Body.Read(buf) - if n > 0 { - s.buf.put(recvMsg{data: buf[:n:n]}) - buf = buf[n:] - } - if err != nil { - s.buf.put(recvMsg{err: mapRecvMsgError(err)}) - return - } - if len(buf) == 0 { - buf = make([]byte, readSize) - } - } - }() - - // startStream is provided by the *grpc.Server's serveStreams. - // It starts a goroutine serving s and exits immediately. - // The goroutine that is started is the one that then calls - // into ht, calling WriteHeader, Write, WriteStatus, Close, etc. - startStream(s) - - ht.runStream() - close(requestOver) - - // Wait for reading goroutine to finish. - req.Body.Close() - <-readerDone -} - -func (ht *serverHandlerTransport) runStream() { - for { - select { - case fn, ok := <-ht.writes: - if !ok { - return - } - fn() - case <-ht.closedCh: - return - } - } -} - -func (ht *serverHandlerTransport) IncrMsgSent() {} - -func (ht *serverHandlerTransport) IncrMsgRecv() {} - -func (ht *serverHandlerTransport) Drain() { - panic("Drain() is not implemented") -} - -// mapRecvMsgError returns the non-nil err into the appropriate -// error value as expected by callers of *grpc.parser.recvMsg. -// In particular, in can only be: -// * io.EOF -// * io.ErrUnexpectedEOF -// * of type transport.ConnectionError -// * of type transport.StreamError -func mapRecvMsgError(err error) error { - if err == io.EOF || err == io.ErrUnexpectedEOF { - return err - } - if se, ok := err.(http2.StreamError); ok { - if code, ok := http2ErrConvTab[se.Code]; ok { - return StreamError{ - Code: code, - Desc: se.Error(), - } - } - } - return connectionErrorf(true, err, err.Error()) -} diff --git a/examples/google.golang.org/grpc/transport/handler_server_test.go b/examples/google.golang.org/grpc/transport/handler_server_test.go deleted file mode 100755 index 3261b8e..0000000 --- a/examples/google.golang.org/grpc/transport/handler_server_test.go +++ /dev/null @@ -1,482 +0,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. - * - */ - -package transport - -import ( - "errors" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "sync" - "testing" - "time" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -func TestHandlerTransport_NewServerHandlerTransport(t *testing.T) { - type testCase struct { - name string - req *http.Request - wantErr string - modrw func(http.ResponseWriter) http.ResponseWriter - check func(*serverHandlerTransport, *testCase) error - } - tests := []testCase{ - { - name: "http/1.1", - req: &http.Request{ - ProtoMajor: 1, - ProtoMinor: 1, - }, - wantErr: "gRPC requires HTTP/2", - }, - { - name: "bad method", - req: &http.Request{ - ProtoMajor: 2, - Method: "GET", - Header: http.Header{}, - RequestURI: "/", - }, - wantErr: "invalid gRPC request method", - }, - { - name: "bad content type", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/foo"}, - }, - RequestURI: "/service/foo.bar", - }, - wantErr: "invalid gRPC request content-type", - }, - { - name: "not flusher", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - RequestURI: "/service/foo.bar", - }, - modrw: func(w http.ResponseWriter) http.ResponseWriter { - // Return w without its Flush method - type onlyCloseNotifier interface { - http.ResponseWriter - http.CloseNotifier - } - return struct{ onlyCloseNotifier }{w.(onlyCloseNotifier)} - }, - wantErr: "gRPC requires a ResponseWriter supporting http.Flusher", - }, - { - name: "not closenotifier", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - RequestURI: "/service/foo.bar", - }, - modrw: func(w http.ResponseWriter) http.ResponseWriter { - // Return w without its CloseNotify method - type onlyFlusher interface { - http.ResponseWriter - http.Flusher - } - return struct{ onlyFlusher }{w.(onlyFlusher)} - }, - wantErr: "gRPC requires a ResponseWriter supporting http.CloseNotifier", - }, - { - name: "valid", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(t *serverHandlerTransport, tt *testCase) error { - if t.req != tt.req { - return fmt.Errorf("t.req = %p; want %p", t.req, tt.req) - } - if t.rw == nil { - return errors.New("t.rw = nil; want non-nil") - } - return nil - }, - }, - { - name: "with timeout", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "Grpc-Timeout": {"200m"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(t *serverHandlerTransport, tt *testCase) error { - if !t.timeoutSet { - return errors.New("timeout not set") - } - if want := 200 * time.Millisecond; t.timeout != want { - return fmt.Errorf("timeout = %v; want %v", t.timeout, want) - } - return nil - }, - }, - { - name: "with bad timeout", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "Grpc-Timeout": {"tomorrow"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - wantErr: `stream error: code = Internal desc = "malformed time-out: transport: timeout unit is not recognized: \"tomorrow\""`, - }, - { - name: "with metadata", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "meta-foo": {"foo-val"}, - "meta-bar": {"bar-val1", "bar-val2"}, - "user-agent": {"x/y a/b"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(ht *serverHandlerTransport, tt *testCase) error { - want := metadata.MD{ - "meta-bar": {"bar-val1", "bar-val2"}, - "user-agent": {"x/y a/b"}, - "meta-foo": {"foo-val"}, - "content-type": {"application/grpc"}, - } - - if !reflect.DeepEqual(ht.headerMD, want) { - return fmt.Errorf("metdata = %#v; want %#v", ht.headerMD, want) - } - return nil - }, - }, - } - - for _, tt := range tests { - rw := newTestHandlerResponseWriter() - if tt.modrw != nil { - rw = tt.modrw(rw) - } - got, gotErr := NewServerHandlerTransport(rw, tt.req, nil) - if (gotErr != nil) != (tt.wantErr != "") || (gotErr != nil && gotErr.Error() != tt.wantErr) { - t.Errorf("%s: error = %v; want %q", tt.name, gotErr, tt.wantErr) - continue - } - if gotErr != nil { - continue - } - if tt.check != nil { - if err := tt.check(got.(*serverHandlerTransport), &tt); err != nil { - t.Errorf("%s: %v", tt.name, err) - } - } - } -} - -type testHandlerResponseWriter struct { - *httptest.ResponseRecorder - closeNotify chan bool -} - -func (w testHandlerResponseWriter) CloseNotify() <-chan bool { return w.closeNotify } -func (w testHandlerResponseWriter) Flush() {} - -func newTestHandlerResponseWriter() http.ResponseWriter { - return testHandlerResponseWriter{ - ResponseRecorder: httptest.NewRecorder(), - closeNotify: make(chan bool, 1), - } -} - -type handleStreamTest struct { - t *testing.T - bodyw *io.PipeWriter - req *http.Request - rw testHandlerResponseWriter - ht *serverHandlerTransport -} - -func newHandleStreamTest(t *testing.T) *handleStreamTest { - bodyr, bodyw := io.Pipe() - req := &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - Body: bodyr, - } - rw := newTestHandlerResponseWriter().(testHandlerResponseWriter) - ht, err := NewServerHandlerTransport(rw, req, nil) - if err != nil { - t.Fatal(err) - } - return &handleStreamTest{ - t: t, - bodyw: bodyw, - ht: ht.(*serverHandlerTransport), - rw: rw, - } -} - -func TestHandlerTransport_HandleStreams(t *testing.T) { - st := newHandleStreamTest(t) - handleStream := func(s *Stream) { - if want := "/service/foo.bar"; s.method != want { - t.Errorf("stream method = %q; want %q", s.method, want) - } - st.bodyw.Close() // no body - st.ht.WriteStatus(s, status.New(codes.OK, "")) - } - st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {"0"}, - } - if !reflect.DeepEqual(st.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer Map: %#v; want %#v", st.rw.HeaderMap, wantHeader) - } -} - -// Tests that codes.Unimplemented will close the body, per comment in handler_server.go. -func TestHandlerTransport_HandleStreams_Unimplemented(t *testing.T) { - handleStreamCloseBodyTest(t, codes.Unimplemented, "thingy is unimplemented") -} - -// Tests that codes.InvalidArgument will close the body, per comment in handler_server.go. -func TestHandlerTransport_HandleStreams_InvalidArgument(t *testing.T) { - handleStreamCloseBodyTest(t, codes.InvalidArgument, "bad arg") -} - -func handleStreamCloseBodyTest(t *testing.T, statusCode codes.Code, msg string) { - st := newHandleStreamTest(t) - - handleStream := func(s *Stream) { - st.ht.WriteStatus(s, status.New(statusCode, msg)) - } - st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {fmt.Sprint(uint32(statusCode))}, - "Grpc-Message": {encodeGrpcMessage(msg)}, - } - - if !reflect.DeepEqual(st.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer mismatch.\n got: %#v\nwant: %#v", st.rw.HeaderMap, wantHeader) - } -} - -func TestHandlerTransport_HandleStreams_Timeout(t *testing.T) { - bodyr, bodyw := io.Pipe() - req := &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - "Grpc-Timeout": {"200m"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - Body: bodyr, - } - rw := newTestHandlerResponseWriter().(testHandlerResponseWriter) - ht, err := NewServerHandlerTransport(rw, req, nil) - if err != nil { - t.Fatal(err) - } - runStream := func(s *Stream) { - defer bodyw.Close() - select { - case <-s.ctx.Done(): - case <-time.After(5 * time.Second): - t.Errorf("timeout waiting for ctx.Done") - return - } - err := s.ctx.Err() - if err != context.DeadlineExceeded { - t.Errorf("ctx.Err = %v; want %v", err, context.DeadlineExceeded) - return - } - ht.WriteStatus(s, status.New(codes.DeadlineExceeded, "too slow")) - } - ht.HandleStreams( - func(s *Stream) { go runStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {"4"}, - "Grpc-Message": {encodeGrpcMessage("too slow")}, - } - if !reflect.DeepEqual(rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer Map mismatch.\n got: %#v\nwant: %#v", rw.HeaderMap, wantHeader) - } -} - -// TestHandlerTransport_HandleStreams_MultiWriteStatus ensures that -// concurrent "WriteStatus"s do not panic writing to closed "writes" channel. -func TestHandlerTransport_HandleStreams_MultiWriteStatus(t *testing.T) { - testHandlerTransportHandleStreams(t, func(st *handleStreamTest, s *Stream) { - if want := "/service/foo.bar"; s.method != want { - t.Errorf("stream method = %q; want %q", s.method, want) - } - st.bodyw.Close() // no body - - var wg sync.WaitGroup - wg.Add(5) - for i := 0; i < 5; i++ { - go func() { - defer wg.Done() - st.ht.WriteStatus(s, status.New(codes.OK, "")) - }() - } - wg.Wait() - }) -} - -// TestHandlerTransport_HandleStreams_WriteStatusWrite ensures that "Write" -// following "WriteStatus" does not panic writing to closed "writes" channel. -func TestHandlerTransport_HandleStreams_WriteStatusWrite(t *testing.T) { - testHandlerTransportHandleStreams(t, func(st *handleStreamTest, s *Stream) { - if want := "/service/foo.bar"; s.method != want { - t.Errorf("stream method = %q; want %q", s.method, want) - } - st.bodyw.Close() // no body - - st.ht.WriteStatus(s, status.New(codes.OK, "")) - st.ht.Write(s, []byte("hdr"), []byte("data"), &Options{}) - }) -} - -func testHandlerTransportHandleStreams(t *testing.T, handleStream func(st *handleStreamTest, s *Stream)) { - st := newHandleStreamTest(t) - st.ht.HandleStreams( - func(s *Stream) { go handleStream(st, s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) -} - -func TestHandlerTransport_HandleStreams_ErrDetails(t *testing.T) { - errDetails := []proto.Message{ - &epb.RetryInfo{ - RetryDelay: &dpb.Duration{Seconds: 60}, - }, - &epb.ResourceInfo{ - ResourceType: "foo bar", - ResourceName: "service.foo.bar", - Owner: "User", - }, - } - - statusCode := codes.ResourceExhausted - msg := "you are being throttled" - st, err := status.New(statusCode, msg).WithDetails(errDetails...) - if err != nil { - t.Fatal(err) - } - - stBytes, err := proto.Marshal(st.Proto()) - if err != nil { - t.Fatal(err) - } - - hst := newHandleStreamTest(t) - handleStream := func(s *Stream) { - hst.ht.WriteStatus(s, st) - } - hst.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {fmt.Sprint(uint32(statusCode))}, - "Grpc-Message": {encodeGrpcMessage(msg)}, - "Grpc-Status-Details-Bin": {encodeBinHeader(stBytes)}, - } - - if !reflect.DeepEqual(hst.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer mismatch.\n got: %#v\nwant: %#v", hst.rw.HeaderMap, wantHeader) - } -} diff --git a/examples/google.golang.org/grpc/transport/http2_client.go b/examples/google.golang.org/grpc/transport/http2_client.go deleted file mode 100755 index eaf007e..0000000 --- a/examples/google.golang.org/grpc/transport/http2_client.go +++ /dev/null @@ -1,1298 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "io" - "math" - "net" - "strings" - "sync" - "sync/atomic" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" -) - -// http2Client implements the ClientTransport interface with HTTP2. -type http2Client struct { - ctx context.Context - cancel context.CancelFunc - ctxDone <-chan struct{} // Cache the ctx.Done() chan. - userAgent string - md interface{} - conn net.Conn // underlying communication channel - loopy *loopyWriter - remoteAddr net.Addr - localAddr net.Addr - authInfo credentials.AuthInfo // auth info about the connection - - readerDone chan struct{} // sync point to enable testing. - writerDone chan struct{} // sync point to enable testing. - // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) - // that the server sent GoAway on this transport. - goAway chan struct{} - // awakenKeepalive is used to wake up keepalive when after it has gone dormant. - awakenKeepalive chan struct{} - - framer *framer - // controlBuf delivers all the control related tasks (e.g., window - // updates, reset streams, and various settings) to the controller. - controlBuf *controlBuffer - fc *trInFlow - // The scheme used: https if TLS is on, http otherwise. - scheme string - - isSecure bool - - creds []credentials.PerRPCCredentials - - // Boolean to keep track of reading activity on transport. - // 1 is true and 0 is false. - activity uint32 // Accessed atomically. - kp keepalive.ClientParameters - keepaliveEnabled bool - - statsHandler stats.Handler - - initialWindowSize int32 - - bdpEst *bdpEstimator - // onSuccess is a callback that client transport calls upon - // receiving server preface to signal that a succefull HTTP2 - // connection was established. - onSuccess func() - - maxConcurrentStreams uint32 - streamQuota int64 - streamsQuotaAvailable chan struct{} - waitingStreams uint32 - nextID uint32 - - mu sync.Mutex // guard the following variables - state transportState - activeStreams map[uint32]*Stream - // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame. - prevGoAwayID uint32 - // goAwayReason records the http2.ErrCode and debug data received with the - // GoAway frame. - goAwayReason GoAwayReason - - // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - kpCount int64 - // The number of streams that have started, including already finished ones. - streamsStarted int64 - // The number of streams that have ended successfully by receiving EoS bit set - // frame from server. - streamsSucceeded int64 - streamsFailed int64 - lastStreamCreated time.Time - msgSent int64 - msgRecv int64 - lastMsgSent time.Time - lastMsgRecv time.Time -} - -func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) { - if fn != nil { - return fn(ctx, addr) - } - return dialContext(ctx, "tcp", addr) -} - -func isTemporary(err error) bool { - switch err := err.(type) { - case interface { - Temporary() bool - }: - return err.Temporary() - case interface { - Timeout() bool - }: - // Timeouts may be resolved upon retry, and are thus treated as - // temporary. - return err.Timeout() - } - return true -} - -// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 -// and starts to receive messages on it. Non-nil error returns if construction -// fails. -func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onSuccess func()) (_ ClientTransport, err error) { - scheme := "http" - ctx, cancel := context.WithCancel(ctx) - defer func() { - if err != nil { - cancel() - } - }() - - conn, err := dial(connectCtx, opts.Dialer, addr.Addr) - if err != nil { - if opts.FailOnNonTempDialError { - return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err) - } - return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err) - } - // Any further errors will close the underlying connection - defer func(conn net.Conn) { - if err != nil { - conn.Close() - } - }(conn) - var ( - isSecure bool - authInfo credentials.AuthInfo - ) - if creds := opts.TransportCredentials; creds != nil { - scheme = "https" - conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn) - if err != nil { - return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) - } - isSecure = true - } - kp := opts.KeepaliveParams - // Validate keepalive parameters. - if kp.Time == 0 { - kp.Time = defaultClientKeepaliveTime - } - if kp.Timeout == 0 { - kp.Timeout = defaultClientKeepaliveTimeout - } - dynamicWindow := true - icwz := int32(initialWindowSize) - if opts.InitialConnWindowSize >= defaultWindowSize { - icwz = opts.InitialConnWindowSize - dynamicWindow = false - } - writeBufSize := defaultWriteBufSize - if opts.WriteBufferSize > 0 { - writeBufSize = opts.WriteBufferSize - } - readBufSize := defaultReadBufSize - if opts.ReadBufferSize > 0 { - readBufSize = opts.ReadBufferSize - } - t := &http2Client{ - ctx: ctx, - ctxDone: ctx.Done(), // Cache Done chan. - cancel: cancel, - userAgent: opts.UserAgent, - md: addr.Metadata, - conn: conn, - remoteAddr: conn.RemoteAddr(), - localAddr: conn.LocalAddr(), - authInfo: authInfo, - readerDone: make(chan struct{}), - writerDone: make(chan struct{}), - goAway: make(chan struct{}), - awakenKeepalive: make(chan struct{}, 1), - framer: newFramer(conn, writeBufSize, readBufSize), - fc: &trInFlow{limit: uint32(icwz)}, - scheme: scheme, - activeStreams: make(map[uint32]*Stream), - isSecure: isSecure, - creds: opts.PerRPCCredentials, - kp: kp, - statsHandler: opts.StatsHandler, - initialWindowSize: initialWindowSize, - onSuccess: onSuccess, - nextID: 1, - maxConcurrentStreams: defaultMaxStreamsClient, - streamQuota: defaultMaxStreamsClient, - streamsQuotaAvailable: make(chan struct{}, 1), - } - t.controlBuf = newControlBuffer(t.ctxDone) - if opts.InitialWindowSize >= defaultWindowSize { - t.initialWindowSize = opts.InitialWindowSize - dynamicWindow = false - } - if dynamicWindow { - t.bdpEst = &bdpEstimator{ - bdp: initialWindowSize, - updateFlowControl: t.updateFlowControl, - } - } - // Make sure awakenKeepalive can't be written upon. - // keepalive routine will make it writable, if need be. - t.awakenKeepalive <- struct{}{} - if t.statsHandler != nil { - t.ctx = t.statsHandler.TagConn(t.ctx, &stats.ConnTagInfo{ - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - }) - connBegin := &stats.ConnBegin{ - Client: true, - } - t.statsHandler.HandleConn(t.ctx, connBegin) - } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, "") - } - if t.kp.Time != infinity { - t.keepaliveEnabled = true - go t.keepalive() - } - // Start the reader goroutine for incoming message. Each transport has - // a dedicated goroutine which reads HTTP2 frame from network. Then it - // dispatches the frame to the corresponding stream entity. - go t.reader() - // Send connection preface to server. - n, err := t.conn.Write(clientPreface) - if err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write client preface: %v", err) - } - if n != len(clientPreface) { - t.Close() - return nil, connectionErrorf(true, err, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface)) - } - if t.initialWindowSize != defaultWindowSize { - err = t.framer.fr.WriteSettings(http2.Setting{ - ID: http2.SettingInitialWindowSize, - Val: uint32(t.initialWindowSize), - }) - } else { - err = t.framer.fr.WriteSettings() - } - if err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err) - } - // Adjust the connection flow control window if needed. - if delta := uint32(icwz - defaultWindowSize); delta > 0 { - if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil { - t.Close() - return nil, connectionErrorf(true, err, "transport: failed to write window update: %v", err) - } - } - t.framer.writer.Flush() - go func() { - t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) - err := t.loopy.run() - if err != nil { - errorf("transport: loopyWriter.run returning. Err: %v", err) - } - // If it's a connection error, let reader goroutine handle it - // since there might be data in the buffers. - if _, ok := err.(net.Error); !ok { - t.conn.Close() - } - close(t.writerDone) - }() - return t, nil -} - -func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { - // TODO(zhaoq): Handle uint32 overflow of Stream.id. - s := &Stream{ - done: make(chan struct{}), - method: callHdr.Method, - sendCompress: callHdr.SendCompress, - buf: newRecvBuffer(), - headerChan: make(chan struct{}), - contentSubtype: callHdr.ContentSubtype, - } - s.wq = newWriteQuota(defaultWriteQuota, s.done) - s.requestRead = func(n int) { - t.adjustWindow(s, uint32(n)) - } - // The client side stream context should have exactly the same life cycle with the user provided context. - // That means, s.ctx should be read-only. And s.ctx is done iff ctx is done. - // So we use the original context here instead of creating a copy. - s.ctx = ctx - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - ctxDone: s.ctx.Done(), - recv: s.buf, - }, - windowHandler: func(n int) { - t.updateWindow(s, uint32(n)) - }, - } - return s -} - -func (t *http2Client) getPeer() *peer.Peer { - pr := &peer.Peer{ - Addr: t.remoteAddr, - } - // Attach Auth info if there is any. - if t.authInfo != nil { - pr.AuthInfo = t.authInfo - } - return pr -} - -func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { - aud := t.createAudience(callHdr) - authData, err := t.getTrAuthData(ctx, aud) - if err != nil { - return nil, err - } - callAuthData, err := t.getCallAuthData(ctx, aud, callHdr) - if err != nil { - return nil, err - } - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - // Make the slice of certain predictable size to reduce allocations made by append. - hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te - hfLen += len(authData) + len(callAuthData) - headerFields := make([]hpack.HeaderField, 0, hfLen) - headerFields = append(headerFields, hpack.HeaderField{Name: ":method", Value: "POST"}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method}) - headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)}) - headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent}) - headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"}) - - if callHdr.SendCompress != "" { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress}) - } - if dl, ok := ctx.Deadline(); ok { - // Send out timeout regardless its value. The server can detect timeout context by itself. - // TODO(mmukhi): Perhaps this field should be updated when actually writing out to the wire. - timeout := dl.Sub(time.Now()) - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-timeout", Value: encodeTimeout(timeout)}) - } - for k, v := range authData { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - for k, v := range callAuthData { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - if b := stats.OutgoingTags(ctx); b != nil { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-tags-bin", Value: encodeBinHeader(b)}) - } - if b := stats.OutgoingTrace(ctx); b != nil { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)}) - } - - if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok { - var k string - for _, vv := range added { - for i, v := range vv { - if i%2 == 0 { - k = v - continue - } - // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. - if isReservedHeader(k) { - continue - } - headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)}) - } - } - for k, vv := range md { - // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - } - if md, ok := t.md.(*metadata.MD); ok { - for k, vv := range *md { - if isReservedHeader(k) { - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - } - return headerFields, nil -} - -func (t *http2Client) createAudience(callHdr *CallHdr) string { - // Create an audience string only if needed. - if len(t.creds) == 0 && callHdr.Creds == nil { - return "" - } - // Construct URI required to get auth request metadata. - // Omit port if it is the default one. - host := strings.TrimSuffix(callHdr.Host, ":443") - pos := strings.LastIndex(callHdr.Method, "/") - if pos == -1 { - pos = len(callHdr.Method) - } - return "https://" + host + callHdr.Method[:pos] -} - -func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { - authData := map[string]string{} - for _, c := range t.creds { - data, err := c.GetRequestMetadata(ctx, audience) - if err != nil { - if _, ok := status.FromError(err); ok { - return nil, err - } - - return nil, streamErrorf(codes.Unauthenticated, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2. - k = strings.ToLower(k) - authData[k] = v - } - } - return authData, nil -} - -func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { - callAuthData := map[string]string{} - // Check if credentials.PerRPCCredentials were provided via call options. - // Note: if these credentials are provided both via dial options and call - // options, then both sets of credentials will be applied. - if callCreds := callHdr.Creds; callCreds != nil { - if !t.isSecure && callCreds.RequireTransportSecurity() { - return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") - } - data, err := callCreds.GetRequestMetadata(ctx, audience) - if err != nil { - return nil, streamErrorf(codes.Internal, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2 - k = strings.ToLower(k) - callAuthData[k] = v - } - } - return callAuthData, nil -} - -// NewStream creates a stream and registers it into the transport as "active" -// streams. -func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { - ctx = peer.NewContext(ctx, t.getPeer()) - headerFields, err := t.createHeaderFields(ctx, callHdr) - if err != nil { - return nil, err - } - s := t.newStream(ctx, callHdr) - cleanup := func(err error) { - if s.swapState(streamDone) == streamDone { - // If it was already done, return. - return - } - // The stream was unprocessed by the server. - atomic.StoreUint32(&s.unprocessed, 1) - s.write(recvMsg{err: err}) - close(s.done) - // If headerChan isn't closed, then close it. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - close(s.headerChan) - } - - } - hdr := &headerFrame{ - hf: headerFields, - endStream: false, - initStream: func(id uint32) (bool, error) { - t.mu.Lock() - if state := t.state; state != reachable { - t.mu.Unlock() - // Do a quick cleanup. - err := error(errStreamDrain) - if state == closing { - err = ErrConnClosing - } - cleanup(err) - return false, err - } - t.activeStreams[id] = s - if channelz.IsOn() { - t.czmu.Lock() - t.streamsStarted++ - t.lastStreamCreated = time.Now() - t.czmu.Unlock() - } - var sendPing bool - // If the number of active streams change from 0 to 1, then check if keepalive - // has gone dormant. If so, wake it up. - if len(t.activeStreams) == 1 && t.keepaliveEnabled { - select { - case t.awakenKeepalive <- struct{}{}: - sendPing = true - // Fill the awakenKeepalive channel again as this channel must be - // kept non-writable except at the point that the keepalive() - // goroutine is waiting either to be awaken or shutdown. - t.awakenKeepalive <- struct{}{} - default: - } - } - t.mu.Unlock() - return sendPing, nil - }, - onOrphaned: cleanup, - wq: s.wq, - } - firstTry := true - var ch chan struct{} - checkForStreamQuota := func(it interface{}) bool { - if t.streamQuota <= 0 { // Can go negative if server decreases it. - if firstTry { - t.waitingStreams++ - } - ch = t.streamsQuotaAvailable - return false - } - if !firstTry { - t.waitingStreams-- - } - t.streamQuota-- - h := it.(*headerFrame) - h.streamID = t.nextID - t.nextID += 2 - s.id = h.streamID - s.fc = &inFlow{limit: uint32(t.initialWindowSize)} - if t.streamQuota > 0 && t.waitingStreams > 0 { - select { - case t.streamsQuotaAvailable <- struct{}{}: - default: - } - } - return true - } - for { - success, err := t.controlBuf.executeAndPut(checkForStreamQuota, hdr) - if err != nil { - return nil, err - } - if success { - break - } - firstTry = false - select { - case <-ch: - case <-s.ctx.Done(): - return nil, ContextErr(s.ctx.Err()) - case <-t.goAway: - return nil, errStreamDrain - case <-t.ctx.Done(): - return nil, ErrConnClosing - } - } - if t.statsHandler != nil { - outHeader := &stats.OutHeader{ - Client: true, - FullMethod: callHdr.Method, - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - Compression: callHdr.SendCompress, - } - t.statsHandler.HandleRPC(s.ctx, outHeader) - } - return s, nil -} - -// CloseStream clears the footprint of a stream when the stream is not needed any more. -// This must not be executed in reader's goroutine. -func (t *http2Client) CloseStream(s *Stream, err error) { - var ( - rst bool - rstCode http2.ErrCode - ) - if err != nil { - rst = true - rstCode = http2.ErrCodeCancel - } - t.closeStream(s, err, rst, rstCode, nil, nil, false) -} - -func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { - // Set stream status to done. - if s.swapState(streamDone) == streamDone { - // If it was already done, return. - return - } - // status and trailers can be updated here without any synchronization because the stream goroutine will - // only read it after it sees an io.EOF error from read or write and we'll write those errors - // only after updating this. - s.status = st - if len(mdata) > 0 { - s.trailer = mdata - } - if err != nil { - // This will unblock reads eventually. - s.write(recvMsg{err: err}) - } - // This will unblock write. - close(s.done) - // If headerChan isn't closed, then close it. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - close(s.headerChan) - } - cleanup := &cleanupStream{ - streamID: s.id, - onWrite: func() { - t.mu.Lock() - if t.activeStreams != nil { - delete(t.activeStreams, s.id) - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - if eosReceived { - t.streamsSucceeded++ - } else { - t.streamsFailed++ - } - t.czmu.Unlock() - } - }, - rst: rst, - rstCode: rstCode, - } - addBackStreamQuota := func(interface{}) bool { - t.streamQuota++ - if t.streamQuota > 0 && t.waitingStreams > 0 { - select { - case t.streamsQuotaAvailable <- struct{}{}: - default: - } - } - return true - } - t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) -} - -// Close kicks off the shutdown process of the transport. This should be called -// only once on a transport. Once it is called, the transport should not be -// accessed any more. -func (t *http2Client) Close() error { - t.mu.Lock() - // Make sure we only Close once. - if t.state == closing { - t.mu.Unlock() - return nil - } - t.state = closing - streams := t.activeStreams - t.activeStreams = nil - t.mu.Unlock() - t.controlBuf.finish() - t.cancel() - err := t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } - // Notify all active streams. - for _, s := range streams { - t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, nil, nil, false) - } - if t.statsHandler != nil { - connEnd := &stats.ConnEnd{ - Client: true, - } - t.statsHandler.HandleConn(t.ctx, connEnd) - } - return err -} - -// GracefulClose sets the state to draining, which prevents new streams from -// being created and causes the transport to be closed when the last active -// stream is closed. If there are no active streams, the transport is closed -// immediately. This does nothing if the transport is already draining or -// closing. -func (t *http2Client) GracefulClose() error { - t.mu.Lock() - // Make sure we move to draining only from active. - if t.state == draining || t.state == closing { - t.mu.Unlock() - return nil - } - t.state = draining - active := len(t.activeStreams) - t.mu.Unlock() - if active == 0 { - return t.Close() - } - t.controlBuf.put(&incomingGoAway{}) - return nil -} - -// Write formats the data into HTTP2 data frame(s) and sends it out. The caller -// should proceed only if Write returns nil. -func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - if opts.Last { - // If it's the last message, update stream state. - if !s.compareAndSwapState(streamActive, streamWriteDone) { - return errStreamDone - } - } else if s.getState() != streamActive { - return errStreamDone - } - df := &dataFrame{ - streamID: s.id, - endStream: opts.Last, - } - if hdr != nil || data != nil { // If it's not an empty data frame. - // Add some data to grpc message header so that we can equally - // distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - df.h, df.d = hdr, data - // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. - if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { - return err - } - } - return t.controlBuf.put(df) -} - -func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) { - t.mu.Lock() - defer t.mu.Unlock() - s, ok := t.activeStreams[f.Header().StreamID] - return s, ok -} - -// adjustWindow sends out extra window update over the initial window size -// of stream if the application is requesting data larger in size than -// the window. -func (t *http2Client) adjustWindow(s *Stream, n uint32) { - if w := s.fc.maybeAdjust(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } -} - -// updateWindow adjusts the inbound quota for the stream. -// Window updates will be sent out when the cumulative quota -// exceeds the corresponding threshold. -func (t *http2Client) updateWindow(s *Stream, n uint32) { - if w := s.fc.onRead(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } -} - -// updateFlowControl updates the incoming flow control windows -// for the transport and the stream based on the current bdp -// estimation. -func (t *http2Client) updateFlowControl(n uint32) { - t.mu.Lock() - for _, s := range t.activeStreams { - s.fc.newLimit(n) - } - t.mu.Unlock() - updateIWS := func(interface{}) bool { - t.initialWindowSize = int32(n) - return true - } - t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)}) - t.controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingInitialWindowSize, - Val: n, - }, - }, - }) -} - -func (t *http2Client) handleData(f *http2.DataFrame) { - size := f.Header().Length - var sendBDPPing bool - if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(size) - } - // Decouple connection's flow control from application's read. - // An update on connection's flow control should not depend on - // whether user application has read the data or not. Such a - // restriction is already imposed on the stream's flow control, - // and therefore the sender will be blocked anyways. - // Decoupling the connection flow control will prevent other - // active(fast) streams from starving in presence of slow or - // inactive streams. - // - if w := t.fc.onData(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - if sendBDPPing { - // Avoid excessive ping detection (e.g. in an L7 proxy) - // by sending a window update prior to the BDP ping. - - if w := t.fc.reset(); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - - t.controlBuf.put(bdpPing) - } - // Select the right stream to dispatch. - s, ok := t.getStream(f) - if !ok { - return - } - if size > 0 { - if err := s.fc.onData(size); err != nil { - t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) - return - } - if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) - } - } - // TODO(bradfitz, zhaoq): A copy is required here because there is no - // guarantee f.Data() is consumed before the arrival of next frame. - // Can this copy be eliminated? - if len(f.Data()) > 0 { - data := make([]byte, len(f.Data())) - copy(data, f.Data()) - s.write(recvMsg{data: data}) - } - } - // The server has closed the stream without sending trailers. Record that - // the read direction is closed, and set the status appropriately. - if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) - } -} - -func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { - s, ok := t.getStream(f) - if !ok { - return - } - if f.ErrCode == http2.ErrCodeRefusedStream { - // The stream was unprocessed by the server. - atomic.StoreUint32(&s.unprocessed, 1) - } - statusCode, ok := http2ErrConvTab[f.ErrCode] - if !ok { - warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) - statusCode = codes.Unknown - } - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false) -} - -func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { - if f.IsAck() { - return - } - var maxStreams *uint32 - var ss []http2.Setting - f.ForeachSetting(func(s http2.Setting) error { - if s.ID == http2.SettingMaxConcurrentStreams { - maxStreams = new(uint32) - *maxStreams = s.Val - return nil - } - ss = append(ss, s) - return nil - }) - if isFirst && maxStreams == nil { - maxStreams = new(uint32) - *maxStreams = math.MaxUint32 - } - sf := &incomingSettings{ - ss: ss, - } - if maxStreams == nil { - t.controlBuf.put(sf) - return - } - updateStreamQuota := func(interface{}) bool { - delta := int64(*maxStreams) - int64(t.maxConcurrentStreams) - t.maxConcurrentStreams = *maxStreams - t.streamQuota += delta - if delta > 0 && t.waitingStreams > 0 { - close(t.streamsQuotaAvailable) // wake all of them up. - t.streamsQuotaAvailable = make(chan struct{}, 1) - } - return true - } - t.controlBuf.executeAndPut(updateStreamQuota, sf) -} - -func (t *http2Client) handlePing(f *http2.PingFrame) { - if f.IsAck() { - // Maybe it's a BDP ping. - if t.bdpEst != nil { - t.bdpEst.calculate(f.Data) - } - return - } - pingAck := &ping{ack: true} - copy(pingAck.data[:], f.Data[:]) - t.controlBuf.put(pingAck) -} - -func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { - t.mu.Lock() - if t.state == closing { - t.mu.Unlock() - return - } - if f.ErrCode == http2.ErrCodeEnhanceYourCalm { - infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.") - } - id := f.LastStreamID - if id > 0 && id%2 != 1 { - t.mu.Unlock() - t.Close() - return - } - // A client can receive multiple GoAways from the server (see - // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first - // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be - // sent after an RTT delay with the ID of the last stream the server will - // process. - // - // Therefore, when we get the first GoAway we don't necessarily close any - // streams. While in case of second GoAway we close all streams created after - // the GoAwayId. This way streams that were in-flight while the GoAway from - // server was being sent don't get killed. - select { - case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). - // If there are multiple GoAways the first one should always have an ID greater than the following ones. - if id > t.prevGoAwayID { - t.mu.Unlock() - t.Close() - return - } - default: - t.setGoAwayReason(f) - close(t.goAway) - t.state = draining - t.controlBuf.put(&incomingGoAway{}) - } - // All streams with IDs greater than the GoAwayId - // and smaller than the previous GoAway ID should be killed. - upperLimit := t.prevGoAwayID - if upperLimit == 0 { // This is the first GoAway Frame. - upperLimit = math.MaxUint32 // Kill all streams after the GoAway ID. - } - for streamID, stream := range t.activeStreams { - if streamID > id && streamID <= upperLimit { - // The stream was unprocessed by the server. - atomic.StoreUint32(&stream.unprocessed, 1) - t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false) - } - } - t.prevGoAwayID = id - active := len(t.activeStreams) - t.mu.Unlock() - if active == 0 { - t.Close() - } -} - -// setGoAwayReason sets the value of t.goAwayReason based -// on the GoAway frame received. -// It expects a lock on transport's mutext to be held by -// the caller. -func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { - t.goAwayReason = GoAwayNoReason - switch f.ErrCode { - case http2.ErrCodeEnhanceYourCalm: - if string(f.DebugData()) == "too_many_pings" { - t.goAwayReason = GoAwayTooManyPings - } - } -} - -func (t *http2Client) GetGoAwayReason() GoAwayReason { - t.mu.Lock() - defer t.mu.Unlock() - return t.goAwayReason -} - -func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) { - t.controlBuf.put(&incomingWindowUpdate{ - streamID: f.Header().StreamID, - increment: f.Increment, - }) -} - -// operateHeaders takes action on the decoded headers. -func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { - s, ok := t.getStream(frame) - if !ok { - return - } - atomic.StoreUint32(&s.bytesReceived, 1) - var state decodeState - if err := state.decodeResponseHeader(frame); err != nil { - t.closeStream(s, err, true, http2.ErrCodeProtocol, nil, nil, false) - // Something wrong. Stops reading even when there is remaining. - return - } - - endStream := frame.StreamEnded() - var isHeader bool - defer func() { - if t.statsHandler != nil { - if isHeader { - inHeader := &stats.InHeader{ - Client: true, - WireLength: int(frame.Header().Length), - } - t.statsHandler.HandleRPC(s.ctx, inHeader) - } else { - inTrailer := &stats.InTrailer{ - Client: true, - WireLength: int(frame.Header().Length), - } - t.statsHandler.HandleRPC(s.ctx, inTrailer) - } - } - }() - // If headers haven't been received yet. - if atomic.SwapUint32(&s.headerDone, 1) == 0 { - if !endStream { - // Headers frame is not actually a trailers-only frame. - isHeader = true - // These values can be set without any synchronization because - // stream goroutine will read it only after seeing a closed - // headerChan which we'll close after setting this. - s.recvCompress = state.encoding - if len(state.mdata) > 0 { - s.header = state.mdata - } - } - close(s.headerChan) - } - if !endStream { - return - } - t.closeStream(s, io.EOF, false, http2.ErrCodeNo, state.status(), state.mdata, true) -} - -// reader runs as a separate goroutine in charge of reading data from network -// connection. -// -// TODO(zhaoq): currently one reader per transport. Investigate whether this is -// optimal. -// TODO(zhaoq): Check the validity of the incoming frame sequence. -func (t *http2Client) reader() { - defer close(t.readerDone) - // Check the validity of server preface. - frame, err := t.framer.fr.ReadFrame() - if err != nil { - t.Close() - return - } - if t.keepaliveEnabled { - atomic.CompareAndSwapUint32(&t.activity, 0, 1) - } - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - t.Close() - return - } - t.onSuccess() - t.handleSettings(sf, true) - - // loop to keep reading incoming messages on this transport. - for { - frame, err := t.framer.fr.ReadFrame() - if t.keepaliveEnabled { - atomic.CompareAndSwapUint32(&t.activity, 0, 1) - } - if err != nil { - // Abort an active stream if the http2.Framer returns a - // http2.StreamError. This can happen only if the server's response - // is malformed http2. - if se, ok := err.(http2.StreamError); ok { - t.mu.Lock() - s := t.activeStreams[se.StreamID] - t.mu.Unlock() - if s != nil { - // use error detail to provide better err message - t.closeStream(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail()), true, http2.ErrCodeProtocol, nil, nil, false) - } - continue - } else { - // Transport error. - t.Close() - return - } - } - switch frame := frame.(type) { - case *http2.MetaHeadersFrame: - t.operateHeaders(frame) - case *http2.DataFrame: - t.handleData(frame) - case *http2.RSTStreamFrame: - t.handleRSTStream(frame) - case *http2.SettingsFrame: - t.handleSettings(frame, false) - case *http2.PingFrame: - t.handlePing(frame) - case *http2.GoAwayFrame: - t.handleGoAway(frame) - case *http2.WindowUpdateFrame: - t.handleWindowUpdate(frame) - default: - errorf("transport: http2Client.reader got unhandled frame type %v.", frame) - } - } -} - -// keepalive running in a separate goroutune makes sure the connection is alive by sending pings. -func (t *http2Client) keepalive() { - p := &ping{data: [8]byte{}} - timer := time.NewTimer(t.kp.Time) - for { - select { - case <-timer.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - timer.Reset(t.kp.Time) - continue - } - // Check if keepalive should go dormant. - t.mu.Lock() - if len(t.activeStreams) < 1 && !t.kp.PermitWithoutStream { - // Make awakenKeepalive writable. - <-t.awakenKeepalive - t.mu.Unlock() - select { - case <-t.awakenKeepalive: - // If the control gets here a ping has been sent - // need to reset the timer with keepalive.Timeout. - case <-t.ctx.Done(): - return - } - } else { - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - t.kpCount++ - t.czmu.Unlock() - } - // Send ping. - t.controlBuf.put(p) - } - - // By the time control gets here a ping has been sent one way or the other. - timer.Reset(t.kp.Timeout) - select { - case <-timer.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - timer.Reset(t.kp.Time) - continue - } - t.Close() - return - case <-t.ctx.Done(): - if !timer.Stop() { - <-timer.C - } - return - } - case <-t.ctx.Done(): - if !timer.Stop() { - <-timer.C - } - return - } - } -} - -func (t *http2Client) Error() <-chan struct{} { - return t.ctx.Done() -} - -func (t *http2Client) GoAway() <-chan struct{} { - return t.goAway -} - -func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric { - t.czmu.RLock() - s := channelz.SocketInternalMetric{ - StreamsStarted: t.streamsStarted, - StreamsSucceeded: t.streamsSucceeded, - StreamsFailed: t.streamsFailed, - MessagesSent: t.msgSent, - MessagesReceived: t.msgRecv, - KeepAlivesSent: t.kpCount, - LastLocalStreamCreatedTimestamp: t.lastStreamCreated, - LastMessageSentTimestamp: t.lastMsgSent, - LastMessageReceivedTimestamp: t.lastMsgRecv, - LocalFlowControlWindow: int64(t.fc.getSize()), - //socket options - LocalAddr: t.localAddr, - RemoteAddr: t.remoteAddr, - // Security - // RemoteName : - } - t.czmu.RUnlock() - s.RemoteFlowControlWindow = t.getOutFlowWindow() - return &s -} - -func (t *http2Client) IncrMsgSent() { - t.czmu.Lock() - t.msgSent++ - t.lastMsgSent = time.Now() - t.czmu.Unlock() -} - -func (t *http2Client) IncrMsgRecv() { - t.czmu.Lock() - t.msgRecv++ - t.lastMsgRecv = time.Now() - t.czmu.Unlock() -} - -func (t *http2Client) getOutFlowWindow() int64 { - resp := make(chan uint32, 1) - timer := time.NewTimer(time.Second) - defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) - select { - case sz := <-resp: - return int64(sz) - case <-t.ctxDone: - return -1 - case <-timer.C: - return -2 - } -} diff --git a/examples/google.golang.org/grpc/transport/http2_server.go b/examples/google.golang.org/grpc/transport/http2_server.go deleted file mode 100755 index 19acedb..0000000 --- a/examples/google.golang.org/grpc/transport/http2_server.go +++ /dev/null @@ -1,1142 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "bytes" - "errors" - "fmt" - "io" - "math" - "net" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/internal/grpcrand" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" -) - -// ErrIllegalHeaderWrite indicates that setting header is illegal because of -// the stream's state. -var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHeader was already called") - -// http2Server implements the ServerTransport interface with HTTP2. -type http2Server struct { - ctx context.Context - ctxDone <-chan struct{} // Cache the context.Done() chan - cancel context.CancelFunc - conn net.Conn - loopy *loopyWriter - readerDone chan struct{} // sync point to enable testing. - writerDone chan struct{} // sync point to enable testing. - remoteAddr net.Addr - localAddr net.Addr - maxStreamID uint32 // max stream ID ever seen - authInfo credentials.AuthInfo // auth info about the connection - inTapHandle tap.ServerInHandle - framer *framer - // The max number of concurrent streams. - maxStreams uint32 - // controlBuf delivers all the control related tasks (e.g., window - // updates, reset streams, and various settings) to the controller. - controlBuf *controlBuffer - fc *trInFlow - stats stats.Handler - // Flag to keep track of reading activity on transport. - // 1 is true and 0 is false. - activity uint32 // Accessed atomically. - // Keepalive and max-age parameters for the server. - kp keepalive.ServerParameters - - // Keepalive enforcement policy. - kep keepalive.EnforcementPolicy - // The time instance last ping was received. - lastPingAt time.Time - // Number of times the client has violated keepalive ping policy so far. - pingStrikes uint8 - // Flag to signify that number of ping strikes should be reset to 0. - // This is set whenever data or header frames are sent. - // 1 means yes. - resetPingStrikes uint32 // Accessed atomically. - initialWindowSize int32 - bdpEst *bdpEstimator - - mu sync.Mutex // guard the following - - // drainChan is initialized when drain(...) is called the first time. - // After which the server writes out the first GoAway(with ID 2^31-1) frame. - // Then an independent goroutine will be launched to later send the second GoAway. - // During this time we don't want to write another first GoAway(with ID 2^31 -1) frame. - // Thus call to drain(...) will be a no-op if drainChan is already initialized since draining is - // already underway. - drainChan chan struct{} - state transportState - activeStreams map[uint32]*Stream - // idle is the time instant when the connection went idle. - // This is either the beginning of the connection or when the number of - // RPCs go down to 0. - // When the connection is busy, this value is set to 0. - idle time.Time - - // Fields below are for channelz metric collection. - channelzID int64 // channelz unique identification number - czmu sync.RWMutex - kpCount int64 - // The number of streams that have started, including already finished ones. - streamsStarted int64 - // The number of streams that have ended successfully by sending frame with - // EoS bit set. - streamsSucceeded int64 - streamsFailed int64 - lastStreamCreated time.Time - msgSent int64 - msgRecv int64 - lastMsgSent time.Time - lastMsgRecv time.Time -} - -// newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is -// returned if something goes wrong. -func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err error) { - writeBufSize := defaultWriteBufSize - if config.WriteBufferSize > 0 { - writeBufSize = config.WriteBufferSize - } - readBufSize := defaultReadBufSize - if config.ReadBufferSize > 0 { - readBufSize = config.ReadBufferSize - } - framer := newFramer(conn, writeBufSize, readBufSize) - // Send initial settings as connection preface to client. - var isettings []http2.Setting - // TODO(zhaoq): Have a better way to signal "no limit" because 0 is - // permitted in the HTTP2 spec. - maxStreams := config.MaxStreams - if maxStreams == 0 { - maxStreams = math.MaxUint32 - } else { - isettings = append(isettings, http2.Setting{ - ID: http2.SettingMaxConcurrentStreams, - Val: maxStreams, - }) - } - dynamicWindow := true - iwz := int32(initialWindowSize) - if config.InitialWindowSize >= defaultWindowSize { - iwz = config.InitialWindowSize - dynamicWindow = false - } - icwz := int32(initialWindowSize) - if config.InitialConnWindowSize >= defaultWindowSize { - icwz = config.InitialConnWindowSize - dynamicWindow = false - } - if iwz != defaultWindowSize { - isettings = append(isettings, http2.Setting{ - ID: http2.SettingInitialWindowSize, - Val: uint32(iwz)}) - } - if err := framer.fr.WriteSettings(isettings...); err != nil { - return nil, connectionErrorf(false, err, "transport: %v", err) - } - // Adjust the connection flow control window if needed. - if delta := uint32(icwz - defaultWindowSize); delta > 0 { - if err := framer.fr.WriteWindowUpdate(0, delta); err != nil { - return nil, connectionErrorf(false, err, "transport: %v", err) - } - } - kp := config.KeepaliveParams - if kp.MaxConnectionIdle == 0 { - kp.MaxConnectionIdle = defaultMaxConnectionIdle - } - if kp.MaxConnectionAge == 0 { - kp.MaxConnectionAge = defaultMaxConnectionAge - } - // Add a jitter to MaxConnectionAge. - kp.MaxConnectionAge += getJitter(kp.MaxConnectionAge) - if kp.MaxConnectionAgeGrace == 0 { - kp.MaxConnectionAgeGrace = defaultMaxConnectionAgeGrace - } - if kp.Time == 0 { - kp.Time = defaultServerKeepaliveTime - } - if kp.Timeout == 0 { - kp.Timeout = defaultServerKeepaliveTimeout - } - kep := config.KeepalivePolicy - if kep.MinTime == 0 { - kep.MinTime = defaultKeepalivePolicyMinTime - } - ctx, cancel := context.WithCancel(context.Background()) - t := &http2Server{ - ctx: ctx, - cancel: cancel, - ctxDone: ctx.Done(), - conn: conn, - remoteAddr: conn.RemoteAddr(), - localAddr: conn.LocalAddr(), - authInfo: config.AuthInfo, - framer: framer, - readerDone: make(chan struct{}), - writerDone: make(chan struct{}), - maxStreams: maxStreams, - inTapHandle: config.InTapHandle, - fc: &trInFlow{limit: uint32(icwz)}, - state: reachable, - activeStreams: make(map[uint32]*Stream), - stats: config.StatsHandler, - kp: kp, - idle: time.Now(), - kep: kep, - initialWindowSize: iwz, - } - t.controlBuf = newControlBuffer(t.ctxDone) - if dynamicWindow { - t.bdpEst = &bdpEstimator{ - bdp: initialWindowSize, - updateFlowControl: t.updateFlowControl, - } - } - if t.stats != nil { - t.ctx = t.stats.TagConn(t.ctx, &stats.ConnTagInfo{ - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - }) - connBegin := &stats.ConnBegin{} - t.stats.HandleConn(t.ctx, connBegin) - } - if channelz.IsOn() { - t.channelzID = channelz.RegisterNormalSocket(t, config.ChannelzParentID, "") - } - t.framer.writer.Flush() - - defer func() { - if err != nil { - t.Close() - } - }() - - // Check the validity of client preface. - preface := make([]byte, len(clientPreface)) - if _, err := io.ReadFull(t.conn, preface); err != nil { - return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) - } - if !bytes.Equal(preface, clientPreface) { - return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) - } - - frame, err := t.framer.fr.ReadFrame() - if err == io.EOF || err == io.ErrUnexpectedEOF { - return nil, err - } - if err != nil { - return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) - } - atomic.StoreUint32(&t.activity, 1) - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) - } - t.handleSettings(sf) - - go func() { - t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) - t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler - if err := t.loopy.run(); err != nil { - errorf("transport: loopyWriter.run returning. Err: %v", err) - } - t.conn.Close() - close(t.writerDone) - }() - go t.keepalive() - return t, nil -} - -// operateHeader takes action on the decoded headers. -func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (close bool) { - streamID := frame.Header().StreamID - var state decodeState - for _, hf := range frame.Fields { - if err := state.processHeaderField(hf); err != nil { - if se, ok := err.(StreamError); ok { - t.controlBuf.put(&cleanupStream{ - streamID: streamID, - rst: true, - rstCode: statusCodeConvTab[se.Code], - onWrite: func() {}, - }) - } - return - } - } - - buf := newRecvBuffer() - s := &Stream{ - id: streamID, - st: t, - buf: buf, - fc: &inFlow{limit: uint32(t.initialWindowSize)}, - recvCompress: state.encoding, - method: state.method, - contentSubtype: state.contentSubtype, - } - if frame.StreamEnded() { - // s is just created by the caller. No lock needed. - s.state = streamReadDone - } - if state.timeoutSet { - s.ctx, s.cancel = context.WithTimeout(t.ctx, state.timeout) - } else { - s.ctx, s.cancel = context.WithCancel(t.ctx) - } - pr := &peer.Peer{ - Addr: t.remoteAddr, - } - // Attach Auth info if there is any. - if t.authInfo != nil { - pr.AuthInfo = t.authInfo - } - s.ctx = peer.NewContext(s.ctx, pr) - // Attach the received metadata to the context. - if len(state.mdata) > 0 { - s.ctx = metadata.NewIncomingContext(s.ctx, state.mdata) - } - if state.statsTags != nil { - s.ctx = stats.SetIncomingTags(s.ctx, state.statsTags) - } - if state.statsTrace != nil { - s.ctx = stats.SetIncomingTrace(s.ctx, state.statsTrace) - } - if t.inTapHandle != nil { - var err error - info := &tap.Info{ - FullMethodName: state.method, - } - s.ctx, err = t.inTapHandle(s.ctx, info) - if err != nil { - warningf("transport: http2Server.operateHeaders got an error from InTapHandle: %v", err) - t.controlBuf.put(&cleanupStream{ - streamID: s.id, - rst: true, - rstCode: http2.ErrCodeRefusedStream, - onWrite: func() {}, - }) - return - } - } - t.mu.Lock() - if t.state != reachable { - t.mu.Unlock() - return - } - if uint32(len(t.activeStreams)) >= t.maxStreams { - t.mu.Unlock() - t.controlBuf.put(&cleanupStream{ - streamID: streamID, - rst: true, - rstCode: http2.ErrCodeRefusedStream, - onWrite: func() {}, - }) - return - } - if streamID%2 != 1 || streamID <= t.maxStreamID { - t.mu.Unlock() - // illegal gRPC stream id. - errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID) - return true - } - t.maxStreamID = streamID - t.activeStreams[streamID] = s - if len(t.activeStreams) == 1 { - t.idle = time.Time{} - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - t.streamsStarted++ - t.lastStreamCreated = time.Now() - t.czmu.Unlock() - } - s.requestRead = func(n int) { - t.adjustWindow(s, uint32(n)) - } - s.ctx = traceCtx(s.ctx, s.method) - if t.stats != nil { - s.ctx = t.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) - inHeader := &stats.InHeader{ - FullMethod: s.method, - RemoteAddr: t.remoteAddr, - LocalAddr: t.localAddr, - Compression: s.recvCompress, - WireLength: int(frame.Header().Length), - } - t.stats.HandleRPC(s.ctx, inHeader) - } - s.ctxDone = s.ctx.Done() - s.wq = newWriteQuota(defaultWriteQuota, s.ctxDone) - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - ctxDone: s.ctxDone, - recv: s.buf, - }, - windowHandler: func(n int) { - t.updateWindow(s, uint32(n)) - }, - } - // Register the stream with loopy. - t.controlBuf.put(®isterStream{ - streamID: s.id, - wq: s.wq, - }) - handle(s) - return -} - -// HandleStreams receives incoming streams using the given handler. This is -// typically run in a separate goroutine. -// traceCtx attaches trace to ctx and returns the new context. -func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) { - defer close(t.readerDone) - for { - frame, err := t.framer.fr.ReadFrame() - atomic.StoreUint32(&t.activity, 1) - if err != nil { - if se, ok := err.(http2.StreamError); ok { - warningf("transport: http2Server.HandleStreams encountered http2.StreamError: %v", se) - t.mu.Lock() - s := t.activeStreams[se.StreamID] - t.mu.Unlock() - if s != nil { - t.closeStream(s, true, se.Code, nil, false) - } else { - t.controlBuf.put(&cleanupStream{ - streamID: se.StreamID, - rst: true, - rstCode: se.Code, - onWrite: func() {}, - }) - } - continue - } - if err == io.EOF || err == io.ErrUnexpectedEOF { - t.Close() - return - } - warningf("transport: http2Server.HandleStreams failed to read frame: %v", err) - t.Close() - return - } - switch frame := frame.(type) { - case *http2.MetaHeadersFrame: - if t.operateHeaders(frame, handle, traceCtx) { - t.Close() - break - } - case *http2.DataFrame: - t.handleData(frame) - case *http2.RSTStreamFrame: - t.handleRSTStream(frame) - case *http2.SettingsFrame: - t.handleSettings(frame) - case *http2.PingFrame: - t.handlePing(frame) - case *http2.WindowUpdateFrame: - t.handleWindowUpdate(frame) - case *http2.GoAwayFrame: - // TODO: Handle GoAway from the client appropriately. - default: - errorf("transport: http2Server.HandleStreams found unhandled frame type %v.", frame) - } - } -} - -func (t *http2Server) getStream(f http2.Frame) (*Stream, bool) { - t.mu.Lock() - defer t.mu.Unlock() - if t.activeStreams == nil { - // The transport is closing. - return nil, false - } - s, ok := t.activeStreams[f.Header().StreamID] - if !ok { - // The stream is already done. - return nil, false - } - return s, true -} - -// adjustWindow sends out extra window update over the initial window size -// of stream if the application is requesting data larger in size than -// the window. -func (t *http2Server) adjustWindow(s *Stream, n uint32) { - if w := s.fc.maybeAdjust(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) - } - -} - -// updateWindow adjusts the inbound quota for the stream and the transport. -// Window updates will deliver to the controller for sending when -// the cumulative quota exceeds the corresponding threshold. -func (t *http2Server) updateWindow(s *Stream, n uint32) { - if w := s.fc.onRead(n); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, - increment: w, - }) - } -} - -// updateFlowControl updates the incoming flow control windows -// for the transport and the stream based on the current bdp -// estimation. -func (t *http2Server) updateFlowControl(n uint32) { - t.mu.Lock() - for _, s := range t.activeStreams { - s.fc.newLimit(n) - } - t.initialWindowSize = int32(n) - t.mu.Unlock() - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: t.fc.newLimit(n), - }) - t.controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingInitialWindowSize, - Val: n, - }, - }, - }) - -} - -func (t *http2Server) handleData(f *http2.DataFrame) { - size := f.Header().Length - var sendBDPPing bool - if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(size) - } - // Decouple connection's flow control from application's read. - // An update on connection's flow control should not depend on - // whether user application has read the data or not. Such a - // restriction is already imposed on the stream's flow control, - // and therefore the sender will be blocked anyways. - // Decoupling the connection flow control will prevent other - // active(fast) streams from starving in presence of slow or - // inactive streams. - if w := t.fc.onData(size); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - if sendBDPPing { - // Avoid excessive ping detection (e.g. in an L7 proxy) - // by sending a window update prior to the BDP ping. - if w := t.fc.reset(); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{ - streamID: 0, - increment: w, - }) - } - t.controlBuf.put(bdpPing) - } - // Select the right stream to dispatch. - s, ok := t.getStream(f) - if !ok { - return - } - if size > 0 { - if err := s.fc.onData(size); err != nil { - t.closeStream(s, true, http2.ErrCodeFlowControl, nil, false) - return - } - if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) - } - } - // TODO(bradfitz, zhaoq): A copy is required here because there is no - // guarantee f.Data() is consumed before the arrival of next frame. - // Can this copy be eliminated? - if len(f.Data()) > 0 { - data := make([]byte, len(f.Data())) - copy(data, f.Data()) - s.write(recvMsg{data: data}) - } - } - if f.Header().Flags.Has(http2.FlagDataEndStream) { - // Received the end of stream from the client. - s.compareAndSwapState(streamActive, streamReadDone) - s.write(recvMsg{err: io.EOF}) - } -} - -func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) { - s, ok := t.getStream(f) - if !ok { - return - } - t.closeStream(s, false, 0, nil, false) -} - -func (t *http2Server) handleSettings(f *http2.SettingsFrame) { - if f.IsAck() { - return - } - var ss []http2.Setting - f.ForeachSetting(func(s http2.Setting) error { - ss = append(ss, s) - return nil - }) - t.controlBuf.put(&incomingSettings{ - ss: ss, - }) -} - -const ( - maxPingStrikes = 2 - defaultPingTimeout = 2 * time.Hour -) - -func (t *http2Server) handlePing(f *http2.PingFrame) { - if f.IsAck() { - if f.Data == goAwayPing.data && t.drainChan != nil { - close(t.drainChan) - return - } - // Maybe it's a BDP ping. - if t.bdpEst != nil { - t.bdpEst.calculate(f.Data) - } - return - } - pingAck := &ping{ack: true} - copy(pingAck.data[:], f.Data[:]) - t.controlBuf.put(pingAck) - - now := time.Now() - defer func() { - t.lastPingAt = now - }() - // A reset ping strikes means that we don't need to check for policy - // violation for this ping and the pingStrikes counter should be set - // to 0. - if atomic.CompareAndSwapUint32(&t.resetPingStrikes, 1, 0) { - t.pingStrikes = 0 - return - } - t.mu.Lock() - ns := len(t.activeStreams) - t.mu.Unlock() - if ns < 1 && !t.kep.PermitWithoutStream { - // Keepalive shouldn't be active thus, this new ping should - // have come after at least defaultPingTimeout. - if t.lastPingAt.Add(defaultPingTimeout).After(now) { - t.pingStrikes++ - } - } else { - // Check if keepalive policy is respected. - if t.lastPingAt.Add(t.kep.MinTime).After(now) { - t.pingStrikes++ - } - } - - if t.pingStrikes > maxPingStrikes { - // Send goaway and close the connection. - errorf("transport: Got too many pings from the client, closing the connection.") - t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true}) - } -} - -func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) { - t.controlBuf.put(&incomingWindowUpdate{ - streamID: f.Header().StreamID, - increment: f.Increment, - }) -} - -func appendHeaderFieldsFromMD(headerFields []hpack.HeaderField, md metadata.MD) []hpack.HeaderField { - for k, vv := range md { - if isReservedHeader(k) { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - continue - } - for _, v := range vv { - headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) - } - } - return headerFields -} - -// WriteHeader sends the header metedata md back to the client. -func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { - if s.updateHeaderSent() || s.getState() == streamDone { - return ErrIllegalHeaderWrite - } - s.hdrMu.Lock() - if md.Len() > 0 { - if s.header.Len() > 0 { - s.header = metadata.Join(s.header, md) - } else { - s.header = md - } - } - t.writeHeaderLocked(s) - s.hdrMu.Unlock() - return nil -} - -func (t *http2Server) writeHeaderLocked(s *Stream) { - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else. - headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) - if s.sendCompress != "" { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress}) - } - headerFields = appendHeaderFieldsFromMD(headerFields, s.header) - t.controlBuf.put(&headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: false, - onWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - }) - if t.stats != nil { - // Note: WireLength is not set in outHeader. - // TODO(mmukhi): Revisit this later, if needed. - outHeader := &stats.OutHeader{} - t.stats.HandleRPC(s.Context(), outHeader) - } -} - -// WriteStatus sends stream status to the client and terminates the stream. -// There is no further I/O operations being able to perform on this stream. -// TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early -// OK is adopted. -func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { - if s.getState() == streamDone { - return nil - } - s.hdrMu.Lock() - // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields - // first and create a slice of that exact size. - headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else. - if !s.updateHeaderSent() { // No headers have been sent. - if len(s.header) > 0 { // Send a separate header frame. - t.writeHeaderLocked(s) - } else { // Send a trailer only response. - headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) - } - } - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status", Value: strconv.Itoa(int(st.Code()))}) - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())}) - - if p := st.Proto(); p != nil && len(p.Details) > 0 { - stBytes, err := proto.Marshal(p) - if err != nil { - // TODO: return error instead, when callers are able to handle it. - grpclog.Errorf("transport: failed to marshal rpc status: %v, error: %v", p, err) - } else { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)}) - } - } - - // Attach the trailer metadata. - headerFields = appendHeaderFieldsFromMD(headerFields, s.trailer) - trailingHeader := &headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: true, - onWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - } - s.hdrMu.Unlock() - t.closeStream(s, false, 0, trailingHeader, true) - if t.stats != nil { - t.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) - } - return nil -} - -// Write converts the data into HTTP2 data frame and sends it out. Non-nil error -// is returns if it fails (e.g., framing error, transport error). -func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - if !s.isHeaderSent() { // Headers haven't been written yet. - if err := t.WriteHeader(s, nil); err != nil { - // TODO(mmukhi, dfawley): Make sure this is the right code to return. - return streamErrorf(codes.Internal, "transport: %v", err) - } - } else { - // Writing headers checks for this condition. - if s.getState() == streamDone { - // TODO(mmukhi, dfawley): Should the server write also return io.EOF? - s.cancel() - select { - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) - } - } - // Add some data to header frame so that we can equally distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - df := &dataFrame{ - streamID: s.id, - h: hdr, - d: data, - onEachWrite: func() { - atomic.StoreUint32(&t.resetPingStrikes, 1) - }, - } - if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { - select { - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - return ContextErr(s.ctx.Err()) - } - return t.controlBuf.put(df) -} - -// keepalive running in a separate goroutine does the following: -// 1. Gracefully closes an idle connection after a duration of keepalive.MaxConnectionIdle. -// 2. Gracefully closes any connection after a duration of keepalive.MaxConnectionAge. -// 3. Forcibly closes a connection after an additive period of keepalive.MaxConnectionAgeGrace over keepalive.MaxConnectionAge. -// 4. Makes sure a connection is alive by sending pings with a frequency of keepalive.Time and closes a non-responsive connection -// after an additional duration of keepalive.Timeout. -func (t *http2Server) keepalive() { - p := &ping{} - var pingSent bool - maxIdle := time.NewTimer(t.kp.MaxConnectionIdle) - maxAge := time.NewTimer(t.kp.MaxConnectionAge) - keepalive := time.NewTimer(t.kp.Time) - // NOTE: All exit paths of this function should reset their - // respective timers. A failure to do so will cause the - // following clean-up to deadlock and eventually leak. - defer func() { - if !maxIdle.Stop() { - <-maxIdle.C - } - if !maxAge.Stop() { - <-maxAge.C - } - if !keepalive.Stop() { - <-keepalive.C - } - }() - for { - select { - case <-maxIdle.C: - t.mu.Lock() - idle := t.idle - if idle.IsZero() { // The connection is non-idle. - t.mu.Unlock() - maxIdle.Reset(t.kp.MaxConnectionIdle) - continue - } - val := t.kp.MaxConnectionIdle - time.Since(idle) - t.mu.Unlock() - if val <= 0 { - // The connection has been idle for a duration of keepalive.MaxConnectionIdle or more. - // Gracefully close the connection. - t.drain(http2.ErrCodeNo, []byte{}) - // Resetting the timer so that the clean-up doesn't deadlock. - maxIdle.Reset(infinity) - return - } - maxIdle.Reset(val) - case <-maxAge.C: - t.drain(http2.ErrCodeNo, []byte{}) - maxAge.Reset(t.kp.MaxConnectionAgeGrace) - select { - case <-maxAge.C: - // Close the connection after grace period. - t.Close() - // Resetting the timer so that the clean-up doesn't deadlock. - maxAge.Reset(infinity) - case <-t.ctx.Done(): - } - return - case <-keepalive.C: - if atomic.CompareAndSwapUint32(&t.activity, 1, 0) { - pingSent = false - keepalive.Reset(t.kp.Time) - continue - } - if pingSent { - t.Close() - // Resetting the timer so that the clean-up doesn't deadlock. - keepalive.Reset(infinity) - return - } - pingSent = true - if channelz.IsOn() { - t.czmu.Lock() - t.kpCount++ - t.czmu.Unlock() - } - t.controlBuf.put(p) - keepalive.Reset(t.kp.Timeout) - case <-t.ctx.Done(): - return - } - } -} - -// Close starts shutting down the http2Server transport. -// TODO(zhaoq): Now the destruction is not blocked on any pending streams. This -// could cause some resource issue. Revisit this later. -func (t *http2Server) Close() error { - t.mu.Lock() - if t.state == closing { - t.mu.Unlock() - return errors.New("transport: Close() was already called") - } - t.state = closing - streams := t.activeStreams - t.activeStreams = nil - t.mu.Unlock() - t.controlBuf.finish() - t.cancel() - err := t.conn.Close() - if channelz.IsOn() { - channelz.RemoveEntry(t.channelzID) - } - // Cancel all active streams. - for _, s := range streams { - s.cancel() - } - if t.stats != nil { - connEnd := &stats.ConnEnd{} - t.stats.HandleConn(t.ctx, connEnd) - } - return err -} - -// closeStream clears the footprint of a stream when the stream is not needed -// any more. -func (t *http2Server) closeStream(s *Stream, rst bool, rstCode http2.ErrCode, hdr *headerFrame, eosReceived bool) { - if s.swapState(streamDone) == streamDone { - // If the stream was already done, return. - return - } - // In case stream sending and receiving are invoked in separate - // goroutines (e.g., bi-directional streaming), cancel needs to be - // called to interrupt the potential blocking on other goroutines. - s.cancel() - cleanup := &cleanupStream{ - streamID: s.id, - rst: rst, - rstCode: rstCode, - onWrite: func() { - t.mu.Lock() - if t.activeStreams != nil { - delete(t.activeStreams, s.id) - if len(t.activeStreams) == 0 { - t.idle = time.Now() - } - } - t.mu.Unlock() - if channelz.IsOn() { - t.czmu.Lock() - if eosReceived { - t.streamsSucceeded++ - } else { - t.streamsFailed++ - } - t.czmu.Unlock() - } - }, - } - if hdr != nil { - hdr.cleanup = cleanup - t.controlBuf.put(hdr) - } else { - t.controlBuf.put(cleanup) - } -} - -func (t *http2Server) RemoteAddr() net.Addr { - return t.remoteAddr -} - -func (t *http2Server) Drain() { - t.drain(http2.ErrCodeNo, []byte{}) -} - -func (t *http2Server) drain(code http2.ErrCode, debugData []byte) { - t.mu.Lock() - defer t.mu.Unlock() - if t.drainChan != nil { - return - } - t.drainChan = make(chan struct{}) - t.controlBuf.put(&goAway{code: code, debugData: debugData, headsUp: true}) -} - -var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}} - -// Handles outgoing GoAway and returns true if loopy needs to put itself -// in draining mode. -func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { - t.mu.Lock() - if t.state == closing { // TODO(mmukhi): This seems unnecessary. - t.mu.Unlock() - // The transport is closing. - return false, ErrConnClosing - } - sid := t.maxStreamID - if !g.headsUp { - // Stop accepting more streams now. - t.state = draining - if len(t.activeStreams) == 0 { - g.closeConn = true - } - t.mu.Unlock() - if err := t.framer.fr.WriteGoAway(sid, g.code, g.debugData); err != nil { - return false, err - } - if g.closeConn { - // Abruptly close the connection following the GoAway (via - // loopywriter). But flush out what's inside the buffer first. - t.framer.writer.Flush() - return false, fmt.Errorf("transport: Connection closing") - } - return true, nil - } - t.mu.Unlock() - // For a graceful close, send out a GoAway with stream ID of MaxUInt32, - // Follow that with a ping and wait for the ack to come back or a timer - // to expire. During this time accept new streams since they might have - // originated before the GoAway reaches the client. - // After getting the ack or timer expiration send out another GoAway this - // time with an ID of the max stream server intends to process. - if err := t.framer.fr.WriteGoAway(math.MaxUint32, http2.ErrCodeNo, []byte{}); err != nil { - return false, err - } - if err := t.framer.fr.WritePing(false, goAwayPing.data); err != nil { - return false, err - } - go func() { - timer := time.NewTimer(time.Minute) - defer timer.Stop() - select { - case <-t.drainChan: - case <-timer.C: - case <-t.ctx.Done(): - return - } - t.controlBuf.put(&goAway{code: g.code, debugData: g.debugData}) - }() - return false, nil -} - -func (t *http2Server) ChannelzMetric() *channelz.SocketInternalMetric { - t.czmu.RLock() - s := channelz.SocketInternalMetric{ - StreamsStarted: t.streamsStarted, - StreamsSucceeded: t.streamsSucceeded, - StreamsFailed: t.streamsFailed, - MessagesSent: t.msgSent, - MessagesReceived: t.msgRecv, - KeepAlivesSent: t.kpCount, - LastRemoteStreamCreatedTimestamp: t.lastStreamCreated, - LastMessageSentTimestamp: t.lastMsgSent, - LastMessageReceivedTimestamp: t.lastMsgRecv, - LocalFlowControlWindow: int64(t.fc.getSize()), - //socket options - LocalAddr: t.localAddr, - RemoteAddr: t.remoteAddr, - // Security - // RemoteName : - } - t.czmu.RUnlock() - s.RemoteFlowControlWindow = t.getOutFlowWindow() - return &s -} - -func (t *http2Server) IncrMsgSent() { - t.czmu.Lock() - t.msgSent++ - t.lastMsgSent = time.Now() - t.czmu.Unlock() -} - -func (t *http2Server) IncrMsgRecv() { - t.czmu.Lock() - t.msgRecv++ - t.lastMsgRecv = time.Now() - t.czmu.Unlock() -} - -func (t *http2Server) getOutFlowWindow() int64 { - resp := make(chan uint32) - timer := time.NewTimer(time.Second) - defer timer.Stop() - t.controlBuf.put(&outFlowControlSizeRequest{resp}) - select { - case sz := <-resp: - return int64(sz) - case <-t.ctxDone: - return -1 - case <-timer.C: - return -2 - } -} - -func getJitter(v time.Duration) time.Duration { - if v == infinity { - return 0 - } - // Generate a jitter between +/- 10% of the value. - r := int64(v / 10) - j := grpcrand.Int63n(2*r) - r - return time.Duration(j) -} diff --git a/examples/google.golang.org/grpc/transport/http_util.go b/examples/google.golang.org/grpc/transport/http_util.go deleted file mode 100755 index 7d15c7d..0000000 --- a/examples/google.golang.org/grpc/transport/http_util.go +++ /dev/null @@ -1,592 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "bufio" - "bytes" - "encoding/base64" - "fmt" - "net" - "net/http" - "strconv" - "strings" - "time" - "unicode/utf8" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -const ( - // http2MaxFrameLen specifies the max length of a HTTP2 frame. - http2MaxFrameLen = 16384 // 16KB frame - // http://http2.github.io/http2-spec/#SettingValues - http2InitHeaderTableSize = 4096 - // http2IOBufSize specifies the buffer size for sending frames. - defaultWriteBufSize = 32 * 1024 - defaultReadBufSize = 32 * 1024 - // baseContentType is the base content-type for gRPC. This is a valid - // content-type on it's own, but can also include a content-subtype such as - // "proto" as a suffix after "+" or ";". See - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests - // for more details. - baseContentType = "application/grpc" -) - -var ( - clientPreface = []byte(http2.ClientPreface) - http2ErrConvTab = map[http2.ErrCode]codes.Code{ - http2.ErrCodeNo: codes.Internal, - http2.ErrCodeProtocol: codes.Internal, - http2.ErrCodeInternal: codes.Internal, - http2.ErrCodeFlowControl: codes.ResourceExhausted, - http2.ErrCodeSettingsTimeout: codes.Internal, - http2.ErrCodeStreamClosed: codes.Internal, - http2.ErrCodeFrameSize: codes.Internal, - http2.ErrCodeRefusedStream: codes.Unavailable, - http2.ErrCodeCancel: codes.Canceled, - http2.ErrCodeCompression: codes.Internal, - http2.ErrCodeConnect: codes.Internal, - http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted, - http2.ErrCodeInadequateSecurity: codes.PermissionDenied, - http2.ErrCodeHTTP11Required: codes.Internal, - } - statusCodeConvTab = map[codes.Code]http2.ErrCode{ - codes.Internal: http2.ErrCodeInternal, - codes.Canceled: http2.ErrCodeCancel, - codes.Unavailable: http2.ErrCodeRefusedStream, - codes.ResourceExhausted: http2.ErrCodeEnhanceYourCalm, - codes.PermissionDenied: http2.ErrCodeInadequateSecurity, - } - httpStatusConvTab = map[int]codes.Code{ - // 400 Bad Request - INTERNAL. - http.StatusBadRequest: codes.Internal, - // 401 Unauthorized - UNAUTHENTICATED. - http.StatusUnauthorized: codes.Unauthenticated, - // 403 Forbidden - PERMISSION_DENIED. - http.StatusForbidden: codes.PermissionDenied, - // 404 Not Found - UNIMPLEMENTED. - http.StatusNotFound: codes.Unimplemented, - // 429 Too Many Requests - UNAVAILABLE. - http.StatusTooManyRequests: codes.Unavailable, - // 502 Bad Gateway - UNAVAILABLE. - http.StatusBadGateway: codes.Unavailable, - // 503 Service Unavailable - UNAVAILABLE. - http.StatusServiceUnavailable: codes.Unavailable, - // 504 Gateway timeout - UNAVAILABLE. - http.StatusGatewayTimeout: codes.Unavailable, - } -) - -// Records the states during HPACK decoding. Must be reset once the -// decoding of the entire headers are finished. -type decodeState struct { - encoding string - // statusGen caches the stream status received from the trailer the server - // sent. Client side only. Do not access directly. After all trailers are - // parsed, use the status method to retrieve the status. - statusGen *status.Status - // rawStatusCode and rawStatusMsg are set from the raw trailer fields and are not - // intended for direct access outside of parsing. - rawStatusCode *int - rawStatusMsg string - httpStatus *int - // Server side only fields. - timeoutSet bool - timeout time.Duration - method string - // key-value metadata map from the peer. - mdata map[string][]string - statsTags []byte - statsTrace []byte - contentSubtype string -} - -// isReservedHeader checks whether hdr belongs to HTTP2 headers -// reserved by gRPC protocol. Any other headers are classified as the -// user-specified metadata. -func isReservedHeader(hdr string) bool { - if hdr != "" && hdr[0] == ':' { - return true - } - switch hdr { - case "content-type", - "user-agent", - "grpc-message-type", - "grpc-encoding", - "grpc-message", - "grpc-status", - "grpc-timeout", - "grpc-status-details-bin", - "te": - return true - default: - return false - } -} - -// isWhitelistedHeader checks whether hdr should be propagated -// into metadata visible to users. -func isWhitelistedHeader(hdr string) bool { - switch hdr { - case ":authority", "user-agent": - return true - default: - return false - } -} - -// contentSubtype returns the content-subtype for the given content-type. The -// given content-type must be a valid content-type that starts with -// "application/grpc". A content-subtype will follow "application/grpc" after a -// "+" or ";". See -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -// -// If contentType is not a valid content-type for gRPC, the boolean -// will be false, otherwise true. If content-type == "application/grpc", -// "application/grpc+", or "application/grpc;", the boolean will be true, -// but no content-subtype will be returned. -// -// contentType is assumed to be lowercase already. -func contentSubtype(contentType string) (string, bool) { - if contentType == baseContentType { - return "", true - } - if !strings.HasPrefix(contentType, baseContentType) { - return "", false - } - // guaranteed since != baseContentType and has baseContentType prefix - switch contentType[len(baseContentType)] { - case '+', ';': - // this will return true for "application/grpc+" or "application/grpc;" - // which the previous validContentType function tested to be valid, so we - // just say that no content-subtype is specified in this case - return contentType[len(baseContentType)+1:], true - default: - return "", false - } -} - -// contentSubtype is assumed to be lowercase -func contentType(contentSubtype string) string { - if contentSubtype == "" { - return baseContentType - } - return baseContentType + "+" + contentSubtype -} - -func (d *decodeState) status() *status.Status { - if d.statusGen == nil { - // No status-details were provided; generate status using code/msg. - d.statusGen = status.New(codes.Code(int32(*(d.rawStatusCode))), d.rawStatusMsg) - } - return d.statusGen -} - -const binHdrSuffix = "-bin" - -func encodeBinHeader(v []byte) string { - return base64.RawStdEncoding.EncodeToString(v) -} - -func decodeBinHeader(v string) ([]byte, error) { - if len(v)%4 == 0 { - // Input was padded, or padding was not necessary. - return base64.StdEncoding.DecodeString(v) - } - return base64.RawStdEncoding.DecodeString(v) -} - -func encodeMetadataHeader(k, v string) string { - if strings.HasSuffix(k, binHdrSuffix) { - return encodeBinHeader(([]byte)(v)) - } - return v -} - -func decodeMetadataHeader(k, v string) (string, error) { - if strings.HasSuffix(k, binHdrSuffix) { - b, err := decodeBinHeader(v) - return string(b), err - } - return v, nil -} - -func (d *decodeState) decodeResponseHeader(frame *http2.MetaHeadersFrame) error { - for _, hf := range frame.Fields { - if err := d.processHeaderField(hf); err != nil { - return err - } - } - - // If grpc status exists, no need to check further. - if d.rawStatusCode != nil || d.statusGen != nil { - return nil - } - - // If grpc status doesn't exist and http status doesn't exist, - // then it's a malformed header. - if d.httpStatus == nil { - return streamErrorf(codes.Internal, "malformed header: doesn't contain status(gRPC or HTTP)") - } - - if *(d.httpStatus) != http.StatusOK { - code, ok := httpStatusConvTab[*(d.httpStatus)] - if !ok { - code = codes.Unknown - } - return streamErrorf(code, http.StatusText(*(d.httpStatus))) - } - - // gRPC status doesn't exist and http status is OK. - // Set rawStatusCode to be unknown and return nil error. - // So that, if the stream has ended this Unknown status - // will be propagated to the user. - // Otherwise, it will be ignored. In which case, status from - // a later trailer, that has StreamEnded flag set, is propagated. - code := int(codes.Unknown) - d.rawStatusCode = &code - return nil - -} - -func (d *decodeState) addMetadata(k, v string) { - if d.mdata == nil { - d.mdata = make(map[string][]string) - } - d.mdata[k] = append(d.mdata[k], v) -} - -func (d *decodeState) processHeaderField(f hpack.HeaderField) error { - switch f.Name { - case "content-type": - contentSubtype, validContentType := contentSubtype(f.Value) - if !validContentType { - return streamErrorf(codes.Internal, "transport: received the unexpected content-type %q", f.Value) - } - d.contentSubtype = contentSubtype - // TODO: do we want to propagate the whole content-type in the metadata, - // or come up with a way to just propagate the content-subtype if it was set? - // ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"} - // in the metadata? - d.addMetadata(f.Name, f.Value) - case "grpc-encoding": - d.encoding = f.Value - case "grpc-status": - code, err := strconv.Atoi(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status: %v", err) - } - d.rawStatusCode = &code - case "grpc-message": - d.rawStatusMsg = decodeGrpcMessage(f.Value) - case "grpc-status-details-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err) - } - s := &spb.Status{} - if err := proto.Unmarshal(v, s); err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-status-details-bin: %v", err) - } - d.statusGen = status.FromProto(s) - case "grpc-timeout": - d.timeoutSet = true - var err error - if d.timeout, err = decodeTimeout(f.Value); err != nil { - return streamErrorf(codes.Internal, "transport: malformed time-out: %v", err) - } - case ":path": - d.method = f.Value - case ":status": - code, err := strconv.Atoi(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed http-status: %v", err) - } - d.httpStatus = &code - case "grpc-tags-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-tags-bin: %v", err) - } - d.statsTags = v - d.addMetadata(f.Name, string(v)) - case "grpc-trace-bin": - v, err := decodeBinHeader(f.Value) - if err != nil { - return streamErrorf(codes.Internal, "transport: malformed grpc-trace-bin: %v", err) - } - d.statsTrace = v - d.addMetadata(f.Name, string(v)) - default: - if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) { - break - } - v, err := decodeMetadataHeader(f.Name, f.Value) - if err != nil { - errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err) - return nil - } - d.addMetadata(f.Name, v) - } - return nil -} - -type timeoutUnit uint8 - -const ( - hour timeoutUnit = 'H' - minute timeoutUnit = 'M' - second timeoutUnit = 'S' - millisecond timeoutUnit = 'm' - microsecond timeoutUnit = 'u' - nanosecond timeoutUnit = 'n' -) - -func timeoutUnitToDuration(u timeoutUnit) (d time.Duration, ok bool) { - switch u { - case hour: - return time.Hour, true - case minute: - return time.Minute, true - case second: - return time.Second, true - case millisecond: - return time.Millisecond, true - case microsecond: - return time.Microsecond, true - case nanosecond: - return time.Nanosecond, true - default: - } - return -} - -const maxTimeoutValue int64 = 100000000 - 1 - -// div does integer division and round-up the result. Note that this is -// equivalent to (d+r-1)/r but has less chance to overflow. -func div(d, r time.Duration) int64 { - if m := d % r; m > 0 { - return int64(d/r + 1) - } - return int64(d / r) -} - -// TODO(zhaoq): It is the simplistic and not bandwidth efficient. Improve it. -func encodeTimeout(t time.Duration) string { - if t <= 0 { - return "0n" - } - if d := div(t, time.Nanosecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "n" - } - if d := div(t, time.Microsecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "u" - } - if d := div(t, time.Millisecond); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "m" - } - if d := div(t, time.Second); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "S" - } - if d := div(t, time.Minute); d <= maxTimeoutValue { - return strconv.FormatInt(d, 10) + "M" - } - // Note that maxTimeoutValue * time.Hour > MaxInt64. - return strconv.FormatInt(div(t, time.Hour), 10) + "H" -} - -func decodeTimeout(s string) (time.Duration, error) { - size := len(s) - if size < 2 { - return 0, fmt.Errorf("transport: timeout string is too short: %q", s) - } - unit := timeoutUnit(s[size-1]) - d, ok := timeoutUnitToDuration(unit) - if !ok { - return 0, fmt.Errorf("transport: timeout unit is not recognized: %q", s) - } - t, err := strconv.ParseInt(s[:size-1], 10, 64) - if err != nil { - return 0, err - } - return d * time.Duration(t), nil -} - -const ( - spaceByte = ' ' - tildeByte = '~' - percentByte = '%' -) - -// encodeGrpcMessage is used to encode status code in header field -// "grpc-message". It does percent encoding and also replaces invalid utf-8 -// characters with Unicode replacement character. -// -// It checks to see if each individual byte in msg is an allowable byte, and -// then either percent encoding or passing it through. When percent encoding, -// the byte is converted into hexadecimal notation with a '%' prepended. -func encodeGrpcMessage(msg string) string { - if msg == "" { - return "" - } - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if !(c >= spaceByte && c <= tildeByte && c != percentByte) { - return encodeGrpcMessageUnchecked(msg) - } - } - return msg -} - -func encodeGrpcMessageUnchecked(msg string) string { - var buf bytes.Buffer - for len(msg) > 0 { - r, size := utf8.DecodeRuneInString(msg) - for _, b := range []byte(string(r)) { - if size > 1 { - // If size > 1, r is not ascii. Always do percent encoding. - buf.WriteString(fmt.Sprintf("%%%02X", b)) - continue - } - - // The for loop is necessary even if size == 1. r could be - // utf8.RuneError. - // - // fmt.Sprintf("%%%02X", utf8.RuneError) gives "%FFFD". - if b >= spaceByte && b <= tildeByte && b != percentByte { - buf.WriteByte(b) - } else { - buf.WriteString(fmt.Sprintf("%%%02X", b)) - } - } - msg = msg[size:] - } - return buf.String() -} - -// decodeGrpcMessage decodes the msg encoded by encodeGrpcMessage. -func decodeGrpcMessage(msg string) string { - if msg == "" { - return "" - } - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - if msg[i] == percentByte && i+2 < lenMsg { - return decodeGrpcMessageUnchecked(msg) - } - } - return msg -} - -func decodeGrpcMessageUnchecked(msg string) string { - var buf bytes.Buffer - lenMsg := len(msg) - for i := 0; i < lenMsg; i++ { - c := msg[i] - if c == percentByte && i+2 < lenMsg { - parsed, err := strconv.ParseUint(msg[i+1:i+3], 16, 8) - if err != nil { - buf.WriteByte(c) - } else { - buf.WriteByte(byte(parsed)) - i += 2 - } - } else { - buf.WriteByte(c) - } - } - return buf.String() -} - -type bufWriter struct { - buf []byte - offset int - batchSize int - conn net.Conn - err error - - onFlush func() -} - -func newBufWriter(conn net.Conn, batchSize int) *bufWriter { - return &bufWriter{ - buf: make([]byte, batchSize*2), - batchSize: batchSize, - conn: conn, - } -} - -func (w *bufWriter) Write(b []byte) (n int, err error) { - if w.err != nil { - return 0, w.err - } - for len(b) > 0 { - nn := copy(w.buf[w.offset:], b) - b = b[nn:] - w.offset += nn - n += nn - if w.offset >= w.batchSize { - err = w.Flush() - } - } - return n, err -} - -func (w *bufWriter) Flush() error { - if w.err != nil { - return w.err - } - if w.offset == 0 { - return nil - } - if w.onFlush != nil { - w.onFlush() - } - _, w.err = w.conn.Write(w.buf[:w.offset]) - w.offset = 0 - return w.err -} - -type framer struct { - writer *bufWriter - fr *http2.Framer -} - -func newFramer(conn net.Conn, writeBufferSize, readBufferSize int) *framer { - r := bufio.NewReaderSize(conn, readBufferSize) - w := newBufWriter(conn, writeBufferSize) - f := &framer{ - writer: w, - fr: http2.NewFramer(w, r), - } - // Opt-in to Frame reuse API on framer to reduce garbage. - // Frames aren't safe to read from after a subsequent call to ReadFrame. - f.fr.SetReuseFrames() - f.fr.ReadMetaHeaders = hpack.NewDecoder(http2InitHeaderTableSize, nil) - return f -} diff --git a/examples/google.golang.org/grpc/transport/http_util_test.go b/examples/google.golang.org/grpc/transport/http_util_test.go deleted file mode 100755 index 44169b6..0000000 --- a/examples/google.golang.org/grpc/transport/http_util_test.go +++ /dev/null @@ -1,237 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -func TestTimeoutEncode(t *testing.T) { - for _, test := range []struct { - in string - out string - }{ - {"12345678ns", "12345678n"}, - {"123456789ns", "123457u"}, - {"12345678us", "12345678u"}, - {"123456789us", "123457m"}, - {"12345678ms", "12345678m"}, - {"123456789ms", "123457S"}, - {"12345678s", "12345678S"}, - {"123456789s", "2057614M"}, - {"12345678m", "12345678M"}, - {"123456789m", "2057614H"}, - } { - d, err := time.ParseDuration(test.in) - if err != nil { - t.Fatalf("failed to parse duration string %s: %v", test.in, err) - } - out := encodeTimeout(d) - if out != test.out { - t.Fatalf("timeoutEncode(%s) = %s, want %s", test.in, out, test.out) - } - } -} - -func TestTimeoutDecode(t *testing.T) { - for _, test := range []struct { - // input - s string - // output - d time.Duration - err error - }{ - {"1234S", time.Second * 1234, nil}, - {"1234x", 0, fmt.Errorf("transport: timeout unit is not recognized: %q", "1234x")}, - {"1", 0, fmt.Errorf("transport: timeout string is too short: %q", "1")}, - {"", 0, fmt.Errorf("transport: timeout string is too short: %q", "")}, - } { - d, err := decodeTimeout(test.s) - if d != test.d || fmt.Sprint(err) != fmt.Sprint(test.err) { - t.Fatalf("timeoutDecode(%q) = %d, %v, want %d, %v", test.s, int64(d), err, int64(test.d), test.err) - } - } -} - -func TestContentSubtype(t *testing.T) { - tests := []struct { - contentType string - want string - wantValid bool - }{ - {"application/grpc", "", true}, - {"application/grpc+", "", true}, - {"application/grpc+blah", "blah", true}, - {"application/grpc;", "", true}, - {"application/grpc;blah", "blah", true}, - {"application/grpcd", "", false}, - {"application/grpd", "", false}, - {"application/grp", "", false}, - } - for _, tt := range tests { - got, gotValid := contentSubtype(tt.contentType) - if got != tt.want || gotValid != tt.wantValid { - t.Errorf("contentSubtype(%q) = (%v, %v); want (%v, %v)", tt.contentType, got, gotValid, tt.want, tt.wantValid) - } - } -} - -func TestEncodeGrpcMessage(t *testing.T) { - for _, tt := range []struct { - input string - expected string - }{ - {"", ""}, - {"Hello", "Hello"}, - {"\u0000", "%00"}, - {"%", "%25"}, - {"系统", "%E7%B3%BB%E7%BB%9F"}, - {string([]byte{0xff, 0xfe, 0xfd}), "%EF%BF%BD%EF%BF%BD%EF%BF%BD"}, - } { - actual := encodeGrpcMessage(tt.input) - if tt.expected != actual { - t.Errorf("encodeGrpcMessage(%q) = %q, want %q", tt.input, actual, tt.expected) - } - } - - // make sure that all the visible ASCII chars except '%' are not percent encoded. - for i := ' '; i <= '~' && i != '%'; i++ { - output := encodeGrpcMessage(string(i)) - if output != string(i) { - t.Errorf("encodeGrpcMessage(%v) = %v, want %v", string(i), output, string(i)) - } - } - - // make sure that all the invisible ASCII chars and '%' are percent encoded. - for i := rune(0); i == '%' || (i >= rune(0) && i < ' ') || (i > '~' && i <= rune(127)); i++ { - output := encodeGrpcMessage(string(i)) - expected := fmt.Sprintf("%%%02X", i) - if output != expected { - t.Errorf("encodeGrpcMessage(%v) = %v, want %v", string(i), output, expected) - } - } -} - -func TestDecodeGrpcMessage(t *testing.T) { - for _, tt := range []struct { - input string - expected string - }{ - {"", ""}, - {"Hello", "Hello"}, - {"H%61o", "Hao"}, - {"H%6", "H%6"}, - {"%G0", "%G0"}, - {"%E7%B3%BB%E7%BB%9F", "系统"}, - {"%EF%BF%BD", "�"}, - } { - actual := decodeGrpcMessage(tt.input) - if tt.expected != actual { - t.Errorf("decodeGrpcMessage(%q) = %q, want %q", tt.input, actual, tt.expected) - } - } - - // make sure that all the visible ASCII chars except '%' are not percent decoded. - for i := ' '; i <= '~' && i != '%'; i++ { - output := decodeGrpcMessage(string(i)) - if output != string(i) { - t.Errorf("decodeGrpcMessage(%v) = %v, want %v", string(i), output, string(i)) - } - } - - // make sure that all the invisible ASCII chars and '%' are percent decoded. - for i := rune(0); i == '%' || (i >= rune(0) && i < ' ') || (i > '~' && i <= rune(127)); i++ { - output := decodeGrpcMessage(fmt.Sprintf("%%%02X", i)) - if output != string(i) { - t.Errorf("decodeGrpcMessage(%v) = %v, want %v", fmt.Sprintf("%%%02X", i), output, string(i)) - } - } -} - -// Decode an encoded string should get the same thing back, except for invalid -// utf8 chars. -func TestDecodeEncodeGrpcMessage(t *testing.T) { - testCases := []struct { - orig string - want string - }{ - {"", ""}, - {"hello", "hello"}, - {"h%6", "h%6"}, - {"%G0", "%G0"}, - {"系统", "系统"}, - {"Hello, 世界", "Hello, 世界"}, - - {string([]byte{0xff, 0xfe, 0xfd}), "���"}, - {string([]byte{0xff}) + "Hello" + string([]byte{0xfe}) + "世界" + string([]byte{0xfd}), "�Hello�世界�"}, - } - for _, tC := range testCases { - got := decodeGrpcMessage(encodeGrpcMessage(tC.orig)) - if got != tC.want { - t.Errorf("decodeGrpcMessage(encodeGrpcMessage(%q)) = %q, want %q", tC.orig, got, tC.want) - } - } -} - -const binaryValue = string(128) - -func TestEncodeMetadataHeader(t *testing.T) { - for _, test := range []struct { - // input - kin string - vin string - // output - vout string - }{ - {"key", "abc", "abc"}, - {"KEY", "abc", "abc"}, - {"key-bin", "abc", "YWJj"}, - {"key-bin", binaryValue, "woA"}, - } { - v := encodeMetadataHeader(test.kin, test.vin) - if !reflect.DeepEqual(v, test.vout) { - t.Fatalf("encodeMetadataHeader(%q, %q) = %q, want %q", test.kin, test.vin, v, test.vout) - } - } -} - -func TestDecodeMetadataHeader(t *testing.T) { - for _, test := range []struct { - // input - kin string - vin string - // output - vout string - err error - }{ - {"a", "abc", "abc", nil}, - {"key-bin", "Zm9vAGJhcg==", "foo\x00bar", nil}, - {"key-bin", "Zm9vAGJhcg", "foo\x00bar", nil}, - {"key-bin", "woA=", binaryValue, nil}, - {"a", "abc,efg", "abc,efg", nil}, - } { - v, err := decodeMetadataHeader(test.kin, test.vin) - if !reflect.DeepEqual(v, test.vout) || !reflect.DeepEqual(err, test.err) { - t.Fatalf("decodeMetadataHeader(%q, %q) = %q, %v, want %q, %v", test.kin, test.vin, v, err, test.vout, test.err) - } - } -} diff --git a/examples/google.golang.org/grpc/transport/log.go b/examples/google.golang.org/grpc/transport/log.go deleted file mode 100755 index ac8e358..0000000 --- a/examples/google.golang.org/grpc/transport/log.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// This file contains wrappers for grpclog functions. -// The transport package only logs to verbose level 2 by default. - -package transport - -import "google.golang.org/grpc/grpclog" - -const logLevel = 2 - -func infof(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Infof(format, args...) - } -} - -func warningf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Warningf(format, args...) - } -} - -func errorf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Errorf(format, args...) - } -} - -func fatalf(format string, args ...interface{}) { - if grpclog.V(logLevel) { - grpclog.Fatalf(format, args...) - } -} diff --git a/examples/google.golang.org/grpc/transport/transport.go b/examples/google.golang.org/grpc/transport/transport.go deleted file mode 100755 index f51f878..0000000 --- a/examples/google.golang.org/grpc/transport/transport.go +++ /dev/null @@ -1,708 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package transport defines and implements message oriented communication -// channel to complete various transactions (e.g., an RPC). It is meant for -// grpc-internal usage and is not intended to be imported directly by users. -package transport // externally used as import "google.golang.org/grpc/transport" - -import ( - "errors" - "fmt" - "io" - "net" - "sync" - "sync/atomic" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/tap" -) - -// recvMsg represents the received msg from the transport. All transport -// protocol specific info has been removed. -type recvMsg struct { - data []byte - // nil: received some data - // io.EOF: stream is completed. data is nil. - // other non-nil error: transport failure. data is nil. - err error -} - -// recvBuffer is an unbounded channel of recvMsg structs. -// Note recvBuffer differs from controlBuffer only in that recvBuffer -// holds a channel of only recvMsg structs instead of objects implementing "item" interface. -// recvBuffer is written to much more often than -// controlBuffer and using strict recvMsg structs helps avoid allocation in "recvBuffer.put" -type recvBuffer struct { - c chan recvMsg - mu sync.Mutex - backlog []recvMsg - err error -} - -func newRecvBuffer() *recvBuffer { - b := &recvBuffer{ - c: make(chan recvMsg, 1), - } - return b -} - -func (b *recvBuffer) put(r recvMsg) { - b.mu.Lock() - if b.err != nil { - b.mu.Unlock() - // An error had occurred earlier, don't accept more - // data or errors. - return - } - b.err = r.err - if len(b.backlog) == 0 { - select { - case b.c <- r: - b.mu.Unlock() - return - default: - } - } - b.backlog = append(b.backlog, r) - b.mu.Unlock() -} - -func (b *recvBuffer) load() { - b.mu.Lock() - if len(b.backlog) > 0 { - select { - case b.c <- b.backlog[0]: - b.backlog[0] = recvMsg{} - b.backlog = b.backlog[1:] - default: - } - } - b.mu.Unlock() -} - -// get returns the channel that receives a recvMsg in the buffer. -// -// Upon receipt of a recvMsg, the caller should call load to send another -// recvMsg onto the channel if there is any. -func (b *recvBuffer) get() <-chan recvMsg { - return b.c -} - -// -// recvBufferReader implements io.Reader interface to read the data from -// recvBuffer. -type recvBufferReader struct { - ctx context.Context - ctxDone <-chan struct{} // cache of ctx.Done() (for performance). - recv *recvBuffer - last []byte // Stores the remaining data in the previous calls. - err error -} - -// Read reads the next len(p) bytes from last. If last is drained, it tries to -// read additional data from recv. It blocks if there no additional data available -// in recv. If Read returns any non-nil error, it will continue to return that error. -func (r *recvBufferReader) Read(p []byte) (n int, err error) { - if r.err != nil { - return 0, r.err - } - n, r.err = r.read(p) - return n, r.err -} - -func (r *recvBufferReader) read(p []byte) (n int, err error) { - if r.last != nil && len(r.last) > 0 { - // Read remaining data left in last call. - copied := copy(p, r.last) - r.last = r.last[copied:] - return copied, nil - } - select { - case <-r.ctxDone: - return 0, ContextErr(r.ctx.Err()) - case m := <-r.recv.get(): - r.recv.load() - if m.err != nil { - return 0, m.err - } - copied := copy(p, m.data) - r.last = m.data[copied:] - return copied, nil - } -} - -type streamState uint32 - -const ( - streamActive streamState = iota - streamWriteDone // EndStream sent - streamReadDone // EndStream received - streamDone // the entire stream is finished. -) - -// Stream represents an RPC in the transport layer. -type Stream struct { - id uint32 - st ServerTransport // nil for client side Stream - ctx context.Context // the associated context of the stream - cancel context.CancelFunc // always nil for client side Stream - done chan struct{} // closed at the end of stream to unblock writers. On the client side. - ctxDone <-chan struct{} // same as done chan but for server side. Cache of ctx.Done() (for performance) - method string // the associated RPC method of the stream - recvCompress string - sendCompress string - buf *recvBuffer - trReader io.Reader - fc *inFlow - recvQuota uint32 - wq *writeQuota - - // Callback to state application's intentions to read data. This - // is used to adjust flow control, if needed. - requestRead func(int) - - headerChan chan struct{} // closed to indicate the end of header metadata. - headerDone uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. - - // hdrMu protects header and trailer metadata on the server-side. - hdrMu sync.Mutex - header metadata.MD // the received header metadata. - trailer metadata.MD // the key-value map of trailer metadata. - - // On the server-side, headerSent is atomically set to 1 when the headers are sent out. - headerSent uint32 - - state streamState - - // On client-side it is the status error received from the server. - // On server-side it is unused. - status *status.Status - - bytesReceived uint32 // indicates whether any bytes have been received on this stream - unprocessed uint32 // set if the server sends a refused stream or GOAWAY including this stream - - // contentSubtype is the content-subtype for requests. - // this must be lowercase or the behavior is undefined. - contentSubtype string -} - -// isHeaderSent is only valid on the server-side. -func (s *Stream) isHeaderSent() bool { - return atomic.LoadUint32(&s.headerSent) == 1 -} - -// updateHeaderSent updates headerSent and returns true -// if it was alreay set. It is valid only on server-side. -func (s *Stream) updateHeaderSent() bool { - return atomic.SwapUint32(&s.headerSent, 1) == 1 -} - -func (s *Stream) swapState(st streamState) streamState { - return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st))) -} - -func (s *Stream) compareAndSwapState(oldState, newState streamState) bool { - return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState)) -} - -func (s *Stream) getState() streamState { - return streamState(atomic.LoadUint32((*uint32)(&s.state))) -} - -func (s *Stream) waitOnHeader() error { - if s.headerChan == nil { - // On the server headerChan is always nil since a stream originates - // only after having received headers. - return nil - } - select { - case <-s.ctx.Done(): - return ContextErr(s.ctx.Err()) - case <-s.headerChan: - return nil - } -} - -// RecvCompress returns the compression algorithm applied to the inbound -// message. It is empty string if there is no compression applied. -func (s *Stream) RecvCompress() string { - if err := s.waitOnHeader(); err != nil { - return "" - } - return s.recvCompress -} - -// SetSendCompress sets the compression algorithm to the stream. -func (s *Stream) SetSendCompress(str string) { - s.sendCompress = str -} - -// Done returns a chanel which is closed when it receives the final status -// from the server. -func (s *Stream) Done() <-chan struct{} { - return s.done -} - -// Header acquires the key-value pairs of header metadata once it -// is available. It blocks until i) the metadata is ready or ii) there is no -// header metadata or iii) the stream is canceled/expired. -func (s *Stream) Header() (metadata.MD, error) { - err := s.waitOnHeader() - // Even if the stream is closed, header is returned if available. - select { - case <-s.headerChan: - if s.header == nil { - return nil, nil - } - return s.header.Copy(), nil - default: - } - return nil, err -} - -// Trailer returns the cached trailer metedata. Note that if it is not called -// after the entire stream is done, it could return an empty MD. Client -// side only. -// It can be safely read only after stream has ended that is either read -// or write have returned io.EOF. -func (s *Stream) Trailer() metadata.MD { - c := s.trailer.Copy() - return c -} - -// ServerTransport returns the underlying ServerTransport for the stream. -// The client side stream always returns nil. -func (s *Stream) ServerTransport() ServerTransport { - return s.st -} - -// ContentSubtype returns the content-subtype for a request. For example, a -// content-subtype of "proto" will result in a content-type of -// "application/grpc+proto". This will always be lowercase. See -// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for -// more details. -func (s *Stream) ContentSubtype() string { - return s.contentSubtype -} - -// Context returns the context of the stream. -func (s *Stream) Context() context.Context { - return s.ctx -} - -// Method returns the method for the stream. -func (s *Stream) Method() string { - return s.method -} - -// Status returns the status received from the server. -// Status can be read safely only after the stream has ended, -// that is, read or write has returned io.EOF. -func (s *Stream) Status() *status.Status { - return s.status -} - -// SetHeader sets the header metadata. This can be called multiple times. -// Server side only. -// This should not be called in parallel to other data writes. -func (s *Stream) SetHeader(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - if s.isHeaderSent() || s.getState() == streamDone { - return ErrIllegalHeaderWrite - } - s.hdrMu.Lock() - s.header = metadata.Join(s.header, md) - s.hdrMu.Unlock() - return nil -} - -// SendHeader sends the given header metadata. The given metadata is -// combined with any metadata set by previous calls to SetHeader and -// then written to the transport stream. -func (s *Stream) SendHeader(md metadata.MD) error { - t := s.ServerTransport() - return t.WriteHeader(s, md) -} - -// SetTrailer sets the trailer metadata which will be sent with the RPC status -// by the server. This can be called multiple times. Server side only. -// This should not be called parallel to other data writes. -func (s *Stream) SetTrailer(md metadata.MD) error { - if md.Len() == 0 { - return nil - } - if s.getState() == streamDone { - return ErrIllegalHeaderWrite - } - s.hdrMu.Lock() - s.trailer = metadata.Join(s.trailer, md) - s.hdrMu.Unlock() - return nil -} - -func (s *Stream) write(m recvMsg) { - s.buf.put(m) -} - -// Read reads all p bytes from the wire for this stream. -func (s *Stream) Read(p []byte) (n int, err error) { - // Don't request a read if there was an error earlier - if er := s.trReader.(*transportReader).er; er != nil { - return 0, er - } - s.requestRead(len(p)) - return io.ReadFull(s.trReader, p) -} - -// tranportReader reads all the data available for this Stream from the transport and -// passes them into the decoder, which converts them into a gRPC message stream. -// The error is io.EOF when the stream is done or another non-nil error if -// the stream broke. -type transportReader struct { - reader io.Reader - // The handler to control the window update procedure for both this - // particular stream and the associated transport. - windowHandler func(int) - er error -} - -func (t *transportReader) Read(p []byte) (n int, err error) { - n, err = t.reader.Read(p) - if err != nil { - t.er = err - return - } - t.windowHandler(n) - return -} - -// BytesReceived indicates whether any bytes have been received on this stream. -func (s *Stream) BytesReceived() bool { - return atomic.LoadUint32(&s.bytesReceived) == 1 -} - -// Unprocessed indicates whether the server did not process this stream -- -// i.e. it sent a refused stream or GOAWAY including this stream ID. -func (s *Stream) Unprocessed() bool { - return atomic.LoadUint32(&s.unprocessed) == 1 -} - -// GoString is implemented by Stream so context.String() won't -// race when printing %#v. -func (s *Stream) GoString() string { - return fmt.Sprintf("", s, s.method) -} - -// state of transport -type transportState int - -const ( - reachable transportState = iota - closing - draining -) - -// ServerConfig consists of all the configurations to establish a server transport. -type ServerConfig struct { - MaxStreams uint32 - AuthInfo credentials.AuthInfo - InTapHandle tap.ServerInHandle - StatsHandler stats.Handler - KeepaliveParams keepalive.ServerParameters - KeepalivePolicy keepalive.EnforcementPolicy - InitialWindowSize int32 - InitialConnWindowSize int32 - WriteBufferSize int - ReadBufferSize int - ChannelzParentID int64 -} - -// NewServerTransport creates a ServerTransport with conn or non-nil error -// if it fails. -func NewServerTransport(protocol string, conn net.Conn, config *ServerConfig) (ServerTransport, error) { - return newHTTP2Server(conn, config) -} - -// ConnectOptions covers all relevant options for communicating with the server. -type ConnectOptions struct { - // UserAgent is the application user agent. - UserAgent string - // Authority is the :authority pseudo-header to use. This field has no effect if - // TransportCredentials is set. - Authority string - // Dialer specifies how to dial a network address. - Dialer func(context.Context, string) (net.Conn, error) - // FailOnNonTempDialError specifies if gRPC fails on non-temporary dial errors. - FailOnNonTempDialError bool - // PerRPCCredentials stores the PerRPCCredentials required to issue RPCs. - PerRPCCredentials []credentials.PerRPCCredentials - // TransportCredentials stores the Authenticator required to setup a client connection. - TransportCredentials credentials.TransportCredentials - // KeepaliveParams stores the keepalive parameters. - KeepaliveParams keepalive.ClientParameters - // StatsHandler stores the handler for stats. - StatsHandler stats.Handler - // InitialWindowSize sets the initial window size for a stream. - InitialWindowSize int32 - // InitialConnWindowSize sets the initial window size for a connection. - InitialConnWindowSize int32 - // WriteBufferSize sets the size of write buffer which in turn determines how much data can be batched before it's written on the wire. - WriteBufferSize int - // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. - ReadBufferSize int - // ChannelzParentID sets the addrConn id which initiate the creation of this client transport. - ChannelzParentID int64 -} - -// TargetInfo contains the information of the target such as network address and metadata. -type TargetInfo struct { - Addr string - Metadata interface{} - Authority string -} - -// NewClientTransport establishes the transport with the required ConnectOptions -// and returns it to the caller. -func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onSuccess func()) (ClientTransport, error) { - return newHTTP2Client(connectCtx, ctx, target, opts, onSuccess) -} - -// Options provides additional hints and information for message -// transmission. -type Options struct { - // Last indicates whether this write is the last piece for - // this stream. - Last bool - - // Delay is a hint to the transport implementation for whether - // the data could be buffered for a batching write. The - // transport implementation may ignore the hint. - Delay bool -} - -// CallHdr carries the information of a particular RPC. -type CallHdr struct { - // Host specifies the peer's host. - Host string - - // Method specifies the operation to perform. - Method string - - // SendCompress specifies the compression algorithm applied on - // outbound message. - SendCompress string - - // Creds specifies credentials.PerRPCCredentials for a call. - Creds credentials.PerRPCCredentials - - // Flush indicates whether a new stream command should be sent - // to the peer without waiting for the first data. This is - // only a hint. - // If it's true, the transport may modify the flush decision - // for performance purposes. - // If it's false, new stream will never be flushed. - Flush bool - - // ContentSubtype specifies the content-subtype for a request. For example, a - // content-subtype of "proto" will result in a content-type of - // "application/grpc+proto". The value of ContentSubtype must be all - // lowercase, otherwise the behavior is undefined. See - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests - // for more details. - ContentSubtype string -} - -// ClientTransport is the common interface for all gRPC client-side transport -// implementations. -type ClientTransport interface { - // Close tears down this transport. Once it returns, the transport - // should not be accessed any more. The caller must make sure this - // is called only once. - Close() error - - // GracefulClose starts to tear down the transport. It stops accepting - // new RPCs and wait the completion of the pending RPCs. - GracefulClose() error - - // Write sends the data for the given stream. A nil stream indicates - // the write is to be performed on the transport as a whole. - Write(s *Stream, hdr []byte, data []byte, opts *Options) error - - // NewStream creates a Stream for an RPC. - NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error) - - // CloseStream clears the footprint of a stream when the stream is - // not needed any more. The err indicates the error incurred when - // CloseStream is called. Must be called when a stream is finished - // unless the associated transport is closing. - CloseStream(stream *Stream, err error) - - // Error returns a channel that is closed when some I/O error - // happens. Typically the caller should have a goroutine to monitor - // this in order to take action (e.g., close the current transport - // and create a new one) in error case. It should not return nil - // once the transport is initiated. - Error() <-chan struct{} - - // GoAway returns a channel that is closed when ClientTransport - // receives the draining signal from the server (e.g., GOAWAY frame in - // HTTP/2). - GoAway() <-chan struct{} - - // GetGoAwayReason returns the reason why GoAway frame was received. - GetGoAwayReason() GoAwayReason - - // IncrMsgSent increments the number of message sent through this transport. - IncrMsgSent() - - // IncrMsgRecv increments the number of message received through this transport. - IncrMsgRecv() -} - -// ServerTransport is the common interface for all gRPC server-side transport -// implementations. -// -// Methods may be called concurrently from multiple goroutines, but -// Write methods for a given Stream will be called serially. -type ServerTransport interface { - // HandleStreams receives incoming streams using the given handler. - HandleStreams(func(*Stream), func(context.Context, string) context.Context) - - // WriteHeader sends the header metadata for the given stream. - // WriteHeader may not be called on all streams. - WriteHeader(s *Stream, md metadata.MD) error - - // Write sends the data for the given stream. - // Write may not be called on all streams. - Write(s *Stream, hdr []byte, data []byte, opts *Options) error - - // WriteStatus sends the status of a stream to the client. WriteStatus is - // the final call made on a stream and always occurs. - WriteStatus(s *Stream, st *status.Status) error - - // Close tears down the transport. Once it is called, the transport - // should not be accessed any more. All the pending streams and their - // handlers will be terminated asynchronously. - Close() error - - // RemoteAddr returns the remote network address. - RemoteAddr() net.Addr - - // Drain notifies the client this ServerTransport stops accepting new RPCs. - Drain() - - // IncrMsgSent increments the number of message sent through this transport. - IncrMsgSent() - - // IncrMsgRecv increments the number of message received through this transport. - IncrMsgRecv() -} - -// streamErrorf creates an StreamError with the specified error code and description. -func streamErrorf(c codes.Code, format string, a ...interface{}) StreamError { - return StreamError{ - Code: c, - Desc: fmt.Sprintf(format, a...), - } -} - -// connectionErrorf creates an ConnectionError with the specified error description. -func connectionErrorf(temp bool, e error, format string, a ...interface{}) ConnectionError { - return ConnectionError{ - Desc: fmt.Sprintf(format, a...), - temp: temp, - err: e, - } -} - -// ConnectionError is an error that results in the termination of the -// entire connection and the retry of all the active streams. -type ConnectionError struct { - Desc string - temp bool - err error -} - -func (e ConnectionError) Error() string { - return fmt.Sprintf("connection error: desc = %q", e.Desc) -} - -// Temporary indicates if this connection error is temporary or fatal. -func (e ConnectionError) Temporary() bool { - return e.temp -} - -// Origin returns the original error of this connection error. -func (e ConnectionError) Origin() error { - // Never return nil error here. - // If the original error is nil, return itself. - if e.err == nil { - return e - } - return e.err -} - -var ( - // ErrConnClosing indicates that the transport is closing. - ErrConnClosing = connectionErrorf(true, nil, "transport is closing") - // errStreamDrain indicates that the stream is rejected because the - // connection is draining. This could be caused by goaway or balancer - // removing the address. - errStreamDrain = streamErrorf(codes.Unavailable, "the connection is draining") - // errStreamDone is returned from write at the client side to indiacte application - // layer of an error. - errStreamDone = errors.New("the stream is done") - // StatusGoAway indicates that the server sent a GOAWAY that included this - // stream's ID in unprocessed RPCs. - statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection") -) - -// TODO: See if we can replace StreamError with status package errors. - -// StreamError is an error that only affects one stream within a connection. -type StreamError struct { - Code codes.Code - Desc string -} - -func (e StreamError) Error() string { - return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc) -} - -// GoAwayReason contains the reason for the GoAway frame received. -type GoAwayReason uint8 - -const ( - // GoAwayInvalid indicates that no GoAway frame is received. - GoAwayInvalid GoAwayReason = 0 - // GoAwayNoReason is the default value when GoAway frame is received. - GoAwayNoReason GoAwayReason = 1 - // GoAwayTooManyPings indicates that a GoAway frame with - // ErrCodeEnhanceYourCalm was received and that the debug data said - // "too_many_pings". - GoAwayTooManyPings GoAwayReason = 2 -) diff --git a/examples/google.golang.org/grpc/transport/transport_test.go b/examples/google.golang.org/grpc/transport/transport_test.go deleted file mode 100755 index b6add20..0000000 --- a/examples/google.golang.org/grpc/transport/transport_test.go +++ /dev/null @@ -1,2312 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package transport - -import ( - "bufio" - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "net" - "net/http" - "reflect" - "runtime" - "strconv" - "strings" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal/leakcheck" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/status" -) - -type server struct { - lis net.Listener - port string - startedErr chan error // error (or nil) with server start value - mu sync.Mutex - conns map[ServerTransport]bool - h *testStreamHandler - ready chan struct{} -} - -var ( - expectedRequest = []byte("ping") - expectedResponse = []byte("pong") - expectedRequestLarge = make([]byte, initialWindowSize*2) - expectedResponseLarge = make([]byte, initialWindowSize*2) - expectedInvalidHeaderField = "invalid/content-type" -) - -type testStreamHandler struct { - t *http2Server - notify chan struct{} - getNotified chan struct{} -} - -type hType int - -const ( - normal hType = iota - suspended - notifyCall - misbehaved - encodingRequiredStatus - invalidHeaderField - delayRead - pingpong -) - -func (h *testStreamHandler) handleStreamAndNotify(s *Stream) { - if h.notify == nil { - return - } - go func() { - select { - case <-h.notify: - default: - close(h.notify) - } - }() -} - -func (h *testStreamHandler) handleStream(t *testing.T, s *Stream) { - req := expectedRequest - resp := expectedResponse - if s.Method() == "foo.Large" { - req = expectedRequestLarge - resp = expectedResponseLarge - } - p := make([]byte, len(req)) - _, err := s.Read(p) - if err != nil { - return - } - if !bytes.Equal(p, req) { - t.Fatalf("handleStream got %v, want %v", p, req) - } - // send a response back to the client. - h.t.Write(s, nil, resp, &Options{}) - // send the trailer to end the stream. - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -func (h *testStreamHandler) handleStreamPingPong(t *testing.T, s *Stream) { - header := make([]byte, 5) - for { - if _, err := s.Read(header); err != nil { - if err == io.EOF { - h.t.WriteStatus(s, status.New(codes.OK, "")) - return - } - t.Fatalf("Error on server while reading data header: %v", err) - } - sz := binary.BigEndian.Uint32(header[1:]) - msg := make([]byte, int(sz)) - if _, err := s.Read(msg); err != nil { - t.Fatalf("Error on server while reading message: %v", err) - } - buf := make([]byte, sz+5) - buf[0] = byte(0) - binary.BigEndian.PutUint32(buf[1:], uint32(sz)) - copy(buf[5:], msg) - h.t.Write(s, nil, buf, &Options{}) - } -} - -func (h *testStreamHandler) handleStreamMisbehave(t *testing.T, s *Stream) { - conn, ok := s.ServerTransport().(*http2Server) - if !ok { - t.Fatalf("Failed to convert %v to *http2Server", s.ServerTransport()) - } - var sent int - p := make([]byte, http2MaxFrameLen) - for sent < initialWindowSize { - n := initialWindowSize - sent - // The last message may be smaller than http2MaxFrameLen - if n <= http2MaxFrameLen { - if s.Method() == "foo.Connection" { - // Violate connection level flow control window of client but do not - // violate any stream level windows. - p = make([]byte, n) - } else { - // Violate stream level flow control window of client. - p = make([]byte, n+1) - } - } - conn.controlBuf.put(&dataFrame{ - streamID: s.id, - h: nil, - d: p, - onEachWrite: func() {}, - }) - sent += len(p) - } -} - -func (h *testStreamHandler) handleStreamEncodingRequiredStatus(t *testing.T, s *Stream) { - // raw newline is not accepted by http2 framer so it must be encoded. - h.t.WriteStatus(s, encodingTestStatus) -} - -func (h *testStreamHandler) handleStreamInvalidHeaderField(t *testing.T, s *Stream) { - headerFields := []hpack.HeaderField{} - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: expectedInvalidHeaderField}) - h.t.controlBuf.put(&headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: false, - }) -} - -// handleStreamDelayRead delays reads so that the other side has to halt on -// stream-level flow control. -// This handler assumes dynamic flow control is turned off and assumes window -// sizes to be set to defaultWindowSize. -func (h *testStreamHandler) handleStreamDelayRead(t *testing.T, s *Stream) { - req := expectedRequest - resp := expectedResponse - if s.Method() == "foo.Large" { - req = expectedRequestLarge - resp = expectedResponseLarge - } - var ( - mu sync.Mutex - total int - ) - s.wq.replenish = func(n int) { - mu.Lock() - total += n - mu.Unlock() - s.wq.realReplenish(n) - } - getTotal := func() int { - mu.Lock() - defer mu.Unlock() - return total - } - done := make(chan struct{}) - defer close(done) - go func() { - for { - select { - // Prevent goroutine from leaking. - case <-done: - return - default: - } - if getTotal() == defaultWindowSize { - // Signal the client to start reading and - // thereby send window update. - close(h.notify) - return - } - runtime.Gosched() - } - }() - p := make([]byte, len(req)) - - // Let the other side run out of stream-level window before - // starting to read and thereby sending a window update. - timer := time.NewTimer(time.Second * 10) - select { - case <-h.getNotified: - timer.Stop() - case <-timer.C: - t.Errorf("Server timed-out.") - return - } - _, err := s.Read(p) - if err != nil { - t.Errorf("s.Read(_) = _, %v, want _, ", err) - return - } - - if !bytes.Equal(p, req) { - t.Errorf("handleStream got %v, want %v", p, req) - return - } - // This write will cause server to run out of stream level, - // flow control and the other side won't send a window update - // until that happens. - if err := h.t.Write(s, nil, resp, &Options{}); err != nil { - t.Errorf("server Write got %v, want ", err) - return - } - // Read one more time to ensure that everything remains fine and - // that the goroutine, that we launched earlier to signal client - // to read, gets enough time to process. - _, err = s.Read(p) - if err != nil { - t.Errorf("s.Read(_) = _, %v, want _, nil", err) - return - } - // send the trailer to end the stream. - if err := h.t.WriteStatus(s, status.New(codes.OK, "")); err != nil { - t.Errorf("server WriteStatus got %v, want ", err) - return - } -} - -// start starts server. Other goroutines should block on s.readyChan for further operations. -func (s *server) start(t *testing.T, port int, serverConfig *ServerConfig, ht hType) { - var err error - if port == 0 { - s.lis, err = net.Listen("tcp", "localhost:0") - } else { - s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port)) - } - if err != nil { - s.startedErr <- fmt.Errorf("failed to listen: %v", err) - return - } - _, p, err := net.SplitHostPort(s.lis.Addr().String()) - if err != nil { - s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err) - return - } - s.port = p - s.conns = make(map[ServerTransport]bool) - s.startedErr <- nil - for { - conn, err := s.lis.Accept() - if err != nil { - return - } - transport, err := NewServerTransport("http2", conn, serverConfig) - if err != nil { - return - } - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - transport.Close() - return - } - s.conns[transport] = true - h := &testStreamHandler{t: transport.(*http2Server)} - s.h = h - s.mu.Unlock() - switch ht { - case notifyCall: - go transport.HandleStreams(h.handleStreamAndNotify, - func(ctx context.Context, _ string) context.Context { - return ctx - }) - case suspended: - go transport.HandleStreams(func(*Stream) {}, // Do nothing to handle the stream. - func(ctx context.Context, method string) context.Context { - return ctx - }) - case misbehaved: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamMisbehave(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case encodingRequiredStatus: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamEncodingRequiredStatus(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case invalidHeaderField: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamInvalidHeaderField(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case delayRead: - h.notify = make(chan struct{}) - h.getNotified = make(chan struct{}) - s.mu.Lock() - close(s.ready) - s.mu.Unlock() - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamDelayRead(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case pingpong: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamPingPong(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - default: - go transport.HandleStreams(func(s *Stream) { - go h.handleStream(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - } - } -} - -func (s *server) wait(t *testing.T, timeout time.Duration) { - select { - case err := <-s.startedErr: - if err != nil { - t.Fatal(err) - } - case <-time.After(timeout): - t.Fatalf("Timed out after %v waiting for server to be ready", timeout) - } -} - -func (s *server) stop() { - s.lis.Close() - s.mu.Lock() - for c := range s.conns { - c.Close() - } - s.conns = nil - s.mu.Unlock() -} - -func setUpServerOnly(t *testing.T, port int, serverConfig *ServerConfig, ht hType) *server { - server := &server{startedErr: make(chan error, 1), ready: make(chan struct{})} - go server.start(t, port, serverConfig, ht) - server.wait(t, 2*time.Second) - return server -} - -func setUp(t *testing.T, port int, maxStreams uint32, ht hType) (*server, ClientTransport) { - return setUpWithOptions(t, port, &ServerConfig{MaxStreams: maxStreams}, ht, ConnectOptions{}, func() {}) -} - -func setUpWithOptions(t *testing.T, port int, serverConfig *ServerConfig, ht hType, copts ConnectOptions, onHandshake func()) (*server, ClientTransport) { - server := setUpServerOnly(t, port, serverConfig, ht) - addr := "localhost:" + server.port - var ( - ct ClientTransport - connErr error - ) - target := TargetInfo{ - Addr: addr, - } - connectCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)) - ct, connErr = NewClientTransport(connectCtx, context.Background(), target, copts, onHandshake) - if connErr != nil { - cancel() // Do not cancel in success path. - t.Fatalf("failed to create transport: %v", connErr) - } - return server, ct -} - -func setUpWithNoPingServer(t *testing.T, copts ConnectOptions, done chan net.Conn) ClientTransport { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - // Launch a non responsive server. - go func() { - defer lis.Close() - conn, err := lis.Accept() - if err != nil { - t.Errorf("Error at server-side while accepting: %v", err) - close(done) - return - } - done <- conn - }() - connectCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)) - tr, err := NewClientTransport(connectCtx, context.Background(), TargetInfo{Addr: lis.Addr().String()}, copts, func() {}) - if err != nil { - cancel() // Do not cancel in success path. - // Server clean-up. - lis.Close() - if conn, ok := <-done; ok { - conn.Close() - } - t.Fatalf("Failed to dial: %v", err) - } - return tr -} - -// TestInflightStreamClosing ensures that closing in-flight stream -// sends StreamError to concurrent stream reader. -func TestInflightStreamClosing(t *testing.T) { - serverConfig := &ServerConfig{} - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - - stream, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - - donec := make(chan struct{}) - serr := StreamError{Desc: "client connection is closing"} - go func() { - defer close(donec) - if _, err := stream.Read(make([]byte, defaultWindowSize)); err != serr { - t.Errorf("unexpected Stream error %v, expected %v", err, serr) - } - }() - - // should unblock concurrent stream.Read - client.CloseStream(stream, serr) - - // wait for stream.Read error - timeout := time.NewTimer(5 * time.Second) - select { - case <-donec: - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timed out, expected a StreamError.") - } -} - -// TestMaxConnectionIdle tests that a server will send GoAway to a idle client. -// An idle client is one who doesn't make any RPC calls for a duration of -// MaxConnectionIdle time. -func TestMaxConnectionIdle(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionIdle: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - stream, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - client.(*http2Client).closeStream(stream, io.EOF, true, http2.ErrCodeCancel, nil, nil, false) - // wait for server to see that closed stream and max-age logic to send goaway after no new RPCs are mode - timeout := time.NewTimer(time.Second * 4) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timed out, expected a GoAway from the server.") - } -} - -// TestMaxConenctionIdleNegative tests that a server will not send GoAway to a non-idle(busy) client. -func TestMaxConnectionIdleNegative(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionIdle: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - timeout := time.NewTimer(time.Second * 4) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - t.Fatalf("A non-idle client received a GoAway.") - case <-timeout.C: - } - -} - -// TestMaxConnectionAge tests that a server will send GoAway after a duration of MaxConnectionAge. -func TestMaxConnectionAge(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionAge: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - _, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Client failed to create stream: %v", err) - } - // Wait for max-age logic to send GoAway. - timeout := time.NewTimer(4 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timer out, expected a GoAway from the server.") - } -} - -// TestKeepaliveServer tests that a server closes connection with a client that doesn't respond to keepalive pings. -func TestKeepaliveServer(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - Time: 2 * time.Second, - Timeout: 1 * time.Second, - }, - } - server, c := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer c.Close() - client, err := net.Dial("tcp", server.lis.Addr().String()) - if err != nil { - t.Fatalf("Failed to dial: %v", err) - } - defer client.Close() - - // Set read deadline on client conn so that it doesn't block forever in errorsome cases. - client.SetDeadline(time.Now().Add(10 * time.Second)) - - if n, err := client.Write(clientPreface); err != nil || n != len(clientPreface) { - t.Fatalf("Error writing client preface; n=%v, err=%v", n, err) - } - framer := newFramer(client, defaultWriteBufSize, defaultReadBufSize) - if err := framer.fr.WriteSettings(http2.Setting{}); err != nil { - t.Fatal("Error writing settings frame:", err) - } - framer.writer.Flush() - // Wait for keepalive logic to close the connection. - time.Sleep(4 * time.Second) - b := make([]byte, 24) - for { - _, err = client.Read(b) - if err == nil { - continue - } - if err != io.EOF { - t.Fatalf("client.Read(_) = _,%v, want io.EOF", err) - } - break - } -} - -// TestKeepaliveServerNegative tests that a server doesn't close connection with a client that responds to keepalive pings. -func TestKeepaliveServerNegative(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - Time: 2 * time.Second, - Timeout: 1 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - // Give keepalive logic some time by sleeping. - time.Sleep(4 * time.Second) - // Assert that client is still active. - clientTr := client.(*http2Client) - clientTr.mu.Lock() - defer clientTr.mu.Unlock() - if clientTr.state != reachable { - t.Fatalf("Test failed: Expected server-client connection to be healthy.") - } -} - -func TestKeepaliveClientClosesIdleTransport(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - PermitWithoutStream: true, // Run keepalive even with no RPCs. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("Server didn't return connection object") - } - defer conn.Close() - // Sleep for keepalive to close the connection. - time.Sleep(4 * time.Second) - // Assert that the connection was closed. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test Failed: Expected client transport to have closed.") - } -} - -func TestKeepaliveClientStaysHealthyOnIdleTransport(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("server didn't reutrn connection object") - } - defer conn.Close() - // Give keepalive some time. - time.Sleep(4 * time.Second) - // Assert that connections is still healthy. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected client transport to be healthy.") - } -} - -func TestKeepaliveClientClosesWithActiveStreams(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("Server didn't return connection object") - } - defer conn.Close() - // Create a stream. - _, err := tr.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create a new stream: %v", err) - } - // Give keepalive some time. - time.Sleep(4 * time.Second) - // Assert that transport was closed. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected client transport to have closed.") - } -} - -func TestKeepaliveClientStaysHealthyWithResponsiveServer(t *testing.T) { - s, tr := setUpWithOptions(t, 0, &ServerConfig{MaxStreams: math.MaxUint32}, normal, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - PermitWithoutStream: true, // Run keepalive even with no RPCs. - }}, func() {}) - defer s.stop() - defer tr.Close() - // Give keep alive some time. - time.Sleep(4 * time.Second) - // Assert that transport is healthy. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected client transport to be healthy.") - } -} - -func TestKeepaliveServerEnforcementWithAbusiveClientNoRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 2 * time.Second, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 1 * time.Second, - PermitWithoutStream: true, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, normal, clientOptions, func() {}) - defer server.stop() - defer client.Close() - - timeout := time.NewTimer(10 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test failed: Expected a GoAway from server.") - } - time.Sleep(500 * time.Millisecond) - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected the connection to be closed.") - } -} - -func TestKeepaliveServerEnforcementWithAbusiveClientWithRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 2 * time.Second, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 1 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions, func() {}) - defer server.stop() - defer client.Close() - - if _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}); err != nil { - t.Fatalf("Client failed to create stream.") - } - timeout := time.NewTimer(10 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test failed: Expected a GoAway from server.") - } - time.Sleep(500 * time.Millisecond) - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected the connection to be closed.") - } -} - -func TestKeepaliveServerEnforcementWithObeyingClientNoRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 100 * time.Millisecond, - PermitWithoutStream: true, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 101 * time.Millisecond, - Timeout: 1 * time.Second, - PermitWithoutStream: true, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, normal, clientOptions, func() {}) - defer server.stop() - defer client.Close() - - // Give keepalive enough time. - time.Sleep(3 * time.Second) - // Assert that connection is healthy. - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected connection to be healthy.") - } -} - -func TestKeepaliveServerEnforcementWithObeyingClientWithRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 100 * time.Millisecond, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 101 * time.Millisecond, - Timeout: 1 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions, func() {}) - defer server.stop() - defer client.Close() - - if _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}); err != nil { - t.Fatalf("Client failed to create stream.") - } - - // Give keepalive enough time. - time.Sleep(3 * time.Second) - // Assert that connection is healthy. - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected connection to be healthy.") - } -} - -func TestClientSendAndReceive(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Small", - } - s1, err1 := ct.NewStream(context.Background(), callHdr) - if err1 != nil { - t.Fatalf("failed to open stream: %v", err1) - } - if s1.id != 1 { - t.Fatalf("wrong stream id: %d", s1.id) - } - s2, err2 := ct.NewStream(context.Background(), callHdr) - if err2 != nil { - t.Fatalf("failed to open stream: %v", err2) - } - if s2.id != 3 { - t.Fatalf("wrong stream id: %d", s2.id) - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s1, nil, expectedRequest, &opts); err != nil && err != io.EOF { - t.Fatalf("failed to send data: %v", err) - } - p := make([]byte, len(expectedResponse)) - _, recvErr := s1.Read(p) - if recvErr != nil || !bytes.Equal(p, expectedResponse) { - t.Fatalf("Error: %v, want ; Result: %v, want %v", recvErr, p, expectedResponse) - } - _, recvErr = s1.Read(p) - if recvErr != io.EOF { - t.Fatalf("Error: %v; want ", recvErr) - } - ct.Close() - server.stop() -} - -func TestClientErrorNotify(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - go server.stop() - // ct.reader should detect the error and activate ct.Error(). - <-ct.Error() - ct.Close() -} - -func performOneRPC(ct ClientTransport) { - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Small", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s, []byte{}, expectedRequest, &opts); err == nil || err == io.EOF { - time.Sleep(5 * time.Millisecond) - // The following s.Recv()'s could error out because the - // underlying transport is gone. - // - // Read response - p := make([]byte, len(expectedResponse)) - s.Read(p) - // Read io.EOF - s.Read(p) - } -} - -func TestClientMix(t *testing.T) { - s, ct := setUp(t, 0, math.MaxUint32, normal) - go func(s *server) { - time.Sleep(5 * time.Second) - s.stop() - }(s) - go func(ct ClientTransport) { - <-ct.Error() - ct.Close() - }(ct) - for i := 0; i < 1000; i++ { - time.Sleep(10 * time.Millisecond) - go performOneRPC(ct) - } -} - -func TestLargeMessage(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - var wg sync.WaitGroup - for i := 0; i < 2; i++ { - wg.Add(1) - go func() { - defer wg.Done() - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, ", ct, err) - } - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{Last: true, Delay: false}); err != nil && err != io.EOF { - t.Errorf("%v.Write(_, _, _) = %v, want ", ct, err) - } - p := make([]byte, len(expectedResponseLarge)) - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponseLarge) { - t.Errorf("s.Read(%v) = _, %v, want %v, ", err, p, expectedResponse) - } - if _, err = s.Read(p); err != io.EOF { - t.Errorf("Failed to complete the stream %v; want ", err) - } - }() - } - wg.Wait() - ct.Close() - server.stop() -} - -func TestLargeMessageWithDelayRead(t *testing.T) { - // Disable dynamic flow control. - sc := &ServerConfig{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - co := ConnectOptions{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - server, ct := setUpWithOptions(t, 0, sc, delayRead, co, func() {}) - defer server.stop() - defer ct.Close() - server.mu.Lock() - ready := server.ready - server.mu.Unlock() - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10)) - defer cancel() - s, err := ct.NewStream(ctx, callHdr) - if err != nil { - t.Fatalf("%v.NewStream(_, _) = _, %v, want _, ", ct, err) - return - } - // Wait for server's handerler to be initialized - select { - case <-ready: - case <-ctx.Done(): - t.Fatalf("Client timed out waiting for server handler to be initialized.") - } - server.mu.Lock() - serviceHandler := server.h - server.mu.Unlock() - var ( - mu sync.Mutex - total int - ) - s.wq.replenish = func(n int) { - mu.Lock() - total += n - mu.Unlock() - s.wq.realReplenish(n) - } - getTotal := func() int { - mu.Lock() - defer mu.Unlock() - return total - } - done := make(chan struct{}) - defer close(done) - go func() { - for { - select { - // Prevent goroutine from leaking in case of error. - case <-done: - return - default: - } - if getTotal() == defaultWindowSize { - // unblock server to be able to read and - // thereby send stream level window update. - close(serviceHandler.getNotified) - return - } - runtime.Gosched() - } - }() - // This write will cause client to run out of stream level, - // flow control and the other side won't send a window update - // until that happens. - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{}); err != nil { - t.Fatalf("write(_, _, _) = %v, want ", err) - } - p := make([]byte, len(expectedResponseLarge)) - - // Wait for the other side to run out of stream level flow control before - // reading and thereby sending a window update. - select { - case <-serviceHandler.notify: - case <-ctx.Done(): - t.Fatalf("Client timed out") - } - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponseLarge) { - t.Fatalf("s.Read(_) = _, %v, want _, ", err) - } - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{Last: true}); err != nil { - t.Fatalf("Write(_, _, _) = %v, want ", err) - } - if _, err = s.Read(p); err != io.EOF { - t.Fatalf("Failed to complete the stream %v; want ", err) - } -} - -func TestGracefulClose(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, pingpong) - defer func() { - // Stop the server's listener to make the server's goroutines terminate - // (after the last active stream is done). - server.lis.Close() - // Check for goroutine leaks (i.e. GracefulClose with an active stream - // doesn't eventually close the connection when that stream completes). - leakcheck.Check(t) - // Correctly clean up the server - server.stop() - }() - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10)) - defer cancel() - s, err := ct.NewStream(ctx, &CallHdr{}) - if err != nil { - t.Fatalf("NewStream(_, _) = _, %v, want _, ", err) - } - msg := make([]byte, 1024) - outgoingHeader := make([]byte, 5) - outgoingHeader[0] = byte(0) - binary.BigEndian.PutUint32(outgoingHeader[1:], uint32(len(msg))) - incomingHeader := make([]byte, 5) - if err := ct.Write(s, outgoingHeader, msg, &Options{}); err != nil { - t.Fatalf("Error while writing: %v", err) - } - if _, err := s.Read(incomingHeader); err != nil { - t.Fatalf("Error while reading: %v", err) - } - sz := binary.BigEndian.Uint32(incomingHeader[1:]) - recvMsg := make([]byte, int(sz)) - if _, err := s.Read(recvMsg); err != nil { - t.Fatalf("Error while reading: %v", err) - } - if err = ct.GracefulClose(); err != nil { - t.Fatalf("GracefulClose() = %v, want ", err) - } - var wg sync.WaitGroup - // Expect the failure for all the follow-up streams because ct has been closed gracefully. - for i := 0; i < 200; i++ { - wg.Add(1) - go func() { - defer wg.Done() - str, err := ct.NewStream(context.Background(), &CallHdr{}) - if err == ErrConnClosing { - return - } else if err != nil { - t.Errorf("_.NewStream(_, _) = _, %v, want _, %v", err, ErrConnClosing) - return - } - ct.Write(str, nil, nil, &Options{Last: true}) - if _, err := str.Read(make([]byte, 8)); err != errStreamDrain && err != ErrConnClosing { - t.Errorf("_.Read(_) = _, %v, want _, %v or %v", err, errStreamDrain, ErrConnClosing) - } - }() - } - ct.Write(s, nil, nil, &Options{Last: true}) - if _, err := s.Read(incomingHeader); err != io.EOF { - t.Fatalf("Client expected EOF from the server. Got: %v", err) - } - // The stream which was created before graceful close can still proceed. - wg.Wait() -} - -func TestLargeMessageSuspension(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - // Set a long enough timeout for writing a large message out. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - s, err := ct.NewStream(ctx, callHdr) - if err != nil { - t.Fatalf("failed to open stream: %v", err) - } - // Launch a goroutine simillar to the stream monitoring goroutine in - // stream.go to keep track of context timeout and call CloseStream. - go func() { - <-ctx.Done() - ct.CloseStream(s, ContextErr(ctx.Err())) - }() - // Write should not be done successfully due to flow control. - msg := make([]byte, initialWindowSize*8) - ct.Write(s, nil, msg, &Options{}) - err = ct.Write(s, nil, msg, &Options{Last: true}) - if err != errStreamDone { - t.Fatalf("Write got %v, want io.EOF", err) - } - expectedErr := streamErrorf(codes.DeadlineExceeded, "%v", context.DeadlineExceeded) - if _, err := s.Read(make([]byte, 8)); err != expectedErr { - t.Fatalf("Read got %v of type %T, want %v", err, err, expectedErr) - } - ct.Close() - server.stop() -} - -func TestMaxStreams(t *testing.T) { - serverConfig := &ServerConfig{ - MaxStreams: 1, - } - server, ct := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer ct.Close() - defer server.stop() - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - // Keep creating streams until one fails with deadline exceeded, marking the application - // of server settings on client. - slist := []*Stream{} - pctx, cancel := context.WithCancel(context.Background()) - defer cancel() - timer := time.NewTimer(time.Second * 10) - expectedErr := streamErrorf(codes.DeadlineExceeded, "%v", context.DeadlineExceeded) - for { - select { - case <-timer.C: - t.Fatalf("Test timeout: client didn't receive server settings.") - default: - } - ctx, cancel := context.WithDeadline(pctx, time.Now().Add(time.Second)) - // This is only to get rid of govet. All these context are based on a base - // context which is canceled at the end of the test. - defer cancel() - if str, err := ct.NewStream(ctx, callHdr); err == nil { - slist = append(slist, str) - continue - } else if err != expectedErr { - t.Fatalf("ct.NewStream(_,_) = _, %v, want _, %v", err, expectedErr) - } - timer.Stop() - break - } - done := make(chan struct{}) - // Try and create a new stream. - go func() { - defer close(done) - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*10)) - defer cancel() - if _, err := ct.NewStream(ctx, callHdr); err != nil { - t.Errorf("Failed to open stream: %v", err) - } - }() - // Close all the extra streams created and make sure the new stream is not created. - for _, str := range slist { - ct.CloseStream(str, nil) - } - select { - case <-done: - t.Fatalf("Test failed: didn't expect new stream to be created just yet.") - default: - } - // Close the first stream created so that the new stream can finally be created. - ct.CloseStream(s, nil) - <-done - ct.Close() - cc := ct.(*http2Client) - <-cc.writerDone - if cc.maxConcurrentStreams != 1 { - t.Fatalf("cc.maxConcurrentStreams: %d, want 1", cc.maxConcurrentStreams) - } -} - -func TestServerContextCanceledOnClosedConnection(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - var sc *http2Server - // Wait until the server transport is setup. - for { - server.mu.Lock() - if len(server.conns) == 0 { - server.mu.Unlock() - time.Sleep(time.Millisecond) - continue - } - for k := range server.conns { - var ok bool - sc, ok = k.(*http2Server) - if !ok { - t.Fatalf("Failed to convert %v to *http2Server", k) - } - } - server.mu.Unlock() - break - } - cc, ok := ct.(*http2Client) - if !ok { - t.Fatalf("Failed to convert %v to *http2Client", ct) - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - cc.controlBuf.put(&dataFrame{ - streamID: s.id, - endStream: false, - h: nil, - d: make([]byte, http2MaxFrameLen), - onEachWrite: func() {}, - }) - // Loop until the server side stream is created. - var ss *Stream - for { - time.Sleep(time.Second) - sc.mu.Lock() - if len(sc.activeStreams) == 0 { - sc.mu.Unlock() - continue - } - ss = sc.activeStreams[s.id] - sc.mu.Unlock() - break - } - cc.Close() - select { - case <-ss.Context().Done(): - if ss.Context().Err() != context.Canceled { - t.Fatalf("ss.Context().Err() got %v, want %v", ss.Context().Err(), context.Canceled) - } - case <-time.After(5 * time.Second): - t.Fatalf("Failed to cancel the context of the sever side stream.") - } - server.stop() -} - -func TestClientConnDecoupledFromApplicationRead(t *testing.T) { - connectOptions := ConnectOptions{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - server, client := setUpWithOptions(t, 0, &ServerConfig{}, notifyCall, connectOptions, func() {}) - defer server.stop() - defer client.Close() - - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - - if len(server.conns) == 0 { - return true, fmt.Errorf("timed-out while waiting for connection to be created on the server") - } - return false, nil - }) - - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - notifyChan := make(chan struct{}) - server.h.notify = notifyChan - server.mu.Unlock() - cstream1, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create first stream. Err: %v", err) - } - - <-notifyChan - var sstream1 *Stream - // Access stream on the server. - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == cstream1.id { - sstream1 = v - } - } - st.mu.Unlock() - if sstream1 == nil { - t.Fatalf("Didn't find stream corresponding to client cstream.id: %v on the server", cstream1.id) - } - // Exhaust client's connection window. - if err := st.Write(sstream1, []byte{}, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Server failed to write data. Err: %v", err) - } - notifyChan = make(chan struct{}) - server.mu.Lock() - server.h.notify = notifyChan - server.mu.Unlock() - // Create another stream on client. - cstream2, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create second stream. Err: %v", err) - } - <-notifyChan - var sstream2 *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == cstream2.id { - sstream2 = v - } - } - st.mu.Unlock() - if sstream2 == nil { - t.Fatalf("Didn't find stream corresponding to client cstream.id: %v on the server", cstream2.id) - } - // Server should be able to send data on the new stream, even though the client hasn't read anything on the first stream. - if err := st.Write(sstream2, []byte{}, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Server failed to write data. Err: %v", err) - } - - // Client should be able to read data on second stream. - if _, err := cstream2.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = _, %v, want _, ", err) - } - - // Client should be able to read data on first stream. - if _, err := cstream1.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = _, %v, want _, ", err) - } -} - -func TestServerConnDecoupledFromApplicationRead(t *testing.T) { - serverConfig := &ServerConfig{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}, func() {}) - defer server.stop() - defer client.Close() - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - - if len(server.conns) == 0 { - return true, fmt.Errorf("timed-out while waiting for connection to be created on the server") - } - return false, nil - }) - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - server.mu.Unlock() - cstream1, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create 1st stream. Err: %v", err) - } - // Exhaust server's connection window. - if err := client.Write(cstream1, nil, make([]byte, defaultWindowSize), &Options{Last: true}); err != nil { - t.Fatalf("Client failed to write data. Err: %v", err) - } - //Client should be able to create another stream and send data on it. - cstream2, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create 2nd stream. Err: %v", err) - } - if err := client.Write(cstream2, nil, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Client failed to write data. Err: %v", err) - } - // Get the streams on server. - waitWhileTrue(t, func() (bool, error) { - st.mu.Lock() - defer st.mu.Unlock() - - if len(st.activeStreams) != 2 { - return true, fmt.Errorf("timed-out while waiting for server to have created the streams") - } - return false, nil - }) - var sstream1 *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == 1 { - sstream1 = v - } - } - st.mu.Unlock() - // Reading from the stream on server should succeed. - if _, err := sstream1.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = %v, want ", err) - } - - if _, err := sstream1.Read(make([]byte, 1)); err != io.EOF { - t.Fatalf("_.Read(_) = %v, want io.EOF", err) - } - -} - -func TestServerWithMisbehavedClient(t *testing.T) { - server := setUpServerOnly(t, 0, &ServerConfig{}, suspended) - defer server.stop() - // Create a client that can override server stream quota. - mconn, err := net.Dial("tcp", server.lis.Addr().String()) - if err != nil { - t.Fatalf("Clent failed to dial:%v", err) - } - defer mconn.Close() - if err := mconn.SetWriteDeadline(time.Now().Add(time.Second * 10)); err != nil { - t.Fatalf("Failed to set write deadline: %v", err) - } - if n, err := mconn.Write(clientPreface); err != nil || n != len(clientPreface) { - t.Fatalf("mconn.Write(clientPreface) = %d, %v, want %d, ", n, err, len(clientPreface)) - } - // success chan indicates that reader received a RSTStream from server. - success := make(chan struct{}) - var mu sync.Mutex - framer := http2.NewFramer(mconn, mconn) - if err := framer.WriteSettings(); err != nil { - t.Fatalf("Error while writing settings: %v", err) - } - go func() { // Launch a reader for this misbehaving client. - for { - frame, err := framer.ReadFrame() - if err != nil { - return - } - switch frame := frame.(type) { - case *http2.PingFrame: - // Write ping ack back so that server's BDP estimation works right. - mu.Lock() - framer.WritePing(true, frame.Data) - mu.Unlock() - case *http2.RSTStreamFrame: - if frame.Header().StreamID != 1 || http2.ErrCode(frame.ErrCode) != http2.ErrCodeFlowControl { - t.Errorf("RST stream received with streamID: %d and code: %v, want streamID: 1 and code: http2.ErrCodeFlowControl", frame.Header().StreamID, http2.ErrCode(frame.ErrCode)) - } - close(success) - return - default: - // Do nothing. - } - - } - }() - // Create a stream. - var buf bytes.Buffer - henc := hpack.NewEncoder(&buf) - // TODO(mmukhi): Remove unnecessary fields. - if err := henc.WriteField(hpack.HeaderField{Name: ":method", Value: "POST"}); err != nil { - t.Fatalf("Error while encoding header: %v", err) - } - if err := henc.WriteField(hpack.HeaderField{Name: ":path", Value: "foo"}); err != nil { - t.Fatalf("Error while encoding header: %v", err) - } - if err := henc.WriteField(hpack.HeaderField{Name: ":authority", Value: "localhost"}); err != nil { - t.Fatalf("Error while encoding header: %v", err) - } - if err := henc.WriteField(hpack.HeaderField{Name: "content-type", Value: "application/grpc"}); err != nil { - t.Fatalf("Error while encoding header: %v", err) - } - mu.Lock() - if err := framer.WriteHeaders(http2.HeadersFrameParam{StreamID: 1, BlockFragment: buf.Bytes(), EndHeaders: true}); err != nil { - mu.Unlock() - t.Fatalf("Error while writing headers: %v", err) - } - mu.Unlock() - - // Test server behavior for violation of stream flow control window size restriction. - timer := time.NewTimer(time.Second * 5) - dbuf := make([]byte, http2MaxFrameLen) - for { - select { - case <-timer.C: - t.Fatalf("Test timed out.") - case <-success: - return - default: - } - mu.Lock() - if err := framer.WriteData(1, false, dbuf); err != nil { - mu.Unlock() - // Error here means the server could have closed the connection due to flow control - // violation. Make sure that is the case by waiting for success chan to be closed. - select { - case <-timer.C: - t.Fatalf("Error while writing data: %v", err) - case <-success: - return - } - } - mu.Unlock() - // This for loop is capable of hogging the CPU and cause starvation - // in Go versions prior to 1.9, - // in single CPU environment. Explicitly relinquish processor. - runtime.Gosched() - } -} - -func TestClientWithMisbehavedServer(t *testing.T) { - // Create a misbehaving server. - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error while listening: %v", err) - } - defer lis.Close() - // success chan indicates that the server received - // RSTStream from the client. - success := make(chan struct{}) - go func() { // Launch the misbehaving server. - sconn, err := lis.Accept() - if err != nil { - t.Errorf("Error while accepting: %v", err) - return - } - defer sconn.Close() - if _, err := io.ReadFull(sconn, make([]byte, len(clientPreface))); err != nil { - t.Errorf("Error while reading clieng preface: %v", err) - return - } - sfr := http2.NewFramer(sconn, sconn) - if err := sfr.WriteSettingsAck(); err != nil { - t.Errorf("Error while writing settings: %v", err) - return - } - var mu sync.Mutex - for { - frame, err := sfr.ReadFrame() - if err != nil { - return - } - switch frame := frame.(type) { - case *http2.HeadersFrame: - // When the client creates a stream, violate the stream flow control. - go func() { - buf := make([]byte, http2MaxFrameLen) - for { - mu.Lock() - if err := sfr.WriteData(1, false, buf); err != nil { - mu.Unlock() - return - } - mu.Unlock() - // This for loop is capable of hogging the CPU and cause starvation - // in Go versions prior to 1.9, - // in single CPU environment. Explicitly relinquish processor. - runtime.Gosched() - } - }() - case *http2.RSTStreamFrame: - if frame.Header().StreamID != 1 || http2.ErrCode(frame.ErrCode) != http2.ErrCodeFlowControl { - t.Errorf("RST stream received with streamID: %d and code: %v, want streamID: 1 and code: http2.ErrCodeFlowControl", frame.Header().StreamID, http2.ErrCode(frame.ErrCode)) - } - close(success) - return - case *http2.PingFrame: - mu.Lock() - sfr.WritePing(true, frame.Data) - mu.Unlock() - default: - } - } - }() - connectCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)) - defer cancel() - ct, err := NewClientTransport(connectCtx, context.Background(), TargetInfo{Addr: lis.Addr().String()}, ConnectOptions{}, func() {}) - if err != nil { - t.Fatalf("Error while creating client transport: %v", err) - } - defer ct.Close() - str, err := ct.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Error while creating stream: %v", err) - } - timer := time.NewTimer(time.Second * 5) - go func() { // This go routine mimics the one in stream.go to call CloseStream. - <-str.Done() - ct.CloseStream(str, nil) - }() - select { - case <-timer.C: - t.Fatalf("Test timed-out.") - case <-success: - } -} - -var encodingTestStatus = status.New(codes.Internal, "\n") - -func TestEncodingRequiredStatus(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, encodingRequiredStatus) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s, nil, expectedRequest, &opts); err != nil && err != errStreamDone { - t.Fatalf("Failed to write the request: %v", err) - } - p := make([]byte, http2MaxFrameLen) - if _, err := s.trReader.(*transportReader).Read(p); err != io.EOF { - t.Fatalf("Read got error %v, want %v", err, io.EOF) - } - if !reflect.DeepEqual(s.Status(), encodingTestStatus) { - t.Fatalf("stream with status %v, want %v", s.Status(), encodingTestStatus) - } - ct.Close() - server.stop() -} - -func TestInvalidHeaderField(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, invalidHeaderField) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - p := make([]byte, http2MaxFrameLen) - _, err = s.trReader.(*transportReader).Read(p) - if se, ok := err.(StreamError); !ok || se.Code != codes.Internal || !strings.Contains(err.Error(), expectedInvalidHeaderField) { - t.Fatalf("Read got error %v, want error with code %s and contains %q", err, codes.Internal, expectedInvalidHeaderField) - } - ct.Close() - server.stop() -} - -func TestIsReservedHeader(t *testing.T) { - tests := []struct { - h string - want bool - }{ - {"", false}, // but should be rejected earlier - {"foo", false}, - {"content-type", true}, - {"user-agent", true}, - {":anything", true}, - {"grpc-message-type", true}, - {"grpc-encoding", true}, - {"grpc-message", true}, - {"grpc-status", true}, - {"grpc-timeout", true}, - {"te", true}, - } - for _, tt := range tests { - got := isReservedHeader(tt.h) - if got != tt.want { - t.Errorf("isReservedHeader(%q) = %v; want %v", tt.h, got, tt.want) - } - } -} - -func TestContextErr(t *testing.T) { - for _, test := range []struct { - // input - errIn error - // outputs - errOut StreamError - }{ - {context.DeadlineExceeded, StreamError{codes.DeadlineExceeded, context.DeadlineExceeded.Error()}}, - {context.Canceled, StreamError{codes.Canceled, context.Canceled.Error()}}, - } { - err := ContextErr(test.errIn) - if err != test.errOut { - t.Fatalf("ContextErr{%v} = %v \nwant %v", test.errIn, err, test.errOut) - } - } -} - -func max(a, b int32) int32 { - if a > b { - return a - } - return b -} - -type windowSizeConfig struct { - serverStream int32 - serverConn int32 - clientStream int32 - clientConn int32 -} - -func TestAccountCheckWindowSizeWithLargeWindow(t *testing.T) { - wc := windowSizeConfig{ - serverStream: 10 * 1024 * 1024, - serverConn: 12 * 1024 * 1024, - clientStream: 6 * 1024 * 1024, - clientConn: 8 * 1024 * 1024, - } - testFlowControlAccountCheck(t, 1024*1024, wc) -} - -func TestAccountCheckWindowSizeWithSmallWindow(t *testing.T) { - wc := windowSizeConfig{ - serverStream: defaultWindowSize, - // Note this is smaller than initialConnWindowSize which is the current default. - serverConn: defaultWindowSize, - clientStream: defaultWindowSize, - clientConn: defaultWindowSize, - } - testFlowControlAccountCheck(t, 1024*1024, wc) -} - -func TestAccountCheckDynamicWindowSmallMessage(t *testing.T) { - testFlowControlAccountCheck(t, 1024, windowSizeConfig{}) -} - -func TestAccountCheckDynamicWindowLargeMessage(t *testing.T) { - testFlowControlAccountCheck(t, 1024*1024, windowSizeConfig{}) -} - -func testFlowControlAccountCheck(t *testing.T, msgSize int, wc windowSizeConfig) { - sc := &ServerConfig{ - InitialWindowSize: wc.serverStream, - InitialConnWindowSize: wc.serverConn, - } - co := ConnectOptions{ - InitialWindowSize: wc.clientStream, - InitialConnWindowSize: wc.clientConn, - } - server, client := setUpWithOptions(t, 0, sc, pingpong, co, func() {}) - defer server.stop() - defer client.Close() - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - if len(server.conns) == 0 { - return true, fmt.Errorf("timed out while waiting for server transport to be created") - } - return false, nil - }) - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - server.mu.Unlock() - ct := client.(*http2Client) - cstream, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Failed to create stream. Err: %v", err) - } - msg := make([]byte, msgSize) - buf := make([]byte, msgSize+5) - buf[0] = byte(0) - binary.BigEndian.PutUint32(buf[1:], uint32(msgSize)) - copy(buf[5:], msg) - opts := Options{} - header := make([]byte, 5) - for i := 1; i <= 10; i++ { - if err := ct.Write(cstream, nil, buf, &opts); err != nil { - t.Fatalf("Error on client while writing message: %v", err) - } - if _, err := cstream.Read(header); err != nil { - t.Fatalf("Error on client while reading data frame header: %v", err) - } - sz := binary.BigEndian.Uint32(header[1:]) - recvMsg := make([]byte, int(sz)) - if _, err := cstream.Read(recvMsg); err != nil { - t.Fatalf("Error on client while reading data: %v", err) - } - if len(recvMsg) != len(msg) { - t.Fatalf("Length of message received by client: %v, want: %v", len(recvMsg), len(msg)) - } - } - var sstream *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - sstream = v - } - st.mu.Unlock() - loopyServerStream := st.loopy.estdStreams[sstream.id] - loopyClientStream := ct.loopy.estdStreams[cstream.id] - ct.Write(cstream, nil, nil, &Options{Last: true}) // Close the stream. - if _, err := cstream.Read(header); err != io.EOF { - t.Fatalf("Client expected an EOF from the server. Got: %v", err) - } - // Sleep for a little to make sure both sides flush out their buffers. - time.Sleep(time.Millisecond * 500) - // Close down both server and client so that their internals can be read without data - // races. - ct.Close() - st.Close() - <-st.readerDone - <-st.writerDone - <-ct.readerDone - <-ct.writerDone - // Check transport flow control. - if ct.fc.limit != ct.fc.unacked+st.loopy.sendQuota { - t.Fatalf("Account mismatch: client transport inflow(%d) != client unacked(%d) + server sendQuota(%d)", ct.fc.limit, ct.fc.unacked, st.loopy.sendQuota) - } - if st.fc.limit != st.fc.unacked+ct.loopy.sendQuota { - t.Fatalf("Account mismatch: server transport inflow(%d) != server unacked(%d) + client sendQuota(%d)", st.fc.limit, st.fc.unacked, ct.loopy.sendQuota) - } - // Check stream flow control. - if int(cstream.fc.limit+cstream.fc.delta-cstream.fc.pendingData-cstream.fc.pendingUpdate) != int(st.loopy.oiws)-loopyServerStream.bytesOutStanding { - t.Fatalf("Account mismatch: client stream inflow limit(%d) + delta(%d) - pendingData(%d) - pendingUpdate(%d) != server outgoing InitialWindowSize(%d) - outgoingStream.bytesOutStanding(%d)", cstream.fc.limit, cstream.fc.delta, cstream.fc.pendingData, cstream.fc.pendingUpdate, st.loopy.oiws, loopyServerStream.bytesOutStanding) - } - if int(sstream.fc.limit+sstream.fc.delta-sstream.fc.pendingData-sstream.fc.pendingUpdate) != int(ct.loopy.oiws)-loopyClientStream.bytesOutStanding { - t.Fatalf("Account mismatch: server stream inflow limit(%d) + delta(%d) - pendingData(%d) - pendingUpdate(%d) != client outgoing InitialWindowSize(%d) - outgoingStream.bytesOutStanding(%d)", sstream.fc.limit, sstream.fc.delta, sstream.fc.pendingData, sstream.fc.pendingUpdate, ct.loopy.oiws, loopyClientStream.bytesOutStanding) - } -} - -func waitWhileTrue(t *testing.T, condition func() (bool, error)) { - var ( - wait bool - err error - ) - timer := time.NewTimer(time.Second * 5) - for { - wait, err = condition() - if wait { - select { - case <-timer.C: - t.Fatalf(err.Error()) - default: - time.Sleep(50 * time.Millisecond) - continue - } - } - if !timer.Stop() { - <-timer.C - } - break - } -} - -// A function of type writeHeaders writes out -// http status with the given stream ID using the given framer. -type writeHeaders func(*http2.Framer, uint32, int) error - -func writeOneHeader(framer *http2.Framer, sid uint32, httpStatus int) error { - var buf bytes.Buffer - henc := hpack.NewEncoder(&buf) - henc.WriteField(hpack.HeaderField{Name: ":status", Value: fmt.Sprint(httpStatus)}) - return framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) -} - -func writeTwoHeaders(framer *http2.Framer, sid uint32, httpStatus int) error { - var buf bytes.Buffer - henc := hpack.NewEncoder(&buf) - henc.WriteField(hpack.HeaderField{ - Name: ":status", - Value: fmt.Sprint(http.StatusOK), - }) - if err := framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndHeaders: true, - }); err != nil { - return err - } - buf.Reset() - henc.WriteField(hpack.HeaderField{ - Name: ":status", - Value: fmt.Sprint(httpStatus), - }) - return framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) -} - -type httpServer struct { - conn net.Conn - httpStatus int - wh writeHeaders -} - -func (s *httpServer) start(t *testing.T, lis net.Listener) { - // Launch an HTTP server to send back header with httpStatus. - go func() { - var err error - s.conn, err = lis.Accept() - if err != nil { - t.Errorf("Error accepting connection: %v", err) - return - } - // Read preface sent by client. - if _, err = io.ReadFull(s.conn, make([]byte, len(http2.ClientPreface))); err != nil { - t.Errorf("Error at server-side while reading preface from client. Err: %v", err) - return - } - reader := bufio.NewReaderSize(s.conn, defaultWriteBufSize) - writer := bufio.NewWriterSize(s.conn, defaultReadBufSize) - framer := http2.NewFramer(writer, reader) - if err = framer.WriteSettingsAck(); err != nil { - t.Errorf("Error at server-side while sending Settings ack. Err: %v", err) - return - } - var sid uint32 - // Read frames until a header is received. - for { - frame, err := framer.ReadFrame() - if err != nil { - t.Errorf("Error at server-side while reading frame. Err: %v", err) - return - } - if hframe, ok := frame.(*http2.HeadersFrame); ok { - sid = hframe.Header().StreamID - break - } - } - if err = s.wh(framer, sid, s.httpStatus); err != nil { - t.Errorf("Error at server-side while writing headers. Err: %v", err) - return - } - writer.Flush() - }() -} - -func (s *httpServer) cleanUp() { - if s.conn != nil { - s.conn.Close() - } -} - -func setUpHTTPStatusTest(t *testing.T, httpStatus int, wh writeHeaders) (stream *Stream, cleanUp func()) { - var ( - err error - lis net.Listener - server *httpServer - client ClientTransport - ) - cleanUp = func() { - if lis != nil { - lis.Close() - } - if server != nil { - server.cleanUp() - } - if client != nil { - client.Close() - } - } - defer func() { - if err != nil { - cleanUp() - } - }() - lis, err = net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen. Err: %v", err) - } - server = &httpServer{ - httpStatus: httpStatus, - wh: wh, - } - server.start(t, lis) - connectCtx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)) - client, err = newHTTP2Client(connectCtx, context.Background(), TargetInfo{Addr: lis.Addr().String()}, ConnectOptions{}, func() {}) - if err != nil { - cancel() // Do not cancel in success path. - t.Fatalf("Error creating client. Err: %v", err) - } - stream, err = client.NewStream(context.Background(), &CallHdr{Method: "bogus/method", Flush: true}) - if err != nil { - t.Fatalf("Error creating stream at client-side. Err: %v", err) - } - return -} - -func TestHTTPToGRPCStatusMapping(t *testing.T) { - for k := range httpStatusConvTab { - testHTTPToGRPCStatusMapping(t, k, writeOneHeader) - } -} - -func testHTTPToGRPCStatusMapping(t *testing.T, httpStatus int, wh writeHeaders) { - stream, cleanUp := setUpHTTPStatusTest(t, httpStatus, wh) - defer cleanUp() - want := httpStatusConvTab[httpStatus] - buf := make([]byte, 8) - _, err := stream.Read(buf) - if err == nil { - t.Fatalf("Stream.Read(_) unexpectedly returned no error. Expected stream error with code %v", want) - } - serr, ok := err.(StreamError) - if !ok { - t.Fatalf("err.(Type) = %T, want StreamError", err) - } - if want != serr.Code { - t.Fatalf("Want error code: %v, got: %v", want, serr.Code) - } -} - -func TestHTTPStatusOKAndMissingGRPCStatus(t *testing.T) { - stream, cleanUp := setUpHTTPStatusTest(t, http.StatusOK, writeOneHeader) - defer cleanUp() - buf := make([]byte, 8) - _, err := stream.Read(buf) - if err != io.EOF { - t.Fatalf("stream.Read(_) = _, %v, want _, io.EOF", err) - } - want := codes.Unknown - if stream.status.Code() != want { - t.Fatalf("Status code of stream: %v, want: %v", stream.status.Code(), want) - } -} - -func TestHTTPStatusNottOKAndMissingGRPCStatusInSecondHeader(t *testing.T) { - testHTTPToGRPCStatusMapping(t, http.StatusUnauthorized, writeTwoHeaders) -} - -// If any error occurs on a call to Stream.Read, future calls -// should continue to return that same error. -func TestReadGivesSameErrorAfterAnyErrorOccurs(t *testing.T) { - testRecvBuffer := newRecvBuffer() - s := &Stream{ - ctx: context.Background(), - buf: testRecvBuffer, - requestRead: func(int) {}, - } - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - ctxDone: s.ctx.Done(), - recv: s.buf, - }, - windowHandler: func(int) {}, - } - testData := make([]byte, 1) - testData[0] = 5 - testErr := errors.New("test error") - s.write(recvMsg{data: testData, err: testErr}) - - inBuf := make([]byte, 1) - actualCount, actualErr := s.Read(inBuf) - if actualCount != 0 { - t.Errorf("actualCount, _ := s.Read(_) differs; want 0; got %v", actualCount) - } - if actualErr.Error() != testErr.Error() { - t.Errorf("_ , actualErr := s.Read(_) differs; want actualErr.Error() to be %v; got %v", testErr.Error(), actualErr.Error()) - } - - s.write(recvMsg{data: testData, err: nil}) - s.write(recvMsg{data: testData, err: errors.New("different error from first")}) - - for i := 0; i < 2; i++ { - inBuf := make([]byte, 1) - actualCount, actualErr := s.Read(inBuf) - if actualCount != 0 { - t.Errorf("actualCount, _ := s.Read(_) differs; want %v; got %v", 0, actualCount) - } - if actualErr.Error() != testErr.Error() { - t.Errorf("_ , actualErr := s.Read(_) differs; want actualErr.Error() to be %v; got %v", testErr.Error(), actualErr.Error()) - } - } -} - -func TestPingPong1B(t *testing.T) { - runPingPongTest(t, 1) -} - -func TestPingPong1KB(t *testing.T) { - runPingPongTest(t, 1024) -} - -func TestPingPong64KB(t *testing.T) { - runPingPongTest(t, 65536) -} - -func TestPingPong1MB(t *testing.T) { - runPingPongTest(t, 1048576) -} - -//This is a stress-test of flow control logic. -func runPingPongTest(t *testing.T, msgSize int) { - server, client := setUp(t, 0, 0, pingpong) - defer server.stop() - defer client.Close() - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - if len(server.conns) == 0 { - return true, fmt.Errorf("timed out while waiting for server transport to be created") - } - return false, nil - }) - ct := client.(*http2Client) - stream, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Failed to create stream. Err: %v", err) - } - msg := make([]byte, msgSize) - outgoingHeader := make([]byte, 5) - outgoingHeader[0] = byte(0) - binary.BigEndian.PutUint32(outgoingHeader[1:], uint32(msgSize)) - opts := &Options{} - incomingHeader := make([]byte, 5) - done := make(chan struct{}) - go func() { - timer := time.NewTimer(time.Second * 5) - <-timer.C - close(done) - }() - for { - select { - case <-done: - ct.Write(stream, nil, nil, &Options{Last: true}) - if _, err := stream.Read(incomingHeader); err != io.EOF { - t.Fatalf("Client expected EOF from the server. Got: %v", err) - } - return - default: - if err := ct.Write(stream, outgoingHeader, msg, opts); err != nil { - t.Fatalf("Error on client while writing message. Err: %v", err) - } - if _, err := stream.Read(incomingHeader); err != nil { - t.Fatalf("Error on client while reading data header. Err: %v", err) - } - sz := binary.BigEndian.Uint32(incomingHeader[1:]) - recvMsg := make([]byte, int(sz)) - if _, err := stream.Read(recvMsg); err != nil { - t.Fatalf("Error on client while reading data. Err: %v", err) - } - } - } -} - -type tableSizeLimit struct { - mu sync.Mutex - limits []uint32 -} - -func (t *tableSizeLimit) add(limit uint32) { - t.mu.Lock() - t.limits = append(t.limits, limit) - t.mu.Unlock() -} - -func (t *tableSizeLimit) getLen() int { - t.mu.Lock() - defer t.mu.Unlock() - return len(t.limits) -} - -func (t *tableSizeLimit) getIndex(i int) uint32 { - t.mu.Lock() - defer t.mu.Unlock() - return t.limits[i] -} - -func TestHeaderTblSize(t *testing.T) { - limits := &tableSizeLimit{} - updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { - e.SetMaxDynamicTableSizeLimit(v) - limits.add(v) - } - defer func() { - updateHeaderTblSize = func(e *hpack.Encoder, v uint32) { - e.SetMaxDynamicTableSizeLimit(v) - } - }() - - server, ct := setUp(t, 0, math.MaxUint32, normal) - defer ct.Close() - defer server.stop() - _, err := ct.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("failed to open stream: %v", err) - } - - var svrTransport ServerTransport - var i int - for i = 0; i < 1000; i++ { - server.mu.Lock() - if len(server.conns) != 0 { - server.mu.Unlock() - break - } - server.mu.Unlock() - time.Sleep(10 * time.Millisecond) - continue - } - if i == 1000 { - t.Fatalf("unable to create any server transport after 10s") - } - - for st := range server.conns { - svrTransport = st - break - } - svrTransport.(*http2Server).controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingHeaderTableSize, - Val: uint32(100), - }, - }, - }) - - for i = 0; i < 1000; i++ { - if limits.getLen() != 1 { - time.Sleep(10 * time.Millisecond) - continue - } - if val := limits.getIndex(0); val != uint32(100) { - t.Fatalf("expected limits[0] = 100, got %d", val) - } - break - } - if i == 1000 { - t.Fatalf("expected len(limits) = 1 within 10s, got != 1") - } - - ct.(*http2Client).controlBuf.put(&outgoingSettings{ - ss: []http2.Setting{ - { - ID: http2.SettingHeaderTableSize, - Val: uint32(200), - }, - }, - }) - - for i := 0; i < 1000; i++ { - if limits.getLen() != 2 { - time.Sleep(10 * time.Millisecond) - continue - } - if val := limits.getIndex(1); val != uint32(200) { - t.Fatalf("expected limits[1] = 200, got %d", val) - } - break - } - if i == 1000 { - t.Fatalf("expected len(limits) = 2 within 10s, got != 2") - } -} diff --git a/examples/google.golang.org/grpc/version.go b/examples/google.golang.org/grpc/version.go deleted file mode 100755 index 7f124fb..0000000 --- a/examples/google.golang.org/grpc/version.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * - * 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. - * - */ - -package grpc - -// Version is the current grpc version. -const Version = "1.13.0" diff --git a/examples/google.golang.org/grpc/vet.sh b/examples/google.golang.org/grpc/vet.sh deleted file mode 100755 index 079bc28..0000000 --- a/examples/google.golang.org/grpc/vet.sh +++ /dev/null @@ -1,94 +0,0 @@ -#!/bin/bash - -if [[ `uname -a` = *"Darwin"* ]]; then - echo "It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047" - exit 1 -fi - -set -ex # Exit on error; debugging enabled. -set -o pipefail # Fail a pipe if any sub-command fails. - -die() { - echo "$@" >&2 - exit 1 -} - -PATH="$GOPATH/bin:$GOROOT/bin:$PATH" - -# Check proto in manual runs or cron runs. -if [[ "$TRAVIS" != "true" || "$TRAVIS_EVENT_TYPE" = "cron" ]]; then - check_proto="true" -fi - -if [ "$1" = "-install" ]; then - go get -d \ - google.golang.org/grpc/... - go get -u \ - github.com/golang/lint/golint \ - golang.org/x/tools/cmd/goimports \ - honnef.co/go/tools/cmd/staticcheck \ - github.com/client9/misspell/cmd/misspell \ - github.com/golang/protobuf/protoc-gen-go - if [[ "$check_proto" = "true" ]]; then - if [[ "$TRAVIS" = "true" ]]; then - PROTOBUF_VERSION=3.3.0 - PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip - pushd /home/travis - wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME} - unzip ${PROTOC_FILENAME} - bin/protoc --version - popd - elif ! which protoc > /dev/null; then - die "Please install protoc into your path" - fi - fi - exit 0 -elif [[ "$#" -ne 0 ]]; then - die "Unknown argument(s): $*" -fi - -# TODO: Remove this check and the mangling below once "context" is imported -# directly. -if git status --porcelain | read; then - die "Uncommitted or untracked files found; commit changes first" -fi - -git ls-files "*.go" | xargs grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" 2>&1 | tee /dev/stderr | (! read) -git ls-files "*.go" | xargs grep -l '"unsafe"' 2>&1 | (! grep -v '_test.go') | tee /dev/stderr | (! read) -git ls-files "*.go" | xargs grep -l '"math/rand"' 2>&1 | (! grep -v '^examples\|^stress\|grpcrand') | tee /dev/stderr | (! read) -gofmt -s -d -l . 2>&1 | tee /dev/stderr | (! read) -goimports -l . 2>&1 | tee /dev/stderr | (! read) -golint ./... 2>&1 | (grep -vE "(_mock|\.pb)\.go:" || true) | tee /dev/stderr | (! read) - -# Undo any edits made by this script. -cleanup() { - git reset --hard HEAD -} -trap cleanup EXIT - -# Rewrite golang.org/x/net/context -> context imports (see grpc/grpc-go#1484). -# TODO: Remove this mangling once "context" is imported directly (grpc/grpc-go#711). -git ls-files "*.go" | xargs sed -i 's:"golang.org/x/net/context":"context":' -set +o pipefail -# TODO: Stop filtering pb.go files once golang/protobuf#214 is fixed. -go tool vet -all . 2>&1 | grep -vE '(clientconn|transport\/transport_test).go:.*cancel (function|var)' | grep -vF '.pb.go:' | tee /dev/stderr | (! read) -set -o pipefail -git reset --hard HEAD - -if [[ "$check_proto" = "true" ]]; then - PATH="/home/travis/bin:$PATH" make proto && \ - git status --porcelain 2>&1 | (! read) || \ - (git status; git --no-pager diff; exit 1) -fi - -# TODO(menghanl): fix errors in transport_test. -staticcheck -ignore ' -google.golang.org/grpc/transport/transport_test.go:SA2002 -google.golang.org/grpc/benchmark/benchmain/main.go:SA1019 -google.golang.org/grpc/stats/stats_test.go:SA1019 -google.golang.org/grpc/test/end2end_test.go:SA1019 -google.golang.org/grpc/balancer_test.go:SA1019 -google.golang.org/grpc/balancer.go:SA1019 -google.golang.org/grpc/clientconn_test.go:SA1019 -' ./... -misspell -error .